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            // Every relay endpoint answers from the relay's own queue, so one the relay was started
590            // against serves it as long as it answers, whichever watcher now owns the record (two
591            // watchers on one mail root swapped it per send, and each swap started a relay).
592            if record.endpoint == endpoint
593                || crate::relay_endpoint::endpoint_answers(&record.endpoint)
594            {
595                return Ok(runtime);
596            }
597            // Started against an endpoint no longer serving, its requests
598            // would go nowhere: it ends, and a new one starts.
599            end_relay_process(&spec.name);
600        }
601        // The replaced runtime leaves the daemon's table too: ending only its process left its
602        // listener and live receipt behind for every client to poll (t_f3f102db t_4f29b43e).
603        if !record.connection.is_empty() {
604            machine_rpc(
605                &spec.program,
606                "runtimes.close",
607                &json!({ "connection": record.connection, "runtime_id": record.runtime_id }),
608            )
609            .await
610            .ok();
611        }
612    }
613    let params = json!({
614        "harness": "claude-code",
615        "launch": {
616            "program": "claude",
617            "arguments": relay_arguments(spec),
618            "env": relay_environment(spec, &endpoint),
619        },
620        "cwd": spec.paths.directory,
621    });
622    let result = machine_rpc(&spec.program, "runtimes.start", &params).await?;
623    let runtime_id = result
624        .pointer("/handle/runtime_id")
625        .and_then(Value::as_str)
626        .ok_or_else(|| format!("the machine daemon did not start the relay: {result}"))?
627        .to_string();
628    let connection = result
629        .get("connection")
630        .and_then(Value::as_str)
631        .unwrap_or_default()
632        .to_string();
633    std::fs::write(
634        &spec.paths.record,
635        serde_json::to_vec(&Record {
636            runtime_id: runtime_id.clone(),
637            endpoint,
638            connection,
639        })
640        .unwrap_or_default(),
641    )
642    .map_err(|error| error.to_string())?;
643    crate::runtime_mail::controlled_runtime("claude-code", &runtime_id)
644        .ok_or_else(|| "the relay started but registered no live runtime".to_string())
645}
646
647/// The relays of sessions no longer running, retired: each relay's runtime (a `claude --print` under
648/// `supercode harness serve`, some hundreds of MB) is closed through the machine daemon that
649/// started it (`runtimes.close`, so the daemon's own table forgets it: a relay process ended behind
650/// its back left sends failing until the daemon restarted), and its folder removed. A relay speaks
651/// for one session and receives the replies to what that session sent; once the session has ended,
652/// nothing reaches it. A relay for a board or an operator, which is not a session, is kept; so is a
653/// live relay recorded before its connection was kept, which no door can close cleanly.
654/// Answers the represented addresses whose relays were retired.
655pub async fn retire_relays_of_ended_sessions(homes: &HarnessHomes) -> Vec<String> {
656    #[derive(Deserialize)]
657    struct Record {
658        runtime_id: String,
659        #[serde(default)]
660        connection: String,
661    }
662    let Ok(entries) = std::fs::read_dir(mail_root().join("relays")) else {
663        return Vec::new();
664    };
665    let running: std::collections::HashSet<String> = crate::mail_route::LiveSessions::read(homes)
666        .all()
667        .iter()
668        .map(|session| session.address.to_string())
669        .collect();
670    let Ok(program) = supercode_program() else {
671        return Vec::new();
672    };
673    let mut retired = Vec::new();
674    for entry in entries.flatten() {
675        let paths = RelayPaths::in_directory(entry.path());
676        // the address the relay speaks for, as its inbound hook names it
677        let Some(represented) = std::fs::read_to_string(&paths.settings)
678            .ok()
679            .and_then(|text| {
680                let from = text.find("relay-inbound '")? + "relay-inbound '".len();
681                let len = text[from..].find('\'')?;
682                MailAddress::parse(&text[from..from + len]).ok()
683            })
684        else {
685            continue;
686        };
687        if matches!(represented.harness.as_str(), "board" | "operator")
688            || running.contains(&represented.to_string())
689        {
690            continue;
691        }
692        let record = std::fs::read(&paths.record)
693            .ok()
694            .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok());
695        let alive = record.as_ref().is_some_and(|record| {
696            crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id).is_some()
697        });
698        if alive {
699            let (connection, runtime_id) = record
700                .map(|record| (record.connection, record.runtime_id))
701                .unwrap_or_default();
702            if connection.is_empty()
703                || machine_rpc(
704                    &program,
705                    "runtimes.close",
706                    &json!({ "connection": connection, "runtime_id": runtime_id }),
707                )
708                .await
709                .is_err()
710            {
711                continue;
712            }
713        }
714        if std::fs::remove_dir_all(&paths.directory).is_ok() {
715            retired.push(represented.to_string());
716        }
717    }
718    retired
719}
720
721/// End the Claude process registered under the relay name `name`.
722fn end_relay_process(name: &str) {
723    let registry = registry_dir(&HarnessHomes::default());
724    for session in read_registry(&registry) {
725        #[cfg(unix)]
726        if session.name == name {
727            // SAFETY: `kill` only sends a signal to the relay's own process.
728            unsafe {
729                libc::kill(session.pid as libc::pid_t, libc::SIGTERM);
730            }
731        }
732    }
733}
734
735/// The relay endpoint's base URL. The machine daemon's watcher serves it;
736/// the daemon is started when it is not running.
737async fn relay_endpoint(program: &Path) -> Result<String, String> {
738    if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
739        return Ok(url);
740    }
741    ensure_machine_daemon(program).await?;
742    let deadline = Instant::now() + Duration::from_secs(10);
743    while Instant::now() < deadline {
744        if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
745            return Ok(url);
746        }
747        tokio::time::sleep(Duration::from_millis(200)).await;
748    }
749    Err(
750        "the relay endpoint is not answering; the machine daemon's `supercode message watch` \
751         serves it (see mail/machine-daemon.log)"
752            .into(),
753    )
754}
755
756/// One `harness.v1` call into this machine's daemon (`supercode teams rpc`),
757/// starting the daemon when it is not running.
758pub async fn machine_rpc(program: &Path, method: &str, params: &Value) -> Result<Value, String> {
759    let call = || {
760        let mut command = tokio::process::Command::new(program);
761        command
762            .args(["teams", "rpc", method, &params.to_string()])
763            .stdin(std::process::Stdio::null())
764            .stdout(std::process::Stdio::piped())
765            .stderr(std::process::Stdio::piped());
766        command.output()
767    };
768    let output = call().await.map_err(|error| error.to_string())?;
769    if output.status.success() {
770        return serde_json::from_slice(&output.stdout)
771            .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
772    }
773    // Not running: start it (this OS user's own daemon, no Teams context
774    // needed) and ask once more.
775    ensure_machine_daemon(program).await?;
776    let output = call().await.map_err(|error| error.to_string())?;
777    if output.status.success() {
778        return serde_json::from_slice(&output.stdout)
779            .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
780    }
781    Err(error_line(&String::from_utf8_lossy(&output.stderr)))
782}
783
784/// Start this OS user's machine daemon when it is not answering. It hosts
785/// relays (in its `harness serve`) and the idle watcher.
786pub async fn ensure_machine_daemon(program: &Path) -> Result<(), String> {
787    let describe = || {
788        tokio::process::Command::new(program)
789            .args(["teams", "describe"])
790            .stdin(std::process::Stdio::null())
791            .stdout(std::process::Stdio::null())
792            .stderr(std::process::Stdio::null())
793            .status()
794    };
795    if describe().await.is_ok_and(|status| status.success()) {
796        return Ok(());
797    }
798    // A service manager runs this user's daemon (a connector, or the machine
799    // unit): it is between restarts, and a daemon started here would take the
800    // socket and lock the service's daemon out. Wait for the service instead.
801    if crate::teams::service_owns_daemon() {
802        for _ in 0..100 {
803            tokio::time::sleep(Duration::from_millis(200)).await;
804            if describe().await.is_ok_and(|status| status.success()) {
805                return Ok(());
806            }
807        }
808        return Err(
809            "this machine's daemon is run by its service manager and did not answer within 20 seconds; \
810             see `supercode teams status`"
811                .into(),
812        );
813    }
814    let root = mail_root();
815    std::fs::create_dir_all(&root).map_err(|error| error.to_string())?;
816    let log = std::fs::OpenOptions::new()
817        .create(true)
818        .append(true)
819        .open(root.join("machine-daemon.log"))
820        .map_err(|error| error.to_string())?;
821    let mut command = std::process::Command::new(program);
822    command
823        .args(["teams", "machine", "start", "--supercode"])
824        .arg(program)
825        .stdin(std::process::Stdio::null())
826        .stdout(log.try_clone().map_err(|error| error.to_string())?)
827        .stderr(log);
828    #[cfg(unix)]
829    {
830        use std::os::unix::process::CommandExt;
831        // Its own process group, so the caller's exit does not take the
832        // daemon (and every relay) with it.
833        command.process_group(0);
834    }
835    command
836        .spawn()
837        .map_err(|error| format!("could not start the machine daemon: {error}"))?;
838    for _ in 0..50 {
839        tokio::time::sleep(Duration::from_millis(200)).await;
840        if describe().await.is_ok_and(|status| status.success()) {
841            return Ok(());
842        }
843    }
844    Err(format!(
845        "the machine daemon did not start within 10 seconds; see {}",
846        root.join("machine-daemon.log").display()
847    ))
848}
849
850/// The one line of a failed command's stderr an agent can act on.
851fn error_line(stderr: &str) -> String {
852    let lines: Vec<&str> = stderr
853        .lines()
854        .map(str::trim)
855        .filter(|line| !line.is_empty())
856        .collect();
857    lines
858        .iter()
859        .find(|line| line.starts_with("Error") || line.starts_with("error"))
860        .or(lines.last())
861        .copied()
862        .unwrap_or("the machine daemon failed without saying why")
863        .chars()
864        .take(300)
865        .collect()
866}
867
868/// An exclusive lock on a relay's sends, released on drop.
869struct SendLock {
870    _file: std::fs::File,
871}
872
873impl SendLock {
874    fn acquire(path: &Path) -> std::io::Result<Self> {
875        let file = std::fs::OpenOptions::new()
876            .create(true)
877            .truncate(false)
878            .write(true)
879            .open(path)?;
880        #[cfg(unix)]
881        {
882            use std::os::unix::io::AsRawFd;
883            // SAFETY: flock on a descriptor this function owns; the lock is
884            // released when the file is dropped.
885            if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
886                return Err(std::io::Error::last_os_error());
887            }
888        }
889        Ok(Self { _file: file })
890    }
891}
892
893/// File one inbound prompt in `represented`'s mailbox. `last_sent` maps a
894/// Claude session name to the newest message this relay sent it, for
895pub fn file_inbound_prompt(
896    homes: &HarnessHomes,
897    represented: &MailAddress,
898    prompt: &str,
899    last_sent: Option<&HashMap<String, String>>,
900) {
901    match parse_inbound_text(prompt) {
902        Some(RelayEvent::Peer(native)) => {
903            let registry = read_registry(&registry_dir(homes));
904            let sender = resolve_native_sender(&registry, &native.from);
905            let in_reply_to = sender
906                .as_ref()
907                .and_then(|session| last_sent.and_then(|sent| sent.get(&session.name).cloned()));
908            file_inbound(represented, &native, sender.as_ref(), in_reply_to);
909        }
910        Some(RelayEvent::IdleNotice(text) | RelayEvent::DeliveryNotice(text)) => {
911            file_notice(represented, &text);
912        }
913        _ => {}
914    }
915}
916/// Recognize an inbound peer envelope or notice in the text Claude handed a
917/// relay.
918pub fn parse_inbound_text(text: &str) -> Option<RelayEvent> {
919    let trimmed = text.trim_start();
920    if trimmed.starts_with(NATIVE_IDLE_NOTICE) {
921        return Some(RelayEvent::IdleNotice(trimmed.to_string()));
922    }
923    if trimmed.starts_with(NATIVE_DELIVERY_NOTICE) {
924        return Some(RelayEvent::DeliveryNotice(trimmed.to_string()));
925    }
926    if !trimmed.starts_with(NATIVE_PEER_PREAMBLE) && !trimmed.starts_with(NATIVE_PEER_OPENING) {
927        return None;
928    }
929    let start = text.find(NATIVE_PEER_OPENING)?;
930    let header_end = start + text[start..].find(">\n")?;
931    let header = &text[start + NATIVE_PEER_OPENING.len()..header_end];
932    let body_start = header_end + 2;
933    // The body is not escaped by Claude; the closing tag is the LAST one, and
934    // the fixed paragraph after it never contains the tag.
935    let body_end = text.rfind(&format!("\n{NATIVE_PEER_CLOSING}"))?;
936    if body_end < body_start {
937        return None;
938    }
939    let attributes = parse_attributes(header);
940    Some(RelayEvent::Peer(NativeEnvelope {
941        from: attributes.get("from")?.clone(),
942        from_name: attributes.get("from-name").cloned(),
943        body: text[body_start..body_end].to_string(),
944    }))
945}
946fn parse_attributes(header: &str) -> BTreeMap<String, String> {
947    let mut attributes = BTreeMap::new();
948    let mut rest = header;
949    while let Some(equals) = rest.find("=\"") {
950        let key = rest[..equals].trim().to_string();
951        let value_start = equals + 2;
952        let Some(length) = rest[value_start..].find('"') else {
953            break;
954        };
955        attributes.insert(key, rest[value_start..value_start + length].to_string());
956        rest = &rest[value_start + length + 1..];
957    }
958    attributes
959}
960/// Deliver mail to the session a relay speaks for. When it lives on another
961/// machine and Teams cannot take the message there, it is kept in this
962/// machine's copy of that mailbox (never dropped) and the failure is written
963fn deliver_home(represented: &MailAddress, envelope: &Envelope) {
964    if let Err(error) = crate::mailbox::deliver_to(represented, envelope) {
965        eprintln!(
966            "could not deliver {} to {represented}: {error}; kept in this machine's mailbox for it",
967            envelope.id
968        );
969        if let Ok(mailbox) = crate::mailbox::Mailbox::open(&mail_root(), represented) {
970            mailbox.deliver(envelope).ok();
971        }
972        return;
973    }
974    // Filed; now hand it to its session by the session's own door, as any
975    // sender's message is (a Claude session gets it at its next tool round).
976    // That can take as long as a relay send, which this hook must not wait
977    // on, so a detached `message push` does it.
978    if represented.machine == crate::mailbox::local_machine_name() {
979        if let Ok(program) = supercode_program() {
980            std::process::Command::new(program)
981                .args(["message", "push", &represented.to_string(), &envelope.id])
982                .stdin(std::process::Stdio::null())
983                .stdout(std::process::Stdio::null())
984                .stderr(std::process::Stdio::null())
985                .spawn()
986                .ok();
987        }
988    }
989}
990fn file_inbound(
991    represented: &MailAddress,
992    native: &NativeEnvelope,
993    sender: Option<&ClaudePeerSession>,
994    in_reply_to: Option<String>,
995) {
996    // The replying Claude session runs beside the relay, on this machine —
997    // not on the machine of the session the relay speaks for.
998    let machine = crate::mailbox::local_machine_name();
999    let (from, from_name) = match sender {
1000        Some(session) => (
1001            MailAddress::new(&machine, "claude-code", &session.session_id),
1002            format!("{}@{machine}", session.name),
1003        ),
1004        None => (
1005            MailAddress::new(&machine, "claude-code", "unknown"),
1006            native
1007                .from_name
1008                .clone()
1009                .unwrap_or_else(|| "an unknown Claude session".into()),
1010        ),
1011    };
1012    let Ok(from) = from else { return };
1013    let Ok(mut envelope) = Envelope::new(
1014        from,
1015        from_name,
1016        MailKind::Peer,
1017        ReplyVia::Command,
1018        native.body.clone(),
1019    ) else {
1020        return;
1021    };
1022    envelope.native_from = Some(native.from.clone());
1023    if let Some(in_reply_to) = in_reply_to {
1024        envelope.thread = crate::mailbox::thread_of_reply(Some(&in_reply_to));
1025        envelope.in_reply_to = Some(in_reply_to);
1026        envelope.in_reply_to_inferred = true;
1027    }
1028    // The session a relay speaks for may be on another machine; its mail goes
1029    // home through Teams.
1030    deliver_home(represented, &envelope);
1031}
1032fn file_notice(represented: &MailAddress, text: &str) {
1033    let Ok(from) = MailAddress::new(
1034        crate::mailbox::local_machine_name(),
1035        "claude-code",
1036        "notice",
1037    ) else {
1038        return;
1039    };
1040    let Ok(envelope) = Envelope::new(
1041        from,
1042        "Claude Code",
1043        MailKind::Notice,
1044        ReplyVia::None,
1045        text.to_string(),
1046    ) else {
1047        return;
1048    };
1049    // The session a relay speaks for may be on another machine; its mail goes
1050    // home through Teams.
1051    deliver_home(represented, &envelope);
1052}
1053/// The `supercode` program that the relay hooks and the machine daemon run:
1054/// this process when it is `supercode` (the CLI, `supercode harness serve`),
1055pub fn supercode_program() -> std::io::Result<PathBuf> {
1056    let current = std::env::current_exe()?;
1057    if current.file_stem().and_then(|stem| stem.to_str()) == Some("supercode") {
1058        return Ok(current);
1059    }
1060    std::env::var_os("PATH")
1061        .iter()
1062        .flat_map(std::env::split_paths)
1063        .map(|directory| directory.join("supercode"))
1064        .find(|candidate| candidate.is_file())
1065        .ok_or_else(|| {
1066            std::io::Error::new(
1067                std::io::ErrorKind::NotFound,
1068                "the supercode program is not on PATH; Claude relays and the machine daemon need it",
1069            )
1070        })
1071}