supercode-cli 0.5.14

Volter Harness — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! `supercode message`: cross-session messaging from any agent's shell.
//!
//! The agent-facing half of the mailbox (`supercode_harness::mailbox`). Every
//! coding harness can run a shell command, so this command is the one reply
//! door every harness shares. Its texts are written for the agent that runs
//! it: each outcome says what happened, whether anything was sent, and what
//! (not) to do next, and the exit code says the same for scripts:
//!
//! | exit | meaning |
//! |---|---|
//! | 0 | delivered, queued or held |
//! | 2 | refused |
//! | 3 | unknown or stale address |
//! | 4 | stored, not delivered (the receiver has no delivery door) |
//! | 5 | failed |
//! | 6 | `wait` timed out with no mail |
//!
//! The sender is never declared: it is resolved from this process's ancestry
//! (the harness process that ran the shell), so a reply always has a live
//! address to return to.

use std::io::Read;
use std::path::PathBuf;
use std::time::{Duration, Instant};

use anyhow::{anyhow, Result};
use clap::Subcommand;
use supercode_harness::claude_relay::{gate_decision, gate_denial, QueuedSend};
use supercode_harness::mail_route::{resolve_caller, Caller, Door};
use supercode_harness::mailbox::{
    local_machine_name, mail_root, Envelope, MailAddress, MailKind, Mailbox,
};
use supercode_harness::HarnessHomes;

use supercode_harness::mail_send::{EXIT_REFUSED, EXIT_UNKNOWN};
const EXIT_TIMEOUT: i32 = 6;

/// Longest `wait` a caller may ask for; agents' shell tools time out soon
/// after, and a killed wait reads as a failure.
const MAX_WAIT: Duration = Duration::from_secs(100);

#[derive(Subcommand)]
pub(crate) enum MessageAction {
    /// List the sessions on this machine that can be messaged.
    #[command(alias = "ls")]
    List {
        /// Print JSON instead of a table.
        #[arg(long)]
        json: bool,
    },
    /// Send a message. The body is the argument, or stdin (use a quoted
    /// heredoc for anything with quotes, `$` or several lines), or --file.
    Send {
        /// Receiver: an address (sc:<machine>:<harness>:<id>), name@machine,
        /// or a name that is unique on this machine.
        to: String,
        /// A short body. Omit it to read the body from stdin.
        body: Option<String>,
        /// Read the body from this file.
        #[arg(long, value_name = "PATH", conflicts_with = "body")]
        file: Option<PathBuf>,
        /// Id of the message this one answers.
        #[arg(long = "re", value_name = "MESSAGE_ID")]
        in_reply_to: Option<String>,
        /// Also send one notice to your mailbox when the receiver next goes idle.
        #[arg(long)]
        notify_when_idle: bool,
        /// Only enqueue; never start a turn in an idle receiver.
        #[arg(long)]
        queue: bool,
        /// Idempotency key: repeating a send with the same key does not send twice.
        #[arg(long, value_name = "KEY")]
        id: Option<String>,
    },
    /// Show your unread messages, each with how to answer it.
    Inbox {
        /// Also show messages already read.
        #[arg(long)]
        all: bool,
        /// Print JSON instead of the rendered messages.
        #[arg(long)]
        json: bool,
    },
    /// Wait for the next message (bounded; never polls a session).
    Wait {
        /// Only wake for mail from this sender.
        #[arg(long, value_name = "TO")]
        from: Option<String>,
        /// Seconds to wait, at most 100.
        #[arg(long, default_value_t = 100)]
        timeout: u64,
    },
    /// Set up a harness's delivery door, so messages to its sessions are shown
    /// to them. `codex`: adds supercode's mail hooks to Codex's hooks.json.
    Setup {
        /// Harness to set up (codex).
        harness: String,
    },
    /// A harness hook that points its session at unread mail (internal).
    #[command(hide = true)]
    Hook {
        /// Harness whose hook this is (codex).
        harness: String,
    },
    /// UserPromptSubmit hook of a Claude relay: files inbound mail (internal).
    #[command(hide = true)]
    RelayInbound {
        /// Address of the session the relay speaks for.
        represented: String,
        /// The relay's directory.
        directory: PathBuf,
    },
    /// Deliver one request that arrived through this machine's Teams mail door
    /// (internal).
    #[command(hide = true)]
    RemoteDeliver,
    /// Serve messaging to an agent as MCP tools over stdio: list_agents,
    /// send_message, read_messages (`teams connect --install` registers it
    /// with each harness).
    Mcp,
    /// Deliver one filed message to its session by the session's door, and
    /// mark it read (internal; a relay's hook starts it).
    #[command(hide = true)]
    Push {
        /// The session's address.
        address: String,
        /// The message's id.
        id: String,
    },
    /// PreToolUse hook of a Claude relay (internal).
    #[command(hide = true)]
    Gate {
        /// The relay's directory.
        directory: PathBuf,
    },
    /// PostToolUse and Stop hook of a Claude relay: records Claude's receipt
    /// for the queued send (internal).
    #[command(hide = true)]
    RelayReceipt {
        /// The relay's directory.
        directory: PathBuf,
    },
    /// Watch idle subscriptions and send their notices, type the user's
    /// waiting turns into their panes, and serve the Claude relays' Messages
    /// API (internal; the machine daemon runs it).
    #[command(hide = true)]
    Watch,
}

/// Run one `supercode message` action. Returns the process exit code.
pub(crate) async fn run(action: &MessageAction) -> Result<i32> {
    let homes = HarnessHomes::default();
    match action {
        MessageAction::List { json } => list(&homes, *json),
        MessageAction::Send {
            to,
            body,
            file,
            in_reply_to,
            notify_when_idle,
            queue,
            id,
        } => {
            let body = read_body(body.as_deref(), file.as_ref())?;
            send(
                &homes,
                to,
                &body,
                supercode_harness::mail_send::SendOptions {
                    in_reply_to: in_reply_to.clone(),
                    notify_when_idle: *notify_when_idle,
                    queue: *queue,
                    idempotency_key: id.clone(),
                },
            )
            .await
        }
        MessageAction::Inbox { all, json } => inbox(&homes, *all, *json),
        MessageAction::Wait { from, timeout } => wait(&homes, from.as_deref(), *timeout).await,
        MessageAction::RelayInbound {
            represented,
            directory,
        } => relay_inbound(&homes, represented, directory),
        MessageAction::RemoteDeliver => remote_deliver(&homes).await,
        MessageAction::Push { address, id } => push(&homes, address, id).await,
        MessageAction::Mcp => {
            let cwd = std::env::current_dir().unwrap_or_default();
            supercode_harness::mcp::serve_stdio(
                &supercode_harness::mail_mcp::registry(),
                &supercode_harness::tools::ToolContext::new(cwd),
            )
            .await?;
            Ok(0)
        }
        MessageAction::Gate { directory } => gate(directory),
        MessageAction::RelayReceipt { directory } => relay_receipt(directory),
        MessageAction::Setup { harness } => setup(harness),
        MessageAction::Hook { harness } => hook(harness),
        MessageAction::Watch => {
            tokio::spawn(async {
                if let Err(error) = supercode_harness::relay_endpoint::serve_relay_endpoint().await
                {
                    eprintln!("supercode: the relay endpoint stopped: {error}");
                    std::process::exit(1);
                }
            });
            let mut watcher = supercode_harness::mail_watch::IdleWatcher::new();
            loop {
                watcher.tick(&homes).await;
                supercode_harness::mail_watch::deliver_waiting_user_turns(&homes).await;
                tokio::time::sleep(Duration::from_secs(2)).await;
            }
        }
    }
}

/// The sessions on this machine that can be messaged, as `message list --json` rows.
fn session_rows(homes: &HarnessHomes) -> Vec<serde_json::Value> {
    supercode_harness::mail_route::LiveSessions::read(homes)
        .all()
        .iter()
        .map(|peer| {
            serde_json::json!({
                "name": peer.name,
                "harness": peer.address.harness,
                "status": peer.status,
                "delivery": peer.door.name(),
                "address": peer.address.to_string(),
            })
        })
        .collect()
}

/// The sessions on the team's other online machines, asked of each machine's
/// mail door in parallel; a machine that cannot answer is left out. Empty
/// without a Teams context.
fn team_rows() -> Vec<serde_json::Value> {
    let Ok(program) = supercode_harness::claude_relay::supercode_program() else {
        return Vec::new();
    };
    let Ok(output) = std::process::Command::new(program)
        .args(["teams", "machines", "list", "--json"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
    else {
        return Vec::new();
    };
    let local = supercode_harness::mailbox::local_machine_name();
    let machines: Vec<String> = serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .ok()
        .and_then(|value| value["items"].as_array().cloned())
        .unwrap_or_default()
        .into_iter()
        .filter(|machine| machine["enrollment"] == "active" && machine["connection"] == "online")
        .filter_map(|machine| machine["name"].as_str().map(str::to_string))
        .filter(|name| *name != local)
        .collect();
    let handles: Vec<_> = machines
        .into_iter()
        .map(|machine| {
            std::thread::spawn(move || {
                supercode_harness::mailbox::teams_mail(&machine, &serde_json::json!({"op": "list"}))
                    .ok()
                    .and_then(|answer| answer["sessions"].as_array().cloned())
                    .unwrap_or_default()
            })
        })
        .collect();
    handles
        .into_iter()
        .flat_map(|handle| handle.join().unwrap_or_default())
        .collect()
}

fn list(homes: &HarnessHomes, json: bool) -> Result<i32> {
    let mut rows = session_rows(homes);
    rows.extend(team_rows());
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(0);
    }
    println!(
        "{:<34} {:<12} {:<8} {:<9} ADDRESS",
        "NAME", "HARNESS", "STATUS", "DELIVERY"
    );
    let text =
        |row: &serde_json::Value, key: &str| row[key].as_str().unwrap_or_default().to_string();
    for row in &rows {
        println!(
            "{:<34} {:<12} {:<8} {:<9} {}",
            text(row, "name"),
            text(row, "harness"),
            text(row, "status"),
            text(row, "delivery"),
            text(row, "address")
        );
    }
    Ok(0)
}

fn read_body(body: Option<&str>, file: Option<&PathBuf>) -> Result<String> {
    let text = match (body, file) {
        (Some(body), _) => body.to_string(),
        (None, Some(path)) => std::fs::read_to_string(path)
            .map_err(|error| anyhow!("could not read {}: {error}", path.display()))?,
        (None, None) => {
            let mut text = String::new();
            std::io::stdin().read_to_string(&mut text)?;
            text
        }
    };
    let text = text.trim_end_matches('\n').to_string();
    if text.trim().is_empty() {
        return Err(anyhow!("Nothing was sent: the message is empty."));
    }
    Ok(text)
}

/// Print an outcome for the agent (a success on stdout, anything else on
/// stderr) and return its exit code.
fn print_outcome(outcome: supercode_harness::mail_send::Outcome) -> i32 {
    if outcome.code == 0 {
        println!("{}", outcome.text);
    } else {
        eprintln!("{}", outcome.text);
    }
    outcome.code
}

async fn send(
    homes: &HarnessHomes,
    to: &str,
    body: &str,
    options: supercode_harness::mail_send::SendOptions,
) -> Result<i32> {
    let caller = match resolve_caller(homes, &supercode_harness::mail_route::process_ancestry()) {
        Ok(caller) => caller,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let outcome = supercode_harness::mail_send::send(homes, &caller, to, body, options).await?;
    Ok(print_outcome(outcome))
}

fn caller_mailbox(homes: &HarnessHomes) -> std::result::Result<Mailbox, String> {
    let caller = resolve_caller(homes, &supercode_harness::mail_route::process_ancestry())?;
    Mailbox::open(&mail_root(), &caller.address).map_err(|error| error.to_string())
}

fn inbox(homes: &HarnessHomes, all: bool, json: bool) -> Result<i32> {
    let mailbox = match caller_mailbox(homes) {
        Ok(mailbox) => mailbox,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let claimed = mailbox.claim_unread()?;
    let stored = if all {
        let mut stored: Vec<_> = mailbox
            .list()?
            .into_iter()
            .filter(|stored| stored.state == supercode_harness::mailbox::MailState::Read)
            .collect();
        stored.extend(claimed.iter().cloned());
        stored
    } else {
        claimed.clone()
    };
    if json {
        let rows: Vec<_> = stored
            .iter()
            .map(|stored| {
                serde_json::json!({
                    "state": stored.state,
                    "envelope": stored.envelope,
                    "rendered": stored.envelope.render(),
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else if stored.is_empty() {
        println!("No unread messages.");
    } else {
        for stored in &stored {
            println!("{}\n", stored.envelope.render());
        }
    }
    // Acknowledged only after printing: a crash before this shows them again.
    for stored in &claimed {
        mailbox.acknowledge(stored)?;
    }
    Ok(0)
}

async fn wait(homes: &HarnessHomes, from: Option<&str>, timeout: u64) -> Result<i32> {
    let mailbox = match caller_mailbox(homes) {
        Ok(mailbox) => mailbox,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let sessions = supercode_harness::mail_route::LiveSessions::read(homes);
    let wanted = from.map(|from| match sessions.resolve(from) {
        Ok(session) => session.address.to_string(),
        _ => from.to_string(),
    });
    let limit = Duration::from_secs(timeout).min(MAX_WAIT);
    let started = Instant::now();
    loop {
        let waiting = mailbox.unread()?.into_iter().any(|stored| {
            wanted.as_deref().is_none_or(|wanted| {
                stored.envelope.from.to_string() == wanted
                    || stored.envelope.from_name.starts_with(wanted)
            })
        });
        if waiting {
            // Everything unread is handed over, not only the awaited sender's:
            // a message the agent is not shown now would stay silent.
            let claimed = mailbox.claim_unread()?;
            for stored in &claimed {
                println!("{}\n", stored.envelope.render());
            }
            for stored in &claimed {
                mailbox.acknowledge(stored)?;
            }
            return Ok(0);
        }
        if started.elapsed() >= limit {
            println!(
                "No mail within {} seconds; nothing is lost.",
                limit.as_secs()
            );
            return Ok(EXIT_TIMEOUT);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

fn gate(directory: &std::path::Path) -> Result<i32> {
    let paths = supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf());
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let hook_input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let queued: Option<QueuedSend> = std::fs::read(&paths.queue)
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok());
    if let Some(reason) = gate_decision(&hook_input, queued.as_ref()) {
        // A send that was queued and refused still answers its sender.
        if queued.is_some() && !paths.receipt.exists() {
            std::fs::write(
                &paths.receipt,
                serde_json::json!({"denied": reason}).to_string(),
            )
            .ok();
        }
        println!("{}", gate_denial(&reason));
    }
    Ok(0)
}

/// A relay's PostToolUse (SendMessage) and Stop hook: record Claude's own
/// answer to the queued send, or that the turn ended without one.
fn relay_receipt(directory: &std::path::Path) -> Result<i32> {
    let paths = supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf());
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    if !paths.queue.exists() || paths.receipt.exists() {
        return Ok(0);
    }
    let receipt = match input
        .get("hook_event_name")
        .and_then(serde_json::Value::as_str)
    {
        Some("PostToolUse") => {
            serde_json::json!({"tool_response": input.get("tool_response").cloned().unwrap_or_default()})
        }
        Some("Stop") => serde_json::json!({"turn_ended": true}),
        _ => return Ok(0),
    };
    std::fs::write(&paths.receipt, receipt.to_string())?;
    Ok(0)
}

fn setup(harness: &str) -> Result<i32> {
    if harness != "codex" {
        eprintln!(
            "Nothing to set up for {harness}: claude-code sessions are reached natively, and \
             other harnesses have no delivery door yet."
        );
        return Ok(EXIT_REFUSED);
    }
    let path = supercode_harness::mail_route::codex_hooks_path();
    let original = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => "{}".into(),
        Err(error) => return Err(error.into()),
    };
    let mut document: serde_json::Value = serde_json::from_str(&original)
        .map_err(|error| anyhow!("{} is not valid JSON: {error}", path.display()))?;
    let command = format!(
        "{} {}",
        supercode_harness::claude_relay::supercode_program()?.display(),
        supercode_harness::mail_route::CODEX_HOOK_ARGUMENTS
    );
    let hooks = document
        .as_object_mut()
        .ok_or_else(|| anyhow!("{} must hold a JSON object", path.display()))?
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let mut added = Vec::new();
    for event in ["PostToolUse", "Stop"] {
        let entries = hooks
            .as_object_mut()
            .ok_or_else(|| anyhow!("`hooks` in {} must be an object", path.display()))?
            .entry(event)
            .or_insert_with(|| serde_json::json!([]));
        let list = entries
            .as_array_mut()
            .ok_or_else(|| anyhow!("`hooks.{event}` in {} must be a list", path.display()))?;
        if list.iter().any(|entry| {
            entry
                .to_string()
                .contains(supercode_harness::mail_route::CODEX_HOOK_ARGUMENTS)
        }) {
            continue;
        }
        // Appended, never inserted: Codex keys each hook's trust by its
        // position, so entries already trusted keep their places.
        let mut entry = serde_json::json!({
            "hooks": [{"type": "command", "command": command, "timeout": 10}]
        });
        if event == "PostToolUse" {
            entry["matcher"] = serde_json::json!(".*");
        }
        list.push(entry);
        added.push(event);
    }
    if added.is_empty() {
        println!("supercode's mail hooks are already in {}.", path.display());
    } else {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let temporary = path.with_extension("json.supercode-tmp");
        std::fs::write(&temporary, serde_json::to_string_pretty(&document)? + "\n")?;
        std::fs::rename(&temporary, &path)?;
        println!(
            "Added supercode's mail hooks ({}) to {}.",
            added.join(", "),
            path.display()
        );
    }
    println!(
        "Codex runs a new hook only after its user trusts it: in Codex, open /hooks and trust the \
         supercode entries. Until then, messages to Codex sessions are stored, not shown."
    );
    Ok(0)
}

/// A harness hook: when the session has unread mail, point it there. It
/// never shows or claims a message itself — hook context carries the
/// harness's own authority, so peer text travels only through `inbox`, which
/// wraps it in its trust paragraph.
fn hook(harness: &str) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let Some(session_id) = input.get("session_id").and_then(serde_json::Value::as_str) else {
        return Ok(0);
    };
    let Ok(address) = MailAddress::new(local_machine_name(), harness, session_id) else {
        return Ok(0);
    };
    let mailbox = Mailbox::open(&mail_root(), &address)?;
    let unread = mailbox.unread()?;
    let event = input
        .get("hook_event_name")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    let again = input
        .get("stop_hook_active")
        .and_then(serde_json::Value::as_bool)
        == Some(true);
    if !unread.is_empty() && (event == "PostToolUse" || (event == "Stop" && !again)) {
        let pointer = mail_pointer(&unread);
        let answer = if event == "PostToolUse" {
            serde_json::json!({
                "hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": pointer}
            })
        } else {
            serde_json::json!({"decision": "block", "reason": format!("{pointer} Read them before you finish.")})
        };
        println!("{answer}");
        return Ok(0);
    }
    Ok(0)
}

/// The pointer a hook shows: how many unread messages, from whom, and the
/// one command that reads them. Never the messages themselves — hook context
/// carries the harness's own authority; inbox wraps peer text in its trust
/// paragraph.
fn mail_pointer(unread: &[supercode_harness::mailbox::StoredEnvelope]) -> String {
    let mut senders: Vec<String> = Vec::new();
    for stored in unread {
        let label = match stored.envelope.kind {
            MailKind::Notice => "a notice".to_string(),
            MailKind::User => "your user".to_string(),
            MailKind::Channel => format!("{} (channel)", printable(&stored.envelope.from_name)),
            MailKind::Peer => printable(&stored.envelope.from_name),
        };
        if !senders.contains(&label) {
            senders.push(label);
        }
    }
    format!(
        "You have {} unread message{} from other sessions (from {}). They are not from your user. \
         Read them with: supercode message inbox",
        unread.len(),
        if unread.len() == 1 { "" } else { "s" },
        senders.join(", "),
    )
}

/// A sender name reduced to characters that cannot break out of a hook's
/// sentence.
fn printable(name: &str) -> String {
    name.chars()
        .filter(|character| character.is_ascii_alphanumeric() || "-_.@ ".contains(*character))
        .take(80)
        .collect()
}

/// A relay's UserPromptSubmit hook. Inbound mail (a peer envelope or a
/// notice) is filed in the represented session's mailbox, threaded by the
/// relay's own record of what it sent, and blocked so the relay's model never
/// runs for it. The host's own send turns pass through untouched.
fn relay_inbound(
    homes: &HarnessHomes,
    represented: &str,
    directory: &std::path::Path,
) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let prompt = input
        .get("prompt")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
        .to_string();
    if !supercode_harness::claude_relay::is_inbound_prompt(&prompt) {
        return Ok(0);
    }
    let represented = MailAddress::parse(represented)?;
    let last_sent =
        supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf())
            .last_sent();
    supercode_harness::claude_relay::file_inbound_prompt(
        homes,
        &represented,
        &prompt,
        Some(&last_sent),
    );
    println!("{}", supercode_harness::claude_relay::inbound_block());
    Ok(0)
}

/// A request another machine's `supercode message` sent through this
/// machine's Teams mail door: deliver it here through the same doors a local
/// send uses, and answer `{code, text}` on stdout.
/// One filed message, delivered through its session's door. It stays in the
/// mailbox, unread, when no door reaches the session or delivery fails.
async fn push(homes: &HarnessHomes, address: &str, id: &str) -> Result<i32> {
    let to = MailAddress::parse(address).map_err(|error| anyhow!("{error}"))?;
    let mailbox = Mailbox::open(&mail_root(), &to)?;
    let Some(stored) = mailbox.find(id)? else {
        return Ok(0);
    };
    if stored.state != supercode_harness::mailbox::MailState::Unread {
        return Ok(0);
    }
    // Only doors that hand a message to the session take it from here; for
    // the rest (an operator's inbox, a Codex hook, no door) the mailbox is
    // where it is read, and it stays unread there.
    let door = match supercode_harness::mail_route::door_for(homes, &to) {
        Ok(door @ (Door::Native(_) | Door::Runtime(_))) => door,
        _ => return Ok(0),
    };
    match supercode_harness::mail_route::deliver(&stored.envelope, &to, &door, true, false).await {
        Ok(Ok(_)) => {
            mailbox.mark_read(&stored)?;
            Ok(0)
        }
        Ok(Err(refused)) => {
            eprintln!("supercode: {id} stays in {to}'s mailbox: {refused:?}");
            Ok(supercode_harness::mail_send::EXIT_REFUSED)
        }
        Err(error) => {
            eprintln!("supercode: {id} stays in {to}'s mailbox: {error}");
            Ok(supercode_harness::mail_send::EXIT_FAILED)
        }
    }
}

async fn remote_deliver(homes: &HarnessHomes) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let request: serde_json::Value = serde_json::from_str(&input)?;
    // The sessions here a caller with this machine's mail door can message.
    if request["op"].as_str() == Some("list") {
        println!(
            "{}",
            serde_json::json!({"code": 0, "sessions": session_rows(homes)})
        );
        return Ok(0);
    }
    let outcome = match request["op"].as_str() {
        Some("file") => {
            let to = MailAddress::parse(request["to"].as_str().unwrap_or_default())?;
            let envelope: Envelope = serde_json::from_value(request["envelope"].clone())?;
            if to.machine != local_machine_name() {
                supercode_harness::mail_send::Outcome::new(
                    EXIT_UNKNOWN,
                    format!("{to} is not on this machine."),
                )
            } else {
                Mailbox::open(&mail_root(), &to)?.deliver(&envelope)?;
                supercode_harness::mail_send::Outcome::new(0, format!("filed for {to}"))
            }
        }
        Some("send") => {
            let caller = Caller {
                address: MailAddress::parse(request["from"].as_str().unwrap_or_default())?,
                name: request["from_name"]
                    .as_str()
                    .unwrap_or_default()
                    .to_string(),
            };
            supercode_harness::mail_send::send(
                homes,
                &caller,
                request["to"].as_str().unwrap_or_default(),
                request["body"].as_str().unwrap_or_default(),
                supercode_harness::mail_send::SendOptions {
                    in_reply_to: request["in_reply_to"].as_str().map(str::to_string),
                    notify_when_idle: request["notify_when_idle"].as_bool().unwrap_or(false),
                    queue: request["queue"].as_bool().unwrap_or(false),
                    idempotency_key: request["id"].as_str().map(str::to_string),
                },
            )
            .await?
        }
        _ => supercode_harness::mail_send::Outcome::new(
            EXIT_REFUSED,
            "Not sent: the mail door takes send or file.",
        ),
    };
    println!(
        "{}",
        serde_json::json!({"code": outcome.code, "text": outcome.text})
    );
    Ok(0)
}