Skip to main content

blyte_cli/
tell.rs

1use std::io::{ErrorKind, Read, Write};
2use std::net::{SocketAddr, TcpStream};
3use std::path::{Path, PathBuf};
4use std::time::{Duration, Instant};
5
6use crate::serve::MESSAGE_HEADER;
7
8const TELL_TIMEOUT: Duration = Duration::from_secs(5);
9const MAX_RESPONSE_BYTES: usize = 64 * 1024;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum TellOutcome {
13    Delivered,
14    Held,
15}
16
17fn format_outcome(name: &str, outcome: TellOutcome) -> String {
18    match outcome {
19        TellOutcome::Delivered => format!("delivered to {name}"),
20        TellOutcome::Held => format!(
21            "held by {name}: it has run five turns from other surfaces since its user last wrote; the message waits for its user's next message"
22        ),
23    }
24}
25
26fn parse_status_code(head: &str) -> Result<u16, String> {
27    let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
28    let mut parts = status_line.split_whitespace();
29    let version = parts
30        .next()
31        .ok_or_else(|| "empty HTTP response".to_string())?;
32    if !version.starts_with("HTTP/") {
33        return Err("invalid HTTP response".to_string());
34    }
35    let code_str = parts
36        .next()
37        .ok_or_else(|| "missing HTTP status code".to_string())?;
38    code_str
39        .parse::<u16>()
40        .map_err(|_| "invalid HTTP status code".to_string())
41}
42
43fn post_peer_message(
44    target_name: &str,
45    port: u16,
46    credential: &str,
47    body: &str,
48) -> Result<(u16, String), String> {
49    let deadline = Instant::now() + TELL_TIMEOUT;
50    let addr = SocketAddr::from(([127, 0, 0, 1], port));
51    let mut stream = TcpStream::connect_timeout(&addr, TELL_TIMEOUT).map_err(|e| {
52        if e.kind() == ErrorKind::ConnectionRefused {
53            format!("surface {target_name} refused the connection on port {port}")
54        } else {
55            format!("cannot connect to surface {target_name} on port {port}: {e}")
56        }
57    })?;
58
59    let remaining = deadline.saturating_duration_since(Instant::now());
60    if remaining.is_zero() {
61        return Err(format!("surface {target_name} timed out on port {port}"));
62    }
63    let _ = stream.set_write_timeout(Some(remaining));
64
65    let req = format!(
66        "POST /api/peer/messages HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{MESSAGE_HEADER}: {credential}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
67        body.len()
68    );
69    stream
70        .write_all(req.as_bytes())
71        .map_err(|e| format!("failed to send message to surface {target_name}: {e}"))?;
72
73    let mut raw = Vec::new();
74    let mut chunk = [0u8; 4096];
75    loop {
76        if raw.len() >= MAX_RESPONSE_BYTES {
77            return Err(format!(
78                "surface {target_name} gave an answer blyte does not understand"
79            ));
80        }
81        let remaining = deadline.saturating_duration_since(Instant::now());
82        if remaining.is_zero() {
83            return Err(format!("surface {target_name} timed out on port {port}"));
84        }
85        let _ = stream.set_read_timeout(Some(remaining));
86        let max_read = (MAX_RESPONSE_BYTES - raw.len()).min(chunk.len());
87        match stream.read(&mut chunk[..max_read]) {
88            Ok(0) => break,
89            Ok(n) => raw.extend_from_slice(&chunk[..n]),
90            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
91            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
92                return Err(format!("surface {target_name} timed out on port {port}"));
93            }
94            Err(e) => {
95                return Err(format!(
96                    "failed to read answer from surface {target_name}: {e}"
97                ));
98            }
99        }
100    }
101
102    let text = std::str::from_utf8(&raw)
103        .map_err(|_| format!("surface {target_name} gave an answer blyte does not understand"))?;
104    let (head, resp_body) = text
105        .split_once("\r\n\r\n")
106        .ok_or_else(|| format!("surface {target_name} gave an answer blyte does not understand"))?;
107    let status = parse_status_code(head)
108        .map_err(|_| format!("surface {target_name} gave an answer blyte does not understand"))?;
109    Ok((status, resp_body.to_string()))
110}
111
112pub fn tell(
113    registry_dir: &Path,
114    from_name: &str,
115    from_repository: &str,
116    target: &str,
117    text: &str,
118) -> Result<TellOutcome, String> {
119    let entry = crate::surface_registry::find_by_name(registry_dir, target)?;
120    let cred_path = blyte_agent::sandbox::surface_message_path_for_id(&entry.id)?;
121    let raw_cred = std::fs::read_to_string(&cred_path).map_err(|_| {
122        format!(
123            "surface {} has no usable message credential at {}",
124            entry.name,
125            cred_path.display()
126        )
127    })?;
128    let credential = raw_cred.trim();
129    if credential.is_empty() || credential.contains(['\r', '\n']) {
130        return Err(format!(
131            "surface {} has no usable message credential at {}",
132            entry.name,
133            cred_path.display()
134        ));
135    }
136
137    let body = serde_json::to_string(&serde_json::json!({
138        "from_name": from_name,
139        "from_repository": from_repository,
140        "text": text,
141    }))
142    .map_err(|e| format!("failed to encode peer message: {e}"))?;
143
144    let (status, resp_body) = post_peer_message(&entry.name, entry.port, credential, &body)?;
145    if status != 200 {
146        let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
147            .ok()
148            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
149            .unwrap_or_else(|| {
150                let trimmed = resp_body.trim();
151                if trimmed.is_empty() {
152                    "no error message".to_string()
153                } else {
154                    trimmed.to_string()
155                }
156            });
157        return Err(format!(
158            "surface {} answered {status}: {detail}",
159            entry.name
160        ));
161    }
162
163    let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
164        format!(
165            "surface {} gave an answer blyte does not understand",
166            entry.name
167        )
168    })?;
169    match parsed.get("status").and_then(|v| v.as_str()) {
170        Some("delivered") => Ok(TellOutcome::Delivered),
171        Some("held") => Ok(TellOutcome::Held),
172        _ => Err(format!(
173            "surface {} gave an answer blyte does not understand",
174            entry.name
175        )),
176    }
177}
178
179pub fn run_tell(
180    registry_dir: &Path,
181    target: &str,
182    text: &str,
183    from: &str,
184    out: &mut dyn Write,
185    err: &mut dyn Write,
186) -> i32 {
187    if let Err(e) = crate::surface_dir::validate_surface_name(from) {
188        let _ = writeln!(err, "blyte: {e}");
189        return 1;
190    }
191
192    let from_repository = match std::env::current_dir()
193        .ok()
194        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
195        .filter(|s| !s.is_empty())
196    {
197        Some(name) => name,
198        None => {
199            let _ = writeln!(err, "blyte: cannot name the current directory");
200            return 1;
201        }
202    };
203
204    match tell(registry_dir, from, &from_repository, target, text) {
205        Ok(outcome) => {
206            let _ = writeln!(out, "{}", format_outcome(target, outcome));
207            0
208        }
209        Err(e) => {
210            let _ = writeln!(err, "blyte: {e}");
211            1
212        }
213    }
214}
215
216pub struct SurfacePeerTools {
217    pub registry_dir: PathBuf,
218    pub surface_id: String,
219    pub surface_name: String,
220    pub repository: String,
221}
222
223impl blyte_agent::tools::PeerTools for SurfacePeerTools {
224    fn surfaces(&self) -> Result<String, String> {
225        let entries = crate::surface_registry::live_entries(&self.registry_dir)?;
226        Ok(crate::surfaces_cmd::format_surfaces_table(
227            &entries,
228            Some(&self.surface_id),
229        ))
230    }
231
232    fn tell(&self, name: &str, message: &str) -> Result<String, String> {
233        if name == self.surface_name || name == self.surface_id {
234            return Err("a surface cannot tell itself".to_string());
235        }
236        let outcome = tell(
237            &self.registry_dir,
238            &self.surface_name,
239            &self.repository,
240            name,
241            message,
242        )?;
243        Ok(format_outcome(name, outcome))
244    }
245}