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 "StopFailure": [{
317 "hooks": [{"type": "command", "command": command("relay-receipt")}],
318 }],
319 "UserPromptSubmit": [{
320 "hooks": [{
321 "type": "command",
322 "command": format!("{program} message relay-inbound {represented} {directory}"),
323 }],
324 }],
325 }
326 })
327}
328
329fn shell_quote(value: &str) -> String {
330 format!("'{}'", value.replace('\'', "'\\''"))
331}
332
333pub fn is_inbound_prompt(prompt: &str) -> bool {
336 let trimmed = prompt.trim_start();
337 trimmed.starts_with(NATIVE_PEER_OPENING)
338 || trimmed.starts_with(NATIVE_IDLE_NOTICE)
339 || trimmed.starts_with(NATIVE_DELIVERY_NOTICE)
340}
341
342pub fn inbound_block() -> Value {
344 json!({
345 "decision": "block",
346 "reason": "filed in the mailbox of the session this relay speaks for",
347 })
348}
349
350pub fn send_turn(send: &QueuedSend) -> String {
352 format!(
353 "Send one message with SendMessage.\n\
354 to: {}\n\
355 message: the exact text between the markers, without the markers\n\
356 ---BEGIN MESSAGE---\n{}\n---END MESSAGE---",
357 send.to, send.message
358 )
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct NativeEnvelope {
364 pub from: String,
366 pub from_name: Option<String>,
368 pub body: String,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
374pub enum RelayEvent {
375 Peer(NativeEnvelope),
377 IdleNotice(String),
379 DeliveryNotice(String),
381}
382
383pub fn resolve_native_sender(
385 registry: &[ClaudePeerSession],
386 native_from: &str,
387) -> Option<ClaudePeerSession> {
388 let socket = native_from.strip_prefix("uds:").unwrap_or(native_from);
389 registry
390 .iter()
391 .find(|session| session.socket_path.to_string_lossy() == socket)
392 .cloned()
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(rename_all = "snake_case", tag = "outcome")]
398pub enum RelayReceipt {
399 Delivered {
401 detail: String,
403 native_msg_id: Option<String>,
405 },
406 Failed {
408 detail: String,
410 },
411}
412
413pub fn read_receipt(value: &Value) -> RelayReceipt {
416 if let Some(reason) = value.get("denied").and_then(Value::as_str) {
417 return RelayReceipt::Failed {
418 detail: format!("the relay's gate refused the send: {reason}"),
419 };
420 }
421 if value.get("turn_ended").and_then(Value::as_bool) == Some(true) {
422 let said = value
423 .get("said")
424 .and_then(Value::as_str)
425 .filter(|said| !said.trim().is_empty())
426 .map(|said| format!("; it said: {}", said.trim()))
427 .unwrap_or_default();
428 return RelayReceipt::Failed {
429 detail: format!(
430 "the Claude relay ended its turn without sending; nothing was sent{said}"
431 ),
432 };
433 }
434 let response = value.get("tool_response").cloned().unwrap_or(Value::Null);
435 let parsed = match &response {
436 Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(response.clone()),
437 Value::Array(blocks) => blocks
438 .iter()
439 .find_map(|block| block.get("text").and_then(Value::as_str))
440 .and_then(|text| serde_json::from_str::<Value>(text).ok())
441 .unwrap_or(response.clone()),
442 _ => response.clone(),
443 };
444 if parsed.get("success").and_then(Value::as_bool) != Some(true) {
445 return RelayReceipt::Failed {
446 detail: format!("Claude did not report the send as successful: {parsed}"),
447 };
448 }
449 RelayReceipt::Delivered {
450 detail: parsed
451 .get("message")
452 .and_then(Value::as_str)
453 .unwrap_or_default()
454 .to_string(),
455 native_msg_id: parsed
456 .get("msg_id")
457 .and_then(Value::as_str)
458 .map(str::to_string),
459 }
460}
461
462pub async fn send_through_relay(
467 sender: &MailAddress,
468 sender_name: &str,
469 to: &str,
470 message: String,
471 message_id: &str,
472) -> RelayReceipt {
473 let failed = |detail: String| RelayReceipt::Failed { detail };
474 let spec = match RelaySpec::for_sender(sender, sender_name) {
475 Ok(spec) => spec,
476 Err(error) => return failed(error.to_string()),
477 };
478 if let Err(error) = std::fs::create_dir_all(&spec.paths.directory) {
479 return failed(error.to_string());
480 }
481 let lock = match tokio::task::spawn_blocking({
483 let path = spec.paths.lock.clone();
484 move || SendLock::acquire(&path)
485 })
486 .await
487 {
488 Ok(Ok(lock)) => lock,
489 Ok(Err(error)) => return failed(format!("could not take the relay's send lock: {error}")),
490 Err(error) => return failed(error.to_string()),
491 };
492 let runtime = match ensure_relay_runtime(&spec).await {
493 Ok(runtime) => runtime,
494 Err(detail) => return failed(detail),
495 };
496 let queued = QueuedSend {
497 to: to.to_string(),
498 message,
499 };
500 std::fs::remove_file(&spec.paths.receipt).ok();
501 if let Err(error) = std::fs::write(
502 &spec.paths.queue,
503 serde_json::to_vec(&queued).unwrap_or_default(),
504 ) {
505 return failed(error.to_string());
506 }
507 let delivered =
508 crate::runtime_mail::deliver_to_runtime(&runtime, send_turn(&queued), true).await;
509 let receipt = match delivered {
510 Err(detail) => failed(format!("could not reach the Claude relay: {detail}")),
511 Ok(_) => wait_for_receipt(&spec.paths.receipt).await,
512 };
513 std::fs::remove_file(&spec.paths.queue).ok();
514 if matches!(receipt, RelayReceipt::Delivered { .. }) {
515 let mut sent = spec.paths.last_sent();
516 sent.insert(to.to_string(), message_id.to_string());
517 std::fs::write(
518 &spec.paths.sent,
519 serde_json::to_vec(&sent).unwrap_or_default(),
520 )
521 .ok();
522 }
523 drop(lock);
524 receipt
525}
526
527async fn wait_for_receipt(path: &Path) -> RelayReceipt {
528 let started = Instant::now();
529 while started.elapsed() < SEND_TIMEOUT {
530 if let Some(value) = std::fs::read(path)
531 .ok()
532 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
533 {
534 return read_receipt(&value);
535 }
536 tokio::time::sleep(Duration::from_millis(200)).await;
537 }
538 RelayReceipt::Failed {
539 detail: format!(
540 "the Claude relay did not confirm the send within {} seconds; it may still arrive",
541 SEND_TIMEOUT.as_secs()
542 ),
543 }
544}
545
546async fn ensure_relay_runtime(
549 spec: &RelaySpec,
550) -> Result<crate::live_runtime::LiveRuntimeRecord, String> {
551 #[derive(Serialize, Deserialize)]
552 struct Record {
553 runtime_id: String,
554 #[serde(default)]
555 endpoint: String,
556 }
557 let endpoint = relay_endpoint(&spec.program).await?;
558 if let Some(record) = std::fs::read(&spec.paths.record)
559 .ok()
560 .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok())
561 {
562 if let Some(runtime) =
563 crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id)
564 {
565 if record.endpoint == endpoint {
566 return Ok(runtime);
567 }
568 end_relay_process(&spec.name);
571 }
572 }
573 std::fs::write(
574 &spec.paths.settings,
575 serde_json::to_vec_pretty(&relay_settings(spec)).unwrap_or_default(),
576 )
577 .map_err(|error| error.to_string())?;
578 let params = json!({
579 "harness": "claude-code",
580 "launch": {
581 "program": "claude",
582 "arguments": relay_arguments(spec),
583 "env": relay_environment(spec, &endpoint),
584 },
585 "cwd": spec.paths.directory,
586 });
587 let result = machine_rpc(&spec.program, "runtimes.start", ¶ms).await?;
588 let runtime_id = result
589 .pointer("/handle/runtime_id")
590 .and_then(Value::as_str)
591 .ok_or_else(|| format!("the machine daemon did not start the relay: {result}"))?
592 .to_string();
593 std::fs::write(
594 &spec.paths.record,
595 serde_json::to_vec(&Record {
596 runtime_id: runtime_id.clone(),
597 endpoint,
598 })
599 .unwrap_or_default(),
600 )
601 .map_err(|error| error.to_string())?;
602 crate::runtime_mail::controlled_runtime("claude-code", &runtime_id)
603 .ok_or_else(|| "the relay started but registered no live runtime".to_string())
604}
605
606fn end_relay_process(name: &str) {
608 let registry = registry_dir(&HarnessHomes::default());
609 for session in read_registry(®istry) {
610 #[cfg(unix)]
611 if session.name == name {
612 unsafe {
614 libc::kill(session.pid as libc::pid_t, libc::SIGTERM);
615 }
616 }
617 }
618}
619
620async fn relay_endpoint(program: &Path) -> Result<String, String> {
623 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
624 return Ok(url);
625 }
626 ensure_machine_daemon(program).await?;
627 let deadline = Instant::now() + Duration::from_secs(10);
628 while Instant::now() < deadline {
629 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
630 return Ok(url);
631 }
632 tokio::time::sleep(Duration::from_millis(200)).await;
633 }
634 Err(
635 "the relay endpoint is not answering; the machine daemon's `supercode message watch` \
636 serves it (see mail/machine-daemon.log)"
637 .into(),
638 )
639}
640
641pub async fn machine_rpc(program: &Path, method: &str, params: &Value) -> Result<Value, String> {
644 let call = || {
645 let mut command = tokio::process::Command::new(program);
646 command
647 .args(["teams", "rpc", method, ¶ms.to_string()])
648 .stdin(std::process::Stdio::null())
649 .stdout(std::process::Stdio::piped())
650 .stderr(std::process::Stdio::piped());
651 command.output()
652 };
653 let output = call().await.map_err(|error| error.to_string())?;
654 if output.status.success() {
655 return serde_json::from_slice(&output.stdout)
656 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
657 }
658 ensure_machine_daemon(program).await?;
661 let output = call().await.map_err(|error| error.to_string())?;
662 if output.status.success() {
663 return serde_json::from_slice(&output.stdout)
664 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
665 }
666 Err(error_line(&String::from_utf8_lossy(&output.stderr)))
667}
668
669pub async fn ensure_machine_daemon(program: &Path) -> Result<(), String> {
672 let describe = || {
673 tokio::process::Command::new(program)
674 .args(["teams", "describe"])
675 .stdin(std::process::Stdio::null())
676 .stdout(std::process::Stdio::null())
677 .stderr(std::process::Stdio::null())
678 .status()
679 };
680 if describe().await.is_ok_and(|status| status.success()) {
681 return Ok(());
682 }
683 let root = mail_root();
684 std::fs::create_dir_all(&root).map_err(|error| error.to_string())?;
685 let log = std::fs::OpenOptions::new()
686 .create(true)
687 .append(true)
688 .open(root.join("machine-daemon.log"))
689 .map_err(|error| error.to_string())?;
690 let mut command = std::process::Command::new(program);
691 command
692 .args(["teams", "machine", "start", "--supercode"])
693 .arg(program)
694 .stdin(std::process::Stdio::null())
695 .stdout(log.try_clone().map_err(|error| error.to_string())?)
696 .stderr(log);
697 #[cfg(unix)]
698 {
699 use std::os::unix::process::CommandExt;
700 command.process_group(0);
703 }
704 command
705 .spawn()
706 .map_err(|error| format!("could not start the machine daemon: {error}"))?;
707 for _ in 0..50 {
708 tokio::time::sleep(Duration::from_millis(200)).await;
709 if describe().await.is_ok_and(|status| status.success()) {
710 return Ok(());
711 }
712 }
713 Err(format!(
714 "the machine daemon did not start within 10 seconds; see {}",
715 root.join("machine-daemon.log").display()
716 ))
717}
718
719fn error_line(stderr: &str) -> String {
721 let lines: Vec<&str> = stderr
722 .lines()
723 .map(str::trim)
724 .filter(|line| !line.is_empty())
725 .collect();
726 lines
727 .iter()
728 .find(|line| line.starts_with("Error") || line.starts_with("error"))
729 .or(lines.last())
730 .copied()
731 .unwrap_or("the machine daemon failed without saying why")
732 .chars()
733 .take(300)
734 .collect()
735}
736
737struct SendLock {
739 _file: std::fs::File,
740}
741
742impl SendLock {
743 fn acquire(path: &Path) -> std::io::Result<Self> {
744 let file = std::fs::OpenOptions::new()
745 .create(true)
746 .truncate(false)
747 .write(true)
748 .open(path)?;
749 #[cfg(unix)]
750 {
751 use std::os::unix::io::AsRawFd;
752 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
755 return Err(std::io::Error::last_os_error());
756 }
757 }
758 Ok(Self { _file: file })
759 }
760}
761
762pub fn file_inbound_prompt(
765 homes: &HarnessHomes,
766 represented: &MailAddress,
767 prompt: &str,
768 last_sent: Option<&HashMap<String, String>>,
769) {
770 match parse_inbound_text(prompt) {
771 Some(RelayEvent::Peer(native)) => {
772 let registry = read_registry(®istry_dir(homes));
773 let sender = resolve_native_sender(®istry, &native.from);
774 let in_reply_to = sender
775 .as_ref()
776 .and_then(|session| last_sent.and_then(|sent| sent.get(&session.name).cloned()));
777 file_inbound(represented, &native, sender.as_ref(), in_reply_to);
778 }
779 Some(RelayEvent::IdleNotice(text) | RelayEvent::DeliveryNotice(text)) => {
780 file_notice(represented, &text);
781 }
782 _ => {}
783 }
784}
785pub fn parse_inbound_text(text: &str) -> Option<RelayEvent> {
788 let trimmed = text.trim_start();
789 if trimmed.starts_with(NATIVE_IDLE_NOTICE) {
790 return Some(RelayEvent::IdleNotice(trimmed.to_string()));
791 }
792 if trimmed.starts_with(NATIVE_DELIVERY_NOTICE) {
793 return Some(RelayEvent::DeliveryNotice(trimmed.to_string()));
794 }
795 if !trimmed.starts_with(NATIVE_PEER_PREAMBLE) && !trimmed.starts_with(NATIVE_PEER_OPENING) {
796 return None;
797 }
798 let start = text.find(NATIVE_PEER_OPENING)?;
799 let header_end = start + text[start..].find(">\n")?;
800 let header = &text[start + NATIVE_PEER_OPENING.len()..header_end];
801 let body_start = header_end + 2;
802 let body_end = text.rfind(&format!("\n{NATIVE_PEER_CLOSING}"))?;
805 if body_end < body_start {
806 return None;
807 }
808 let attributes = parse_attributes(header);
809 Some(RelayEvent::Peer(NativeEnvelope {
810 from: attributes.get("from")?.clone(),
811 from_name: attributes.get("from-name").cloned(),
812 body: text[body_start..body_end].to_string(),
813 }))
814}
815fn parse_attributes(header: &str) -> BTreeMap<String, String> {
816 let mut attributes = BTreeMap::new();
817 let mut rest = header;
818 while let Some(equals) = rest.find("=\"") {
819 let key = rest[..equals].trim().to_string();
820 let value_start = equals + 2;
821 let Some(length) = rest[value_start..].find('"') else {
822 break;
823 };
824 attributes.insert(key, rest[value_start..value_start + length].to_string());
825 rest = &rest[value_start + length + 1..];
826 }
827 attributes
828}
829fn deliver_home(represented: &MailAddress, envelope: &Envelope) {
833 if let Err(error) = crate::mailbox::deliver_to(represented, envelope) {
834 eprintln!(
835 "could not deliver {} to {represented}: {error}; kept in this machine's mailbox for it",
836 envelope.id
837 );
838 if let Ok(mailbox) = crate::mailbox::Mailbox::open(&mail_root(), represented) {
839 mailbox.deliver(envelope).ok();
840 }
841 return;
842 }
843 if represented.machine == crate::mailbox::local_machine_name() {
848 if let Ok(program) = supercode_program() {
849 std::process::Command::new(program)
850 .args(["message", "push", &represented.to_string(), &envelope.id])
851 .stdin(std::process::Stdio::null())
852 .stdout(std::process::Stdio::null())
853 .stderr(std::process::Stdio::null())
854 .spawn()
855 .ok();
856 }
857 }
858}
859fn file_inbound(
860 represented: &MailAddress,
861 native: &NativeEnvelope,
862 sender: Option<&ClaudePeerSession>,
863 in_reply_to: Option<String>,
864) {
865 let machine = crate::mailbox::local_machine_name();
868 let (from, from_name) = match sender {
869 Some(session) => (
870 MailAddress::new(&machine, "claude-code", &session.session_id),
871 format!("{}@{machine}", session.name),
872 ),
873 None => (
874 MailAddress::new(&machine, "claude-code", "unknown"),
875 native
876 .from_name
877 .clone()
878 .unwrap_or_else(|| "an unknown Claude session".into()),
879 ),
880 };
881 let Ok(from) = from else { return };
882 let Ok(mut envelope) = Envelope::new(
883 from,
884 from_name,
885 MailKind::Peer,
886 ReplyVia::Command,
887 native.body.clone(),
888 ) else {
889 return;
890 };
891 envelope.native_from = Some(native.from.clone());
892 if let Some(in_reply_to) = in_reply_to {
893 envelope.in_reply_to = Some(in_reply_to);
894 envelope.in_reply_to_inferred = true;
895 }
896 deliver_home(represented, &envelope);
899}
900fn file_notice(represented: &MailAddress, text: &str) {
901 let Ok(from) = MailAddress::new(
902 crate::mailbox::local_machine_name(),
903 "claude-code",
904 "notice",
905 ) else {
906 return;
907 };
908 let Ok(envelope) = Envelope::new(
909 from,
910 "Claude Code",
911 MailKind::Notice,
912 ReplyVia::None,
913 text.to_string(),
914 ) else {
915 return;
916 };
917 deliver_home(represented, &envelope);
920}
921pub fn supercode_program() -> std::io::Result<PathBuf> {
924 let current = std::env::current_exe()?;
925 if current.file_stem().and_then(|stem| stem.to_str()) == Some("supercode") {
926 return Ok(current);
927 }
928 std::env::var_os("PATH")
929 .iter()
930 .flat_map(std::env::split_paths)
931 .map(|directory| directory.join("supercode"))
932 .find(|candidate| candidate.is_file())
933 .ok_or_else(|| {
934 std::io::Error::new(
935 std::io::ErrorKind::NotFound,
936 "the supercode program is not on PATH; Claude relays and the machine daemon need it",
937 )
938 })
939}