1use 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
43pub const RELAY_MODEL: &str = "haiku";
46
47pub const RELAY_NAME_PREFIX: &str = "sc-";
49
50pub const RELAY_STATUS_LINE: &str = "relay, not the session's status";
53
54pub const SEND_TIMEOUT: Duration = Duration::from_secs(90);
56
57const RELAY_TOOLS: &str = "ListAgents,SendMessage";
59
60const NATIVE_PEER_PREAMBLE: &str = "Another Claude session sent a message:";
64const 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
70pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct QueuedSend {
82 pub to: String,
84 pub message: String,
86}
87
88pub 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
151pub fn gate_denial(reason: &str) -> Value {
153 json!({
154 "hookSpecificOutput": {
155 "hookEventName": "PreToolUse",
156 "permissionDecision": "deny",
157 "permissionDecisionReason": reason,
158 }
159 })
160}
161
162#[derive(Debug, Clone)]
165pub struct RelayPaths {
166 pub directory: PathBuf,
168 pub queue: PathBuf,
170 pub receipt: PathBuf,
172 pub settings: PathBuf,
174 pub record: PathBuf,
176 pub sent: PathBuf,
178 pub lock: PathBuf,
180}
181
182impl RelayPaths {
183 pub fn new(root: &Path, relay_name: &str) -> Self {
185 let hash = blake3::hash(relay_name.as_bytes()).to_hex();
186 Self::in_directory(root.join("relays").join(&hash[..24]))
187 }
188
189 pub fn in_directory(directory: PathBuf) -> Self {
191 Self {
192 queue: directory.join("queue.json"),
193 receipt: directory.join("receipt.json"),
194 settings: directory.join("settings.json"),
195 record: directory.join("relay.json"),
196 sent: directory.join("sent.json"),
197 lock: directory.join("send.lock"),
198 directory,
199 }
200 }
201
202 pub fn last_sent(&self) -> HashMap<String, String> {
204 std::fs::read(&self.sent)
205 .ok()
206 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
207 .unwrap_or_default()
208 }
209}
210
211#[derive(Debug, Clone)]
213pub struct RelaySpec {
214 pub represented: MailAddress,
216 pub represented_name: String,
218 pub name: String,
220 pub paths: RelayPaths,
222 pub program: PathBuf,
224}
225
226impl RelaySpec {
227 pub fn for_sender(represented: &MailAddress, represented_name: &str) -> std::io::Result<Self> {
229 let base = represented_name
230 .split('@')
231 .next()
232 .unwrap_or(represented_name);
233 let name = relay_name(base, &represented.machine);
234 Ok(Self {
235 represented: represented.clone(),
236 represented_name: represented_name.to_string(),
237 paths: RelayPaths::new(&mail_root(), &name),
238 name,
239 program: supercode_program()?,
240 })
241 }
242}
243
244pub fn relay_arguments(spec: &RelaySpec) -> Vec<String> {
250 vec![
251 "--print".into(),
252 "--input-format".into(),
253 "stream-json".into(),
254 "--output-format".into(),
255 "stream-json".into(),
256 "--verbose".into(),
257 "--permission-prompt-tool".into(),
258 "stdio".into(),
259 "--model".into(),
260 RELAY_MODEL.into(),
261 "--name".into(),
262 spec.name.clone(),
263 "--permission-mode".into(),
264 "bypassPermissions".into(),
265 "--setting-sources".into(),
266 "project".into(),
267 "--settings".into(),
268 spec.paths.settings.to_string_lossy().into_owned(),
269 "--tools".into(),
270 RELAY_TOOLS.into(),
271 "--no-session-persistence".into(),
272 ]
273}
274
275pub fn relay_environment(spec: &RelaySpec, endpoint: &str) -> BTreeMap<String, String> {
279 let key = spec
280 .paths
281 .directory
282 .file_name()
283 .map(|name| name.to_string_lossy().into_owned())
284 .unwrap_or_default();
285 BTreeMap::from([
286 ("ANTHROPIC_BASE_URL".to_string(), endpoint.to_string()),
287 ("ANTHROPIC_API_KEY".to_string(), key),
288 (
289 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
290 "1".to_string(),
291 ),
292 ])
293}
294
295pub fn relay_settings(spec: &RelaySpec) -> Value {
297 let program = shell_quote(&spec.program.to_string_lossy());
298 let directory = shell_quote(&spec.paths.directory.to_string_lossy());
299 let represented = shell_quote(&spec.represented.to_string());
300 let command = |verb: &str| format!("{program} message {verb} {directory}");
301 json!({
302 "hooks": {
303 "PreToolUse": [{
305 "matcher": ".*",
306 "hooks": [{"type": "command", "command": command("gate")}],
307 }],
308 "PostToolUse": [{
309 "matcher": "SendMessage",
310 "hooks": [{"type": "command", "command": command("relay-receipt")}],
311 }],
312 "Stop": [{
313 "hooks": [{"type": "command", "command": command("relay-receipt")}],
314 }],
315 "UserPromptSubmit": [{
316 "hooks": [{
317 "type": "command",
318 "command": format!("{program} message relay-inbound {represented} {directory}"),
319 }],
320 }],
321 }
322 })
323}
324
325fn shell_quote(value: &str) -> String {
326 format!("'{}'", value.replace('\'', "'\\''"))
327}
328
329pub fn is_inbound_prompt(prompt: &str) -> bool {
332 let trimmed = prompt.trim_start();
333 trimmed.starts_with(NATIVE_PEER_OPENING)
334 || trimmed.starts_with(NATIVE_IDLE_NOTICE)
335 || trimmed.starts_with(NATIVE_DELIVERY_NOTICE)
336}
337
338pub fn inbound_block() -> Value {
340 json!({
341 "decision": "block",
342 "reason": "filed in the mailbox of the session this relay speaks for",
343 })
344}
345
346pub fn send_turn(send: &QueuedSend) -> String {
348 format!(
349 "Send one message with SendMessage.\n\
350 to: {}\n\
351 message: the exact text between the markers, without the markers\n\
352 ---BEGIN MESSAGE---\n{}\n---END MESSAGE---",
353 send.to, send.message
354 )
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
359pub struct NativeEnvelope {
360 pub from: String,
362 pub from_name: Option<String>,
364 pub body: String,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq)]
370pub enum RelayEvent {
371 Peer(NativeEnvelope),
373 IdleNotice(String),
375 DeliveryNotice(String),
377}
378
379pub fn resolve_native_sender(
381 registry: &[ClaudePeerSession],
382 native_from: &str,
383) -> Option<ClaudePeerSession> {
384 let socket = native_from.strip_prefix("uds:").unwrap_or(native_from);
385 registry
386 .iter()
387 .find(|session| session.socket_path.to_string_lossy() == socket)
388 .cloned()
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(rename_all = "snake_case", tag = "outcome")]
394pub enum RelayReceipt {
395 Delivered {
397 detail: String,
399 native_msg_id: Option<String>,
401 },
402 Failed {
404 detail: String,
406 },
407}
408
409pub fn read_receipt(value: &Value) -> RelayReceipt {
412 if let Some(reason) = value.get("denied").and_then(Value::as_str) {
413 return RelayReceipt::Failed {
414 detail: format!("the relay's gate refused the send: {reason}"),
415 };
416 }
417 if value.get("turn_ended").and_then(Value::as_bool) == Some(true) {
418 return RelayReceipt::Failed {
419 detail: "the Claude relay ended its turn without sending; nothing was sent".into(),
420 };
421 }
422 let response = value.get("tool_response").cloned().unwrap_or(Value::Null);
423 let parsed = match &response {
424 Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(response.clone()),
425 Value::Array(blocks) => blocks
426 .iter()
427 .find_map(|block| block.get("text").and_then(Value::as_str))
428 .and_then(|text| serde_json::from_str::<Value>(text).ok())
429 .unwrap_or(response.clone()),
430 _ => response.clone(),
431 };
432 if parsed.get("success").and_then(Value::as_bool) != Some(true) {
433 return RelayReceipt::Failed {
434 detail: format!("Claude did not report the send as successful: {parsed}"),
435 };
436 }
437 RelayReceipt::Delivered {
438 detail: parsed
439 .get("message")
440 .and_then(Value::as_str)
441 .unwrap_or_default()
442 .to_string(),
443 native_msg_id: parsed
444 .get("msg_id")
445 .and_then(Value::as_str)
446 .map(str::to_string),
447 }
448}
449
450pub async fn send_through_relay(
455 sender: &MailAddress,
456 sender_name: &str,
457 to: &str,
458 message: String,
459 message_id: &str,
460) -> RelayReceipt {
461 let failed = |detail: String| RelayReceipt::Failed { detail };
462 let spec = match RelaySpec::for_sender(sender, sender_name) {
463 Ok(spec) => spec,
464 Err(error) => return failed(error.to_string()),
465 };
466 if let Err(error) = std::fs::create_dir_all(&spec.paths.directory) {
467 return failed(error.to_string());
468 }
469 let lock = match tokio::task::spawn_blocking({
471 let path = spec.paths.lock.clone();
472 move || SendLock::acquire(&path)
473 })
474 .await
475 {
476 Ok(Ok(lock)) => lock,
477 Ok(Err(error)) => return failed(format!("could not take the relay's send lock: {error}")),
478 Err(error) => return failed(error.to_string()),
479 };
480 let runtime = match ensure_relay_runtime(&spec).await {
481 Ok(runtime) => runtime,
482 Err(detail) => return failed(detail),
483 };
484 let queued = QueuedSend {
485 to: to.to_string(),
486 message,
487 };
488 std::fs::remove_file(&spec.paths.receipt).ok();
489 if let Err(error) = std::fs::write(
490 &spec.paths.queue,
491 serde_json::to_vec(&queued).unwrap_or_default(),
492 ) {
493 return failed(error.to_string());
494 }
495 let delivered =
496 crate::runtime_mail::deliver_to_runtime(&runtime, send_turn(&queued), true).await;
497 let receipt = match delivered {
498 Err(detail) => failed(format!("could not reach the Claude relay: {detail}")),
499 Ok(_) => wait_for_receipt(&spec.paths.receipt).await,
500 };
501 std::fs::remove_file(&spec.paths.queue).ok();
502 if matches!(receipt, RelayReceipt::Delivered { .. }) {
503 let mut sent = spec.paths.last_sent();
504 sent.insert(to.to_string(), message_id.to_string());
505 std::fs::write(
506 &spec.paths.sent,
507 serde_json::to_vec(&sent).unwrap_or_default(),
508 )
509 .ok();
510 }
511 drop(lock);
512 receipt
513}
514
515async fn wait_for_receipt(path: &Path) -> RelayReceipt {
516 let started = Instant::now();
517 while started.elapsed() < SEND_TIMEOUT {
518 if let Some(value) = std::fs::read(path)
519 .ok()
520 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
521 {
522 return read_receipt(&value);
523 }
524 tokio::time::sleep(Duration::from_millis(200)).await;
525 }
526 RelayReceipt::Failed {
527 detail: format!(
528 "the Claude relay did not confirm the send within {} seconds; it may still arrive",
529 SEND_TIMEOUT.as_secs()
530 ),
531 }
532}
533
534async fn ensure_relay_runtime(
537 spec: &RelaySpec,
538) -> Result<crate::live_runtime::LiveRuntimeRecord, String> {
539 #[derive(Serialize, Deserialize)]
540 struct Record {
541 runtime_id: String,
542 #[serde(default)]
543 endpoint: String,
544 }
545 let endpoint = relay_endpoint(&spec.program).await?;
546 if let Some(record) = std::fs::read(&spec.paths.record)
547 .ok()
548 .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok())
549 {
550 if let Some(runtime) =
551 crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id)
552 {
553 if record.endpoint == endpoint {
554 return Ok(runtime);
555 }
556 end_relay_process(&spec.name);
559 }
560 }
561 std::fs::write(
562 &spec.paths.settings,
563 serde_json::to_vec_pretty(&relay_settings(spec)).unwrap_or_default(),
564 )
565 .map_err(|error| error.to_string())?;
566 let params = json!({
567 "harness": "claude-code",
568 "launch": {
569 "program": "claude",
570 "arguments": relay_arguments(spec),
571 "env": relay_environment(spec, &endpoint),
572 },
573 "cwd": spec.paths.directory,
574 });
575 let result = machine_rpc(&spec.program, "runtimes.start", ¶ms).await?;
576 let runtime_id = result
577 .pointer("/handle/runtime_id")
578 .and_then(Value::as_str)
579 .ok_or_else(|| format!("the machine daemon did not start the relay: {result}"))?
580 .to_string();
581 std::fs::write(
582 &spec.paths.record,
583 serde_json::to_vec(&Record {
584 runtime_id: runtime_id.clone(),
585 endpoint,
586 })
587 .unwrap_or_default(),
588 )
589 .map_err(|error| error.to_string())?;
590 crate::runtime_mail::controlled_runtime("claude-code", &runtime_id)
591 .ok_or_else(|| "the relay started but registered no live runtime".to_string())
592}
593
594fn end_relay_process(name: &str) {
596 let registry = registry_dir(&HarnessHomes::default());
597 for session in read_registry(®istry) {
598 #[cfg(unix)]
599 if session.name == name {
600 unsafe {
602 libc::kill(session.pid as libc::pid_t, libc::SIGTERM);
603 }
604 }
605 }
606}
607
608async fn relay_endpoint(program: &Path) -> Result<String, String> {
611 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
612 return Ok(url);
613 }
614 ensure_machine_daemon(program).await?;
615 let deadline = Instant::now() + Duration::from_secs(10);
616 while Instant::now() < deadline {
617 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
618 return Ok(url);
619 }
620 tokio::time::sleep(Duration::from_millis(200)).await;
621 }
622 Err(
623 "the relay endpoint is not answering; the machine daemon's `supercode message watch` \
624 serves it (see mail/machine-daemon.log)"
625 .into(),
626 )
627}
628
629pub async fn machine_rpc(program: &Path, method: &str, params: &Value) -> Result<Value, String> {
632 let call = || {
633 let mut command = tokio::process::Command::new(program);
634 command
635 .args(["teams", "rpc", method, ¶ms.to_string()])
636 .stdin(std::process::Stdio::null())
637 .stdout(std::process::Stdio::piped())
638 .stderr(std::process::Stdio::piped());
639 command.output()
640 };
641 let output = call().await.map_err(|error| error.to_string())?;
642 if output.status.success() {
643 return serde_json::from_slice(&output.stdout)
644 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
645 }
646 ensure_machine_daemon(program).await?;
649 let output = call().await.map_err(|error| error.to_string())?;
650 if output.status.success() {
651 return serde_json::from_slice(&output.stdout)
652 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
653 }
654 Err(error_line(&String::from_utf8_lossy(&output.stderr)))
655}
656
657pub async fn ensure_machine_daemon(program: &Path) -> Result<(), String> {
660 let describe = || {
661 tokio::process::Command::new(program)
662 .args(["teams", "describe"])
663 .stdin(std::process::Stdio::null())
664 .stdout(std::process::Stdio::null())
665 .stderr(std::process::Stdio::null())
666 .status()
667 };
668 if describe().await.is_ok_and(|status| status.success()) {
669 return Ok(());
670 }
671 let root = mail_root();
672 std::fs::create_dir_all(&root).map_err(|error| error.to_string())?;
673 let log = std::fs::OpenOptions::new()
674 .create(true)
675 .append(true)
676 .open(root.join("machine-daemon.log"))
677 .map_err(|error| error.to_string())?;
678 let mut command = std::process::Command::new(program);
679 command
680 .args(["teams", "machine", "start", "--supercode"])
681 .arg(program)
682 .stdin(std::process::Stdio::null())
683 .stdout(log.try_clone().map_err(|error| error.to_string())?)
684 .stderr(log);
685 #[cfg(unix)]
686 {
687 use std::os::unix::process::CommandExt;
688 command.process_group(0);
691 }
692 command
693 .spawn()
694 .map_err(|error| format!("could not start the machine daemon: {error}"))?;
695 for _ in 0..50 {
696 tokio::time::sleep(Duration::from_millis(200)).await;
697 if describe().await.is_ok_and(|status| status.success()) {
698 return Ok(());
699 }
700 }
701 Err(format!(
702 "the machine daemon did not start within 10 seconds; see {}",
703 root.join("machine-daemon.log").display()
704 ))
705}
706
707fn error_line(stderr: &str) -> String {
709 let lines: Vec<&str> = stderr
710 .lines()
711 .map(str::trim)
712 .filter(|line| !line.is_empty())
713 .collect();
714 lines
715 .iter()
716 .find(|line| line.starts_with("Error") || line.starts_with("error"))
717 .or(lines.last())
718 .copied()
719 .unwrap_or("the machine daemon failed without saying why")
720 .chars()
721 .take(300)
722 .collect()
723}
724
725struct SendLock {
727 _file: std::fs::File,
728}
729
730impl SendLock {
731 fn acquire(path: &Path) -> std::io::Result<Self> {
732 let file = std::fs::OpenOptions::new()
733 .create(true)
734 .truncate(false)
735 .write(true)
736 .open(path)?;
737 #[cfg(unix)]
738 {
739 use std::os::unix::io::AsRawFd;
740 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
743 return Err(std::io::Error::last_os_error());
744 }
745 }
746 Ok(Self { _file: file })
747 }
748}
749
750pub fn file_inbound_prompt(
753 homes: &HarnessHomes,
754 represented: &MailAddress,
755 prompt: &str,
756 last_sent: Option<&HashMap<String, String>>,
757) {
758 match parse_inbound_text(prompt) {
759 Some(RelayEvent::Peer(native)) => {
760 let registry = read_registry(®istry_dir(homes));
761 let sender = resolve_native_sender(®istry, &native.from);
762 let in_reply_to = sender
763 .as_ref()
764 .and_then(|session| last_sent.and_then(|sent| sent.get(&session.name).cloned()));
765 file_inbound(represented, &native, sender.as_ref(), in_reply_to);
766 }
767 Some(RelayEvent::IdleNotice(text) | RelayEvent::DeliveryNotice(text)) => {
768 file_notice(represented, &text);
769 }
770 _ => {}
771 }
772}
773pub fn parse_inbound_text(text: &str) -> Option<RelayEvent> {
776 let trimmed = text.trim_start();
777 if trimmed.starts_with(NATIVE_IDLE_NOTICE) {
778 return Some(RelayEvent::IdleNotice(trimmed.to_string()));
779 }
780 if trimmed.starts_with(NATIVE_DELIVERY_NOTICE) {
781 return Some(RelayEvent::DeliveryNotice(trimmed.to_string()));
782 }
783 if !trimmed.starts_with(NATIVE_PEER_PREAMBLE) && !trimmed.starts_with(NATIVE_PEER_OPENING) {
784 return None;
785 }
786 let start = text.find(NATIVE_PEER_OPENING)?;
787 let header_end = start + text[start..].find(">\n")?;
788 let header = &text[start + NATIVE_PEER_OPENING.len()..header_end];
789 let body_start = header_end + 2;
790 let body_end = text.rfind(&format!("\n{NATIVE_PEER_CLOSING}"))?;
793 if body_end < body_start {
794 return None;
795 }
796 let attributes = parse_attributes(header);
797 Some(RelayEvent::Peer(NativeEnvelope {
798 from: attributes.get("from")?.clone(),
799 from_name: attributes.get("from-name").cloned(),
800 body: text[body_start..body_end].to_string(),
801 }))
802}
803fn parse_attributes(header: &str) -> BTreeMap<String, String> {
804 let mut attributes = BTreeMap::new();
805 let mut rest = header;
806 while let Some(equals) = rest.find("=\"") {
807 let key = rest[..equals].trim().to_string();
808 let value_start = equals + 2;
809 let Some(length) = rest[value_start..].find('"') else {
810 break;
811 };
812 attributes.insert(key, rest[value_start..value_start + length].to_string());
813 rest = &rest[value_start + length + 1..];
814 }
815 attributes
816}
817fn deliver_home(represented: &MailAddress, envelope: &Envelope) {
821 if let Err(error) = crate::mailbox::deliver_to(represented, envelope) {
822 eprintln!(
823 "could not deliver {} to {represented}: {error}; kept in this machine's mailbox for it",
824 envelope.id
825 );
826 if let Ok(mailbox) = crate::mailbox::Mailbox::open(&mail_root(), represented) {
827 mailbox.deliver(envelope).ok();
828 }
829 return;
830 }
831 if represented.machine == crate::mailbox::local_machine_name() {
836 if let Ok(program) = supercode_program() {
837 std::process::Command::new(program)
838 .args(["message", "push", &represented.to_string(), &envelope.id])
839 .stdin(std::process::Stdio::null())
840 .stdout(std::process::Stdio::null())
841 .stderr(std::process::Stdio::null())
842 .spawn()
843 .ok();
844 }
845 }
846}
847fn file_inbound(
848 represented: &MailAddress,
849 native: &NativeEnvelope,
850 sender: Option<&ClaudePeerSession>,
851 in_reply_to: Option<String>,
852) {
853 let machine = crate::mailbox::local_machine_name();
856 let (from, from_name) = match sender {
857 Some(session) => (
858 MailAddress::new(&machine, "claude-code", &session.session_id),
859 format!("{}@{machine}", session.name),
860 ),
861 None => (
862 MailAddress::new(&machine, "claude-code", "unknown"),
863 native
864 .from_name
865 .clone()
866 .unwrap_or_else(|| "an unknown Claude session".into()),
867 ),
868 };
869 let Ok(from) = from else { return };
870 let Ok(mut envelope) = Envelope::new(
871 from,
872 from_name,
873 MailKind::Peer,
874 ReplyVia::Command,
875 native.body.clone(),
876 ) else {
877 return;
878 };
879 envelope.native_from = Some(native.from.clone());
880 if let Some(in_reply_to) = in_reply_to {
881 envelope.in_reply_to = Some(in_reply_to);
882 envelope.in_reply_to_inferred = true;
883 }
884 deliver_home(represented, &envelope);
887}
888fn file_notice(represented: &MailAddress, text: &str) {
889 let Ok(from) = MailAddress::new(
890 crate::mailbox::local_machine_name(),
891 "claude-code",
892 "notice",
893 ) else {
894 return;
895 };
896 let Ok(envelope) = Envelope::new(
897 from,
898 "Claude Code",
899 MailKind::Notice,
900 ReplyVia::None,
901 text.to_string(),
902 ) else {
903 return;
904 };
905 deliver_home(represented, &envelope);
908}
909pub fn supercode_program() -> std::io::Result<PathBuf> {
912 let current = std::env::current_exe()?;
913 if current.file_stem().and_then(|stem| stem.to_str()) == Some("supercode") {
914 return Ok(current);
915 }
916 std::env::var_os("PATH")
917 .iter()
918 .flat_map(std::env::split_paths)
919 .map(|directory| directory.join("supercode"))
920 .find(|candidate| candidate.is_file())
921 .ok_or_else(|| {
922 std::io::Error::new(
923 std::io::ErrorKind::NotFound,
924 "the supercode program is not on PATH; Claude relays and the machine daemon need it",
925 )
926 })
927}