1use std::path::PathBuf;
8
9use crate::mail_route::{Caller, LiveSessions, Unresolved};
10use crate::mailbox::{
11 local_machine_name, mail_root, Envelope, MailAddress, MailKind, Mailbox, ReplyVia,
12};
13use crate::HarnessHomes;
14
15pub const EXIT_REFUSED: i32 = 2;
17pub const EXIT_UNKNOWN: i32 = 3;
19pub const EXIT_STORED: i32 = 4;
21pub const EXIT_FAILED: i32 = 5;
23
24pub struct Outcome {
26 pub code: i32,
29 pub text: String,
31}
32
33impl Outcome {
34 pub fn new(code: i32, text: impl Into<String>) -> Self {
36 Self {
37 code,
38 text: text.into(),
39 }
40 }
41}
42
43#[derive(Debug, Clone, Default)]
45pub struct SendOptions {
46 pub in_reply_to: Option<String>,
48 pub notify_when_idle: bool,
50 pub queue: bool,
52 pub idempotency_key: Option<String>,
54}
55
56pub async fn send(
60 homes: &HarnessHomes,
61 caller: &Caller,
62 to: &str,
63 body: &str,
64 options: SendOptions,
65) -> std::io::Result<Outcome> {
66 let SendOptions {
67 in_reply_to,
68 notify_when_idle,
69 queue,
70 idempotency_key,
71 } = options;
72 if let Some(machine) = remote_machine(to) {
73 let request = serde_json::json!({
74 "op": "send",
75 "from": caller.address.to_string(),
76 "from_name": caller.name,
77 "to": to,
78 "body": body,
79 "in_reply_to": in_reply_to,
80 "notify_when_idle": notify_when_idle,
81 "queue": queue,
82 "id": idempotency_key,
83 });
84 return Ok(remote_send(&machine, &request));
85 }
86 deliver(
87 homes,
88 caller,
89 to,
90 body,
91 in_reply_to,
92 notify_when_idle,
93 queue,
94 idempotency_key,
95 )
96 .await
97}
98
99fn remote_machine(to: &str) -> Option<String> {
101 let local = local_machine_name();
102 let machine = match MailAddress::parse(to) {
103 Ok(address) => address.machine,
104 Err(_) => to.rsplit_once('@')?.1.to_string(),
105 };
106 (machine != local).then_some(machine)
107}
108
109fn remote_send(machine: &str, request: &serde_json::Value) -> Outcome {
111 match crate::mailbox::teams_mail(machine, request) {
112 Ok(answer) => Outcome::new(
113 answer["code"]
114 .as_i64()
115 .map_or(EXIT_FAILED, |code| code as i32),
116 answer["text"]
117 .as_str()
118 .or_else(|| answer["detail"].as_str())
119 .unwrap_or("the other machine answered nothing readable")
120 .to_string(),
121 ),
122 Err(detail) if detail.contains("no mail grant") => Outcome::new(
123 EXIT_REFUSED,
124 format!(
125 "Not sent: machine {machine} does not accept mail from you (no mail grant). Only \
126 an operator can grant it; tell your user. Don't retry."
127 ),
128 ),
129 Err(detail) => Outcome::new(
130 EXIT_FAILED,
131 format!("Not sent to machine {machine}: {detail}"),
132 ),
133 }
134}
135
136#[allow(clippy::too_many_arguments)]
139async fn deliver(
140 homes: &HarnessHomes,
141 caller: &Caller,
142 to: &str,
143 body: &str,
144 in_reply_to: Option<String>,
145 notify_when_idle: bool,
146 queue: bool,
147 idempotency_key: Option<String>,
148) -> std::io::Result<Outcome> {
149 use crate::mail_route::{deliver as route, door_for, Delivered, Refused};
150 let local_operator = to
155 .strip_prefix("operator:")
156 .and_then(|name| MailAddress::new(local_machine_name(), "operator", name).ok());
157 let (address, name) = match local_operator
158 .map(Ok)
159 .unwrap_or_else(|| MailAddress::parse(to))
160 {
161 Ok(address) if address.harness == "operator" => {
162 let name = format!("{}@{}", address.session_id, address.machine);
163 (address, name)
164 }
165 _ => match LiveSessions::read(homes).resolve(to) {
166 Ok(session) => (session.address.clone(), session.name.clone()),
167 Err(Unresolved::Stale(message) | Unresolved::Unknown(message)) => {
168 return Ok(Outcome::new(EXIT_UNKNOWN, message));
169 }
170 },
171 };
172 if address == caller.address {
173 return Ok(Outcome::new(
174 EXIT_REFUSED,
175 "Not sent: that address is your own session.",
176 ));
177 }
178 let door = match door_for(homes, &address) {
179 Ok(door) => door,
180 Err(_) => {
181 return Ok(Outcome::new(
182 EXIT_UNKNOWN,
183 format!(
184 "{name} is no longer running. Nothing was sent. Run supercode message list for \
185 the live sessions."
186 ),
187 ))
188 }
189 };
190 let message_id = match &idempotency_key {
191 Some(key) => format!(
192 "m-{}",
193 &blake3::hash(format!("{}\0{key}", caller.address).as_bytes()).to_hex()[..24]
194 ),
195 None => crate::mailbox::new_message_id()?,
196 };
197 let sent_marker = sent_marker(&caller.address, &message_id);
198 if let Ok(previous) = std::fs::read_to_string(&sent_marker) {
199 return Ok(Outcome::new(
200 0,
201 format!(
202 "Already sent with --id {}: {previous} Nothing was sent again.",
203 idempotency_key.as_deref().unwrap_or_default()
204 ),
205 ));
206 }
207 let in_reply_to = match in_reply_to {
212 Some(answered) if answered.len() < FULL_ID_LEN => {
213 let found = Mailbox::open(&mail_root(), &caller.address)
214 .and_then(|mailbox| mailbox.find_prefix(&answered))
215 .unwrap_or_default();
216 match found.as_slice() {
217 [only] => Some(only.envelope.id.clone()),
218 [] => {
219 return Ok(Outcome::new(
220 EXIT_REFUSED,
221 format!(
222 "Not sent: no message in your mailbox has an id starting {answered}. \
223 Name the message you answer as its envelope shows it."
224 ),
225 ))
226 }
227 many => {
228 let ids: Vec<&str> = many
229 .iter()
230 .map(|stored| stored.envelope.id.as_str())
231 .collect();
232 return Ok(Outcome::new(
233 EXIT_REFUSED,
234 format!(
235 "Not sent: {answered} names {} messages in your mailbox ({}). Give \
236 more of its id.",
237 ids.len(),
238 ids.join(", ")
239 ),
240 ));
241 }
242 }
243 }
244 other => other,
245 };
246 if let Some(answered) = in_reply_to.as_deref() {
247 if reply_chain_depth(&caller.address, &address, answered) >= REPLY_CHAIN_LIMIT {
248 return Ok(Outcome::new(
249 EXIT_REFUSED,
250 format!(
251 "Not sent: you and {name} have answered each other {REPLY_CHAIN_LIMIT} times \
252 in a row. If you are trading acknowledgements or status, stop; to go on, \
253 send a new message (without --re), or tell your user."
254 ),
255 ));
256 }
257 }
258 let mut envelope = Envelope::new(
259 caller.address.clone(),
260 caller.name.clone(),
261 MailKind::Peer,
262 ReplyVia::Command,
263 body,
264 )?;
265 envelope.id = message_id.clone();
266 envelope.in_reply_to = in_reply_to;
267 let tier = door.name();
268 let idle_note = if notify_when_idle {
269 " Subscribed: one idle notice reaches you when its next turn ends."
270 } else {
271 ""
272 };
273 let (code, what) = match route(&envelope, &address, &door, !queue, notify_when_idle).await {
274 Err(detail) => {
275 return Ok(Outcome::new(
276 EXIT_FAILED,
277 format!("Not sent to {name}: {detail}"),
278 ))
279 }
280 Ok(Err(Refused::CannotQueueNative)) => {
281 return Ok(Outcome::new(
282 EXIT_REFUSED,
283 format!(
284 "Not sent: {name} is idle, and a Claude session always starts a turn when a \
285 message arrives, so --queue cannot hold it. Send without --queue to wake it."
286 ),
287 ))
288 }
289 Ok(Err(Refused::TooLong(bytes))) => {
290 return Ok(Outcome::new(
291 EXIT_REFUSED,
292 format!(
293 "Not sent: the message is {bytes} bytes; the limit is {}. Write it to a file \
294 and send its path instead.",
295 crate::mail_route::MAX_RELAYED_BYTES
296 ),
297 ))
298 }
299 Ok(Ok(Delivered::Steered)) => (0, "steered into its running turn"),
300 Ok(Ok(Delivered::Started)) => (0, "it was idle, so the message started a turn"),
301 Ok(Ok(Delivered::Native { busy: true })) => (0, "it will read it at its next tool call"),
302 Ok(Ok(Delivered::Native { busy: false })) => {
303 (0, "it was idle, so the message starts its next turn")
304 }
305 Ok(Ok(Delivered::Hooked)) => (
306 0,
307 "its hook points it at the message at its next tool call, or when its turn ends; an \
308 idle session sees it on its next turn",
309 ),
310 Ok(Ok(Delivered::Queued)) => (
311 0,
312 "it is idle and --queue leaves it so; the message waits in its mailbox",
313 ),
314 Ok(Ok(Delivered::Operator)) => (0, "filed in its mailbox"),
315 Ok(Ok(Delivered::Stored)) => (
316 EXIT_STORED,
317 "Stored (not failed): it has no delivery door, so it sees this only if it runs \
318 supercode message inbox (a Codex session gets one with: supercode message setup \
319 codex). Don't resend, and don't wait for a reply",
320 ),
321 };
322 record_send(&caller.address, &address, &message_id);
323 let shown_id = crate::mailbox::short_id(&message_id);
324 let text = if code == 0 {
325 format!(
326 "sent to {name} ({}, {tier}): {what}. Message id {shown_id}.{idle_note} Don't poll; \
327 carry on.",
328 address.harness
329 )
330 } else {
331 format!(
332 "{name} ({}): {what}. Message id {shown_id}.{idle_note}",
333 address.harness
334 )
335 };
336 if code == 0 && idempotency_key.is_some() {
337 if let Some(parent) = sent_marker.parent() {
338 std::fs::create_dir_all(parent).ok();
339 }
340 std::fs::write(&sent_marker, &text).ok();
341 }
342 Ok(Outcome::new(code, text))
343}
344
345const REPLY_CHAIN_LIMIT: usize = 32;
350
351const FULL_ID_LEN: usize = 26;
353
354fn reply_chain_depth(a: &MailAddress, b: &MailAddress, answered: &str) -> usize {
358 let mut links = std::collections::HashMap::new();
359 for address in [a, b] {
360 let Ok(mailbox) = Mailbox::open(&mail_root(), address) else {
361 continue;
362 };
363 for stored in mailbox.list().unwrap_or_default() {
364 links.insert(
365 stored.envelope.id.clone(),
366 stored.envelope.in_reply_to.clone(),
367 );
368 }
369 }
370 let mut depth = 0;
371 let mut current = Some(answered.to_string());
372 while let Some(id) = current {
373 if depth > REPLY_CHAIN_LIMIT || !links.contains_key(&id) {
374 break;
375 }
376 depth += 1;
377 current = links.get(&id).cloned().flatten();
378 }
379 depth
380}
381
382fn send_log(sender: &MailAddress) -> PathBuf {
383 let hash = blake3::hash(sender.to_string().as_bytes()).to_hex();
384 mail_root().join("sent").join(&hash[..24]).join("log.jsonl")
385}
386
387fn record_send(sender: &MailAddress, to: &MailAddress, message_id: &str) {
388 let log = send_log(sender);
389 if let Some(parent) = log.parent() {
390 std::fs::create_dir_all(parent).ok();
391 }
392 if let Ok(mut file) = std::fs::OpenOptions::new()
393 .create(true)
394 .append(true)
395 .open(&log)
396 {
397 use std::io::Write as _;
398 let entry = serde_json::json!({"to": to.to_string(), "at_ms": now_ms(), "id": message_id});
399 writeln!(file, "{entry}").ok();
400 }
401}
402
403fn now_ms() -> u64 {
404 std::time::SystemTime::now()
405 .duration_since(std::time::UNIX_EPOCH)
406 .map(|elapsed| elapsed.as_millis() as u64)
407 .unwrap_or_default()
408}
409
410fn sent_marker(sender: &MailAddress, message_id: &str) -> PathBuf {
412 let hash = blake3::hash(sender.to_string().as_bytes()).to_hex();
413 mail_root().join("sent").join(&hash[..24]).join(message_id)
414}