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