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 turn: PathBuf,
175 pub settings: PathBuf,
177 pub record: PathBuf,
179 pub sent: PathBuf,
181 pub lock: PathBuf,
183}
184
185impl RelayPaths {
186 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 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 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#[derive(Debug, Clone)]
217pub struct RelaySpec {
218 pub represented: MailAddress,
220 pub represented_name: String,
222 pub name: String,
224 pub paths: RelayPaths,
226 pub program: PathBuf,
228}
229
230impl RelaySpec {
231 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
248pub 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
279pub 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 ("SUPERCODE_CLAUDE_RELAY".to_string(), "1".to_string()),
291 ("ANTHROPIC_BASE_URL".to_string(), endpoint.to_string()),
292 ("ANTHROPIC_API_KEY".to_string(), key),
293 (
294 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
295 "1".to_string(),
296 ),
297 ])
298}
299
300pub fn relay_settings(spec: &RelaySpec) -> Value {
302 let program = shell_quote(&spec.program.to_string_lossy());
303 let directory = shell_quote(&spec.paths.directory.to_string_lossy());
304 let represented = shell_quote(&spec.represented.to_string());
305 let command = |verb: &str| format!("{program} message {verb} {directory}");
306 json!({
307 "hooks": {
308 "PreToolUse": [{
310 "matcher": ".*",
311 "hooks": [{"type": "command", "command": command("gate")}],
312 }],
313 "PostToolUse": [{
314 "matcher": "SendMessage",
315 "hooks": [{"type": "command", "command": command("relay-receipt")}],
316 }],
317 "PostToolUseFailure": [{
319 "matcher": "SendMessage",
320 "hooks": [{"type": "command", "command": command("relay-receipt")}],
321 }],
322 "Stop": [{
323 "hooks": [{"type": "command", "command": command("relay-receipt")}],
324 }],
325 "StopFailure": [{
327 "hooks": [{"type": "command", "command": command("relay-receipt")}],
328 }],
329 "UserPromptSubmit": [{
330 "hooks": [{
331 "type": "command",
332 "command": format!("{program} message relay-inbound {represented} {directory}"),
333 }],
334 }],
335 }
336 })
337}
338
339fn shell_quote(value: &str) -> String {
340 format!("'{}'", value.replace('\'', "'\\''"))
341}
342
343pub fn is_inbound_prompt(prompt: &str) -> bool {
346 let trimmed = prompt.trim_start();
347 trimmed.starts_with(NATIVE_PEER_OPENING)
348 || trimmed.starts_with(NATIVE_IDLE_NOTICE)
349 || trimmed.starts_with(NATIVE_DELIVERY_NOTICE)
350}
351
352pub fn inbound_block() -> Value {
354 json!({
355 "decision": "block",
356 "reason": "filed in the mailbox of the session this relay speaks for",
357 })
358}
359
360pub fn send_turn(send: &QueuedSend) -> String {
362 format!(
363 "Send one message with SendMessage.\n\
364 to: {}\n\
365 message: the exact text between the markers, without the markers\n\
366 ---BEGIN MESSAGE---\n{}\n---END MESSAGE---",
367 send.to, send.message
368 )
369}
370
371#[derive(Debug, Clone, PartialEq, Eq)]
373pub struct NativeEnvelope {
374 pub from: String,
376 pub from_name: Option<String>,
378 pub body: String,
380}
381
382#[derive(Debug, Clone, PartialEq, Eq)]
384pub enum RelayEvent {
385 Peer(NativeEnvelope),
387 IdleNotice(String),
389 DeliveryNotice(String),
391}
392
393pub fn resolve_native_sender(
395 registry: &[ClaudePeerSession],
396 native_from: &str,
397) -> Option<ClaudePeerSession> {
398 let socket = native_from.strip_prefix("uds:").unwrap_or(native_from);
399 registry
400 .iter()
401 .find(|session| session.socket_path.to_string_lossy() == socket)
402 .cloned()
403}
404
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(rename_all = "snake_case", tag = "outcome")]
408pub enum RelayReceipt {
409 Delivered {
411 detail: String,
413 native_msg_id: Option<String>,
415 },
416 Failed {
418 detail: String,
420 },
421}
422
423pub fn read_receipt(value: &Value) -> RelayReceipt {
426 if let Some(reason) = value.get("denied").and_then(Value::as_str) {
427 return RelayReceipt::Failed {
428 detail: format!("the relay's gate refused the send: {reason}"),
429 };
430 }
431 if let Some(error) = value.get("send_failed").and_then(Value::as_str) {
432 return RelayReceipt::Failed {
433 detail: format!("Claude Code refused the relay's send: {}", error.trim()),
434 };
435 }
436 if value.get("turn_ended").and_then(Value::as_bool) == Some(true) {
437 let said = value
438 .get("said")
439 .and_then(Value::as_str)
440 .filter(|said| !said.trim().is_empty())
441 .map(|said| format!("; it said: {}", said.trim()))
442 .unwrap_or_default();
443 return RelayReceipt::Failed {
444 detail: format!(
445 "the Claude relay ended its turn without sending; nothing was sent{said}"
446 ),
447 };
448 }
449 let response = value.get("tool_response").cloned().unwrap_or(Value::Null);
450 let parsed = match &response {
451 Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(response.clone()),
452 Value::Array(blocks) => blocks
453 .iter()
454 .find_map(|block| block.get("text").and_then(Value::as_str))
455 .and_then(|text| serde_json::from_str::<Value>(text).ok())
456 .unwrap_or(response.clone()),
457 _ => response.clone(),
458 };
459 if parsed.get("success").and_then(Value::as_bool) != Some(true) {
460 return RelayReceipt::Failed {
461 detail: format!("Claude did not report the send as successful: {parsed}"),
462 };
463 }
464 RelayReceipt::Delivered {
465 detail: parsed
466 .get("message")
467 .and_then(Value::as_str)
468 .unwrap_or_default()
469 .to_string(),
470 native_msg_id: parsed
471 .get("msg_id")
472 .and_then(Value::as_str)
473 .map(str::to_string),
474 }
475}
476
477pub async fn send_through_relay(
482 sender: &MailAddress,
483 sender_name: &str,
484 to: &str,
485 message: String,
486 message_id: &str,
487) -> RelayReceipt {
488 let failed = |detail: String| RelayReceipt::Failed { detail };
489 let spec = match RelaySpec::for_sender(sender, sender_name) {
490 Ok(spec) => spec,
491 Err(error) => return failed(error.to_string()),
492 };
493 if let Err(error) = std::fs::create_dir_all(&spec.paths.directory) {
494 return failed(error.to_string());
495 }
496 let lock = match tokio::task::spawn_blocking({
498 let path = spec.paths.lock.clone();
499 move || SendLock::acquire(&path)
500 })
501 .await
502 {
503 Ok(Ok(lock)) => lock,
504 Ok(Err(error)) => return failed(format!("could not take the relay's send lock: {error}")),
505 Err(error) => return failed(error.to_string()),
506 };
507 let mut runtime = match ensure_relay_runtime(&spec).await {
508 Ok(runtime) => runtime,
509 Err(detail) => return failed(detail),
510 };
511 let queued = QueuedSend {
512 to: to.to_string(),
513 message,
514 };
515 std::fs::remove_file(&spec.paths.receipt).ok();
516 if let Err(error) = std::fs::write(
517 &spec.paths.queue,
518 serde_json::to_vec(&queued).unwrap_or_default(),
519 ) {
520 return failed(error.to_string());
521 }
522 let mut attempts = 0;
523 let receipt = loop {
524 let delivered =
525 crate::runtime_mail::deliver_to_runtime(&runtime, send_turn(&queued), true).await;
526 let receipt = match delivered {
527 Err(detail) => failed(format!("could not reach the Claude relay: {detail}")),
528 Ok(_) => wait_for_receipt(&spec.paths.receipt, relay_pid(&spec, &runtime)).await,
529 };
530 if matches!(receipt, RelayReceipt::Delivered { .. })
531 || relay_pid(&spec, &runtime).is_some_and(crate::claude_peer::process_is_live)
532 || attempts == 1
533 {
534 break receipt;
535 }
536 if relay_pid(&spec, &runtime).is_none() {
539 break receipt;
540 }
541 attempts += 1;
542 runtime = match ensure_relay_runtime(&spec).await {
543 Ok(runtime) => runtime,
544 Err(detail) => break failed(detail),
545 };
546 std::fs::remove_file(&spec.paths.receipt).ok();
547 };
548 std::fs::remove_file(&spec.paths.queue).ok();
549 if matches!(receipt, RelayReceipt::Delivered { .. }) {
550 let mut sent = spec.paths.last_sent();
551 sent.insert(to.to_string(), message_id.to_string());
552 std::fs::write(
553 &spec.paths.sent,
554 serde_json::to_vec(&sent).unwrap_or_default(),
555 )
556 .ok();
557 }
558 drop(lock);
559 receipt
560}
561
562async fn wait_for_receipt(path: &Path, pid: Option<u32>) -> RelayReceipt {
563 let started = Instant::now();
564 while started.elapsed() < SEND_TIMEOUT {
565 if let Some(value) = std::fs::read(path)
566 .ok()
567 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
568 {
569 return read_receipt(&value);
570 }
571 if pid.is_some_and(|pid| !crate::claude_peer::process_is_live(pid)) {
572 return RelayReceipt::Failed {
573 detail: "the Claude relay process exited before confirming the send".into(),
574 };
575 }
576 tokio::time::sleep(Duration::from_millis(200)).await;
577 }
578 RelayReceipt::Failed {
579 detail: format!(
580 "the Claude relay did not confirm the send within {} seconds; it may still arrive",
581 SEND_TIMEOUT.as_secs()
582 ),
583 }
584}
585
586#[derive(Serialize, Deserialize)]
587struct RelayRuntimeRecord {
588 runtime_id: String,
589 #[serde(default)]
590 pid: Option<u32>,
591 #[serde(default)]
592 endpoint: String,
593 #[serde(default)]
595 connection: String,
596}
597fn relay_pid(spec: &RelaySpec, runtime: &crate::live_runtime::LiveRuntimeRecord) -> Option<u32> {
600 runtime
601 .metadata
602 .child_pid
603 .or_else(|| {
604 std::fs::read(&spec.paths.record)
605 .ok()
606 .and_then(|bytes| serde_json::from_slice::<RelayRuntimeRecord>(&bytes).ok())
607 .filter(|record| record.runtime_id == runtime.runtime_session_id)
608 .and_then(|record| record.pid)
609 })
610 .or_else(|| {
611 read_registry(®istry_dir(&HarnessHomes::default()))
612 .into_iter()
613 .find(|session| {
614 session.session_id == runtime.runtime_session_id && session.name == spec.name
615 })
616 .map(|session| session.pid)
617 })
618}
619
620async fn ensure_relay_runtime(
623 spec: &RelaySpec,
624) -> Result<crate::live_runtime::LiveRuntimeRecord, String> {
625 let endpoint = relay_endpoint(&spec.program).await?;
626 std::fs::write(
629 &spec.paths.settings,
630 serde_json::to_vec_pretty(&relay_settings(spec)).unwrap_or_default(),
631 )
632 .map_err(|error| error.to_string())?;
633 if let Some(record) = std::fs::read(&spec.paths.record)
634 .ok()
635 .and_then(|bytes| serde_json::from_slice::<RelayRuntimeRecord>(&bytes).ok())
636 {
637 let runtime = crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id);
638 if let Some(runtime) = &runtime {
639 if relay_pid(spec, runtime).is_some_and(crate::claude_peer::process_is_live)
640 && (record.endpoint == endpoint
641 || crate::relay_endpoint::endpoint_answers(&record.endpoint))
642 {
643 return Ok(runtime.clone());
644 }
645 }
646 let result = machine_rpc(
649 &spec.program,
650 "runtimes.close",
651 &json!({ "connection": record.connection, "runtime_id": record.runtime_id }),
652 )
653 .await;
654 if let Err(error) = result {
655 if crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id).is_some()
656 {
657 return Err(format!("could not retire the old relay: {error}"));
658 }
659 }
660 }
661 let params = json!({
662 "harness": "claude-code",
663 "launch": {
664 "program": "claude",
665 "arguments": relay_arguments(spec),
666 "env": relay_environment(spec, &endpoint),
667 },
668 "cwd": spec.paths.directory,
669 });
670 let result = machine_rpc(&spec.program, "runtimes.start", ¶ms).await?;
671 let runtime_id = result
672 .pointer("/handle/runtime_id")
673 .and_then(Value::as_str)
674 .ok_or_else(|| format!("the machine daemon did not start the relay: {result}"))?
675 .to_string();
676 let connection = result
677 .get("connection")
678 .and_then(Value::as_str)
679 .unwrap_or_default()
680 .to_string();
681 let pid = result
682 .pointer("/handle/endpoint/pid")
683 .and_then(Value::as_u64)
684 .map(|pid| pid as u32);
685 std::fs::write(
686 &spec.paths.record,
687 serde_json::to_vec(&RelayRuntimeRecord {
688 pid,
689 runtime_id: runtime_id.clone(),
690 endpoint,
691 connection,
692 })
693 .unwrap_or_default(),
694 )
695 .map_err(|error| error.to_string())?;
696 crate::runtime_mail::controlled_runtime("claude-code", &runtime_id)
697 .ok_or_else(|| "the relay started but registered no live runtime".to_string())
698}
699
700pub async fn retire_relays_of_ended_sessions(homes: &HarnessHomes) -> Vec<String> {
709 #[derive(Deserialize)]
710 struct Record {
711 runtime_id: String,
712 #[serde(default)]
713 connection: String,
714 }
715 let Ok(entries) = std::fs::read_dir(mail_root().join("relays")) else {
716 return Vec::new();
717 };
718 let running: std::collections::HashSet<String> = crate::mail_route::LiveSessions::read(homes)
719 .all()
720 .iter()
721 .map(|session| session.address.to_string())
722 .collect();
723 let Ok(program) = supercode_program() else {
724 return Vec::new();
725 };
726 let mut retired = Vec::new();
727 for entry in entries.flatten() {
728 let paths = RelayPaths::in_directory(entry.path());
729 let Some(represented) = std::fs::read_to_string(&paths.settings)
731 .ok()
732 .and_then(|text| {
733 let from = text.find("relay-inbound '")? + "relay-inbound '".len();
734 let len = text[from..].find('\'')?;
735 MailAddress::parse(&text[from..from + len]).ok()
736 })
737 else {
738 continue;
739 };
740 if matches!(represented.harness.as_str(), "board" | "operator")
741 || running.contains(&represented.to_string())
742 {
743 continue;
744 }
745 let record = std::fs::read(&paths.record)
746 .ok()
747 .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok());
748 let alive = record.as_ref().is_some_and(|record| {
749 crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id).is_some()
750 });
751 if alive {
752 let (connection, runtime_id) = record
753 .map(|record| (record.connection, record.runtime_id))
754 .unwrap_or_default();
755 if connection.is_empty()
756 || machine_rpc(
757 &program,
758 "runtimes.close",
759 &json!({ "connection": connection, "runtime_id": runtime_id }),
760 )
761 .await
762 .is_err()
763 {
764 continue;
765 }
766 }
767 if std::fs::remove_dir_all(&paths.directory).is_ok() {
768 retired.push(represented.to_string());
769 }
770 }
771 retired
772}
773
774async fn relay_endpoint(program: &Path) -> Result<String, String> {
777 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
778 return Ok(url);
779 }
780 ensure_machine_daemon(program).await?;
781 let deadline = Instant::now() + Duration::from_secs(10);
782 while Instant::now() < deadline {
783 if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
784 return Ok(url);
785 }
786 tokio::time::sleep(Duration::from_millis(200)).await;
787 }
788 Err(
789 "the relay endpoint is not answering; the machine daemon's `supercode message watch` \
790 serves it (see mail/machine-daemon.log)"
791 .into(),
792 )
793}
794
795pub async fn machine_rpc(program: &Path, method: &str, params: &Value) -> Result<Value, String> {
798 let call = || {
799 let mut command = tokio::process::Command::new(program);
800 command
801 .args(["teams", "rpc", method, ¶ms.to_string()])
802 .stdin(std::process::Stdio::null())
803 .stdout(std::process::Stdio::piped())
804 .stderr(std::process::Stdio::piped());
805 command.output()
806 };
807 let output = call().await.map_err(|error| error.to_string())?;
808 if output.status.success() {
809 return serde_json::from_slice(&output.stdout)
810 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
811 }
812 ensure_machine_daemon(program).await?;
815 let output = call().await.map_err(|error| error.to_string())?;
816 if output.status.success() {
817 return serde_json::from_slice(&output.stdout)
818 .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
819 }
820 Err(error_line(&String::from_utf8_lossy(&output.stderr)))
821}
822
823pub async fn ensure_machine_daemon(program: &Path) -> Result<(), String> {
826 let describe = || {
827 tokio::process::Command::new(program)
828 .args(["teams", "describe"])
829 .stdin(std::process::Stdio::null())
830 .stdout(std::process::Stdio::null())
831 .stderr(std::process::Stdio::null())
832 .status()
833 };
834 if describe().await.is_ok_and(|status| status.success()) {
835 return Ok(());
836 }
837 if crate::teams::service_owns_daemon() {
841 for _ in 0..100 {
842 tokio::time::sleep(Duration::from_millis(200)).await;
843 if describe().await.is_ok_and(|status| status.success()) {
844 return Ok(());
845 }
846 }
847 return Err(
848 "this machine's daemon is run by its service manager and did not answer within 20 seconds; \
849 see `supercode teams status`"
850 .into(),
851 );
852 }
853 let root = mail_root();
854 std::fs::create_dir_all(&root).map_err(|error| error.to_string())?;
855 let log = std::fs::OpenOptions::new()
856 .create(true)
857 .append(true)
858 .open(root.join("machine-daemon.log"))
859 .map_err(|error| error.to_string())?;
860 let mut command = std::process::Command::new(program);
861 command
862 .args(["teams", "machine", "start", "--supercode"])
863 .arg(program)
864 .stdin(std::process::Stdio::null())
865 .stdout(log.try_clone().map_err(|error| error.to_string())?)
866 .stderr(log);
867 #[cfg(unix)]
868 {
869 use std::os::unix::process::CommandExt;
870 command.process_group(0);
873 }
874 command
875 .spawn()
876 .map_err(|error| format!("could not start the machine daemon: {error}"))?;
877 for _ in 0..50 {
878 tokio::time::sleep(Duration::from_millis(200)).await;
879 if describe().await.is_ok_and(|status| status.success()) {
880 return Ok(());
881 }
882 }
883 Err(format!(
884 "the machine daemon did not start within 10 seconds; see {}",
885 root.join("machine-daemon.log").display()
886 ))
887}
888
889fn error_line(stderr: &str) -> String {
891 let lines: Vec<&str> = stderr
892 .lines()
893 .map(str::trim)
894 .filter(|line| !line.is_empty())
895 .collect();
896 lines
897 .iter()
898 .find(|line| line.starts_with("Error") || line.starts_with("error"))
899 .or(lines.last())
900 .copied()
901 .unwrap_or("the machine daemon failed without saying why")
902 .chars()
903 .take(300)
904 .collect()
905}
906
907struct SendLock {
909 _file: std::fs::File,
910}
911
912impl SendLock {
913 fn acquire(path: &Path) -> std::io::Result<Self> {
914 let file = std::fs::OpenOptions::new()
915 .create(true)
916 .truncate(false)
917 .write(true)
918 .open(path)?;
919 #[cfg(unix)]
920 {
921 use std::os::unix::io::AsRawFd;
922 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
925 return Err(std::io::Error::last_os_error());
926 }
927 }
928 Ok(Self { _file: file })
929 }
930}
931
932pub fn file_inbound_prompt(
935 homes: &HarnessHomes,
936 represented: &MailAddress,
937 prompt: &str,
938 last_sent: Option<&HashMap<String, String>>,
939) {
940 match parse_inbound_text(prompt) {
941 Some(RelayEvent::Peer(native)) => {
942 let registry = read_registry(®istry_dir(homes));
943 let sender = resolve_native_sender(®istry, &native.from);
944 let in_reply_to = sender
945 .as_ref()
946 .and_then(|session| last_sent.and_then(|sent| sent.get(&session.name).cloned()));
947 file_inbound(represented, &native, sender.as_ref(), in_reply_to);
948 }
949 Some(RelayEvent::IdleNotice(text) | RelayEvent::DeliveryNotice(text)) => {
950 file_notice(represented, &text);
951 }
952 _ => {}
953 }
954}
955pub fn parse_inbound_text(text: &str) -> Option<RelayEvent> {
958 let trimmed = text.trim_start();
959 if trimmed.starts_with(NATIVE_IDLE_NOTICE) {
960 return Some(RelayEvent::IdleNotice(trimmed.to_string()));
961 }
962 if trimmed.starts_with(NATIVE_DELIVERY_NOTICE) {
963 return Some(RelayEvent::DeliveryNotice(trimmed.to_string()));
964 }
965 if !trimmed.starts_with(NATIVE_PEER_PREAMBLE) && !trimmed.starts_with(NATIVE_PEER_OPENING) {
966 return None;
967 }
968 let start = text.find(NATIVE_PEER_OPENING)?;
969 let header_end = start + text[start..].find(">\n")?;
970 let header = &text[start + NATIVE_PEER_OPENING.len()..header_end];
971 let body_start = header_end + 2;
972 let body_end = text.rfind(&format!("\n{NATIVE_PEER_CLOSING}"))?;
975 if body_end < body_start {
976 return None;
977 }
978 let attributes = parse_attributes(header);
979 Some(RelayEvent::Peer(NativeEnvelope {
980 from: attributes.get("from")?.clone(),
981 from_name: attributes.get("from-name").cloned(),
982 body: text[body_start..body_end].to_string(),
983 }))
984}
985fn parse_attributes(header: &str) -> BTreeMap<String, String> {
986 let mut attributes = BTreeMap::new();
987 let mut rest = header;
988 while let Some(equals) = rest.find("=\"") {
989 let key = rest[..equals].trim().to_string();
990 let value_start = equals + 2;
991 let Some(length) = rest[value_start..].find('"') else {
992 break;
993 };
994 attributes.insert(key, rest[value_start..value_start + length].to_string());
995 rest = &rest[value_start + length + 1..];
996 }
997 attributes
998}
999fn deliver_home(represented: &MailAddress, envelope: &Envelope) {
1003 if let Err(error) = crate::mailbox::deliver_to(represented, envelope) {
1004 eprintln!(
1005 "could not deliver {} to {represented}: {error}; kept in this machine's mailbox for it",
1006 envelope.id
1007 );
1008 if let Ok(mailbox) = crate::mailbox::Mailbox::open(&mail_root(), represented) {
1009 mailbox.deliver(envelope).ok();
1010 }
1011 return;
1012 }
1013 if represented.machine == crate::mailbox::local_machine_name() {
1018 if let Ok(program) = supercode_program() {
1019 std::process::Command::new(program)
1020 .args(["message", "push", &represented.to_string(), &envelope.id])
1021 .stdin(std::process::Stdio::null())
1022 .stdout(std::process::Stdio::null())
1023 .stderr(std::process::Stdio::null())
1024 .spawn()
1025 .ok();
1026 }
1027 }
1028}
1029fn file_inbound(
1030 represented: &MailAddress,
1031 native: &NativeEnvelope,
1032 sender: Option<&ClaudePeerSession>,
1033 in_reply_to: Option<String>,
1034) {
1035 let machine = crate::mailbox::local_machine_name();
1038 let (from, from_name) = match sender {
1039 Some(session) => (
1040 MailAddress::new(&machine, "claude-code", &session.session_id),
1041 format!("{}@{machine}", session.name),
1042 ),
1043 None => (
1044 MailAddress::new(&machine, "claude-code", "unknown"),
1045 native
1046 .from_name
1047 .clone()
1048 .unwrap_or_else(|| "an unknown Claude session".into()),
1049 ),
1050 };
1051 let Ok(from) = from else { return };
1052 let Ok(mut envelope) = Envelope::new(
1053 from,
1054 from_name,
1055 MailKind::Peer,
1056 ReplyVia::Command,
1057 native.body.clone(),
1058 ) else {
1059 return;
1060 };
1061 envelope.native_from = Some(native.from.clone());
1062 if let Some(in_reply_to) = in_reply_to {
1063 envelope.thread = crate::mailbox::thread_of_reply(Some(&in_reply_to));
1064 envelope.in_reply_to = Some(in_reply_to);
1065 envelope.in_reply_to_inferred = true;
1066 }
1067 deliver_home(represented, &envelope);
1070}
1071fn file_notice(represented: &MailAddress, text: &str) {
1072 let Ok(from) = MailAddress::new(
1073 crate::mailbox::local_machine_name(),
1074 "claude-code",
1075 "notice",
1076 ) else {
1077 return;
1078 };
1079 let Ok(envelope) = Envelope::new(
1080 from,
1081 "Claude Code",
1082 MailKind::Notice,
1083 ReplyVia::None,
1084 text.to_string(),
1085 ) else {
1086 return;
1087 };
1088 deliver_home(represented, &envelope);
1091}
1092pub fn supercode_program() -> std::io::Result<PathBuf> {
1095 let current = std::env::current_exe()?;
1096 if current.file_stem().and_then(|stem| stem.to_str()) == Some("supercode") {
1097 return Ok(current);
1098 }
1099 std::env::var_os("PATH")
1100 .iter()
1101 .flat_map(std::env::split_paths)
1102 .map(|directory| directory.join("supercode"))
1103 .find(|candidate| candidate.is_file())
1104 .ok_or_else(|| {
1105 std::io::Error::new(
1106 std::io::ErrorKind::NotFound,
1107 "the supercode program is not on PATH; Claude relays and the machine daemon need it",
1108 )
1109 })
1110}