Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
Teams without a relay of their own use Reason's, not n0's
Lars Talian75ee9bc4703b
diff --git a/DESIGN.md b/DESIGN.mdindex ce89674..50223a9 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -87,13 +87,19 @@ SDK) both exist and work today. Zig has neither, which is why agent-rpc's MCP sh**Transport: iroh 1.3.** Each daemon is an iroh `Endpoint` with a persistent secret key(`~/.reason/network/machine.key`). Peers are dialed by `EndpointId`; iroh resolves addresses via n0 DNS/pkarr, findsLAN peers with `iroh-mdns-address-lookup` (works with no internet), hole-punches, and falls back to a relay-over HTTPS. Default relays are n0's public ones (they only see encrypted QUIC). A team can set its own relay+over HTTPS. Relays only see encrypted QUIC. The default relay is Reason's (`DEFAULT_RELAYS` in `src/net.rs`, a list+so more regions can join), as n0's public relays are rate-limited and meant for development. A team without its own+relay still looks addresses up on n0's DNS, where each machine publishes its home relay: that is how a machine on+Reason's relay and one of an older build, on n0's, find each other (iroh dials a peer through whichever relay it is+on), and what a four-word code needs. Teammates are also dialed through the default relay itself, so machines of this+build find each other even without that lookup. A team can set its own relay(`reason-network relay <url>` or `reason-network init --relay <url>`; the `iroh-relay` binary on any VPS, Let's Encrypt on :443,access limited to the roster's endpoint ids). Then its machines never contact n0: they use only that relay(teammates are dialed through it) and mDNS on the LAN, and invites come in the long form, since a four-word codeneeds n0's lookup. A machine that was off while the team switched relays can't find it on its own; `reason-network doctor`there says to set the same relay with `reason-network relay`.-That is the "HTTPS and local network, MagicDNS style" requirement with one stack and no server we must run.+That is the "HTTPS and local network, MagicDNS style" requirement with one stack, and a relay as the only server+(Reason's, or the team's own).**Roster (membership).** Replicated to every machine, every entry signed by a member machine's key:- *admissions*: how each machine got in (the founder's self-signed entry, then each admission signed by an@@ -276,8 +282,8 @@ not approve. Nothing changes how an agent works when it isn't messaging.terminal, or `--from <you>/terminal` from a script. A machine also refuses a group message from a teammate's agent(an older Reason Network's). It doesn't stop a teammate's agent from messaging your sessions one by one; the loop guardand the inbound policy cover that.-- Nothing is sent to any service we run. Relays see ciphertext only. With its own relay, a team's machines never- contact n0 either.+- Relays see ciphertext only (and which machines talk to which); the default one is Reason's. With its own relay, a+ team's machines contact neither Reason's relay nor n0.## Install UX (M3)diff --git a/README.md b/README.mdindex ce09014..c417d4c 100644--- a/README.md+++ b/README.md@@ -65,8 +65,9 @@ With the Reason CLI, `reason network who` and `reason network send` work too, anEach computer runs a small daemon. Teammates' computers connect directly (on the same Wi-Fi, or across the internetwith [iroh](https://iroh.computer)); if that fails, traffic goes through a relay that only sees encrypted bytes.-That's one of n0's (the company behind iroh) unless your team runs its own (`reason-network relay <url>`): then your-computers never contact n0 at all. Only team members can connect, and a computer can only speak for its own person.+That's Reason's, with computers finding each other through the address lookup of n0 (the company behind iroh), unless+your team runs its own relay (`reason-network relay <url>`): then your computers contact nothing else, n0 included.+Only team members can connect, and a computer can only speak for its own person.Messages to someone offline wait and go out when they're back.Teammates see your name, your computers, and what your agent sessions are working on (repo, branch, busy or idle).diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rsindex 8f284d6..597bf0a 100644--- a/src/daemon/teamops.rs+++ b/src/daemon/teamops.rs@@ -595,7 +595,10 @@ impl Daemon {self.restart_soon();let (now, cmd) = match &url {Some(u) => (format!("The team now uses relay {u}, and nothing of n0's."), format!("{CLI} relay {u}")),- None => ("The team now uses n0's public relays.".into(), format!("{CLI} relay default")),+ None => (+ format!("The team now uses relay {}.", crate::render::default_relays()),+ format!("{CLI} relay default"),+ ),};let mut out = format!("{now} Team links from before stop working: `{CLI} link` shows the new one.");// A machine that is off can't hear about it, and won't find the team where it looks when it's back.diff --git a/src/main.rs b/src/main.rsindex d978631..a34f8db 100644--- a/src/main.rs+++ b/src/main.rs@@ -227,7 +227,7 @@ enum Cmd {#[arg(long)]force: bool,},- /// Use your own iroh relay for the team, so its machines never contact n0 (or `default` for n0's public relays)+ /// Use your own iroh relay for the team, so its machines never contact n0 (or `default` for Reason's relay)Relay { url: String },/// List messages waiting for your approval (when `inbound` is `hold`)Held,diff --git a/src/net.rs b/src/net.rsindex dcd7e55..f884617 100644--- a/src/net.rs+++ b/src/net.rs@@ -36,6 +36,12 @@ const MAX_FRAME: usize = 4 << 20;const ACK_TIMEOUT: Duration = Duration::from_secs(5);/// Two machines that dial each other at once open their connections within this long of each other.const DIALED_TOGETHER: Duration = Duration::from_secs(5);+/// The relays of a team that doesn't run its own: Reason's. n0's public ones are rate-limited and meant for testing.+pub const DEFAULT_RELAYS: &[&str] = &["https://relay-sfo1.compute.reasonmachines.com"];++pub fn default_relays() -> Vec<RelayUrl> {+ DEFAULT_RELAYS.iter().map(|u| u.parse().expect("default relays are urls")).collect()+}#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(tag = "t", rename_all = "snake_case")]@@ -103,8 +109,8 @@ struct Link {pub struct Net {endpoint: Endpoint,- /// The team's own relay, if it has one: teammates are dialed through it, as nothing looks them up on n0's DNS.- relay: Option<RelayUrl>,+ /// Where teammates are dialed: the team's own relay (nothing looks them up on n0's DNS then), or the default ones.+ relays: Vec<RelayUrl>,router: Mutex<Option<Router>>,/// Endpoints listening for joins on behalf of invite codes, by their (code-derived) id.invites: Mutex<HashMap<EndpointId, Router>>,@@ -122,7 +128,9 @@ pub struct Net {pub async fn bind(key: SecretKey, relay: Option<&str>, lan: bool) -> Result<Endpoint> {let Some(url) = relay else {- let mut b = Endpoint::builder(presets::N0).secret_key(key);+ // The default relays, with n0's address lookup still: that is how a teammate on an older Reason Network (on+ // n0's relays) and this machine find each other, and what four-word codes need.+ let mut b = Endpoint::builder(presets::N0).secret_key(key).relay_mode(RelayMode::custom(default_relays()));if lan {b = b.address_lookup(MdnsAddressLookup::builder());}@@ -346,7 +354,7 @@ impl Net {)),invites: Default::default(),endpoint,- relay: relay.and_then(|u| u.parse().ok()),+ relays: relay.map_or_else(default_relays, |u| u.parse().into_iter().collect()),daemon: Arc::downgrade(daemon),links: Default::default(),remote: Mutex::new(remote),@@ -509,8 +517,9 @@ impl Net {}async fn dial(self: Arc<Self>, id: EndpointId) {+ // On the default relays, n0's address lookup runs too: a teammate may be on n0's (an older Reason Network).let mut addr = EndpointAddr::new(id);- if let Some(url) = &self.relay {+ for url in &self.relays {addr = addr.with_relay_url(url.clone());}match tokio::time::timeout(Duration::from_secs(20), self.endpoint.connect(addr, ALPN)).await {@@ -755,6 +764,14 @@ mod tests {}}+ #[test]+ fn the_default_relay_is_reasons_and_none_of_n0s() {+ let relays = default_relays();+ assert_eq!(relays.len(), DEFAULT_RELAYS.len());+ assert_eq!(relays[0].to_string(), "https://relay-sfo1.compute.reasonmachines.com/");+ assert!(relays.iter().all(|u| u.scheme() == "https" && !u.as_str().contains(".n0.iroh.link")));+ }+#[test]fn a_stale_connection_is_replaced_but_a_simultaneous_dial_is_dropped() {let (a, b) = (SecretKey::generate().public(), SecretKey::generate().public());diff --git a/src/render.rs b/src/render.rsindex a30f04b..ae923f1 100644--- a/src/render.rs+++ b/src/render.rs@@ -201,10 +201,15 @@ fn link(m: &MachineInfo, now: i64) -> String {m.last_seen.map_or_else(|| "not seen yet".to_string(), |t| format!("offline {}", util::ago(t, now)))}+/// What a team that doesn't run its own relay uses.+pub fn default_relays() -> String {+ format!("{} (Reason's, the default)", crate::net::DEFAULT_RELAYS.join(", "))+}+pub fn team(t: &TeamInfo) -> String {let now = util::now_ms();let mut out = String::new();- let relay = t.relay.as_deref().unwrap_or("n0 public relays");+ let relay = t.relay.clone().unwrap_or_else(default_relays);let _ = writeln!(out, "team {} · relay: {relay}", t.name);let pw = t.machines.iter().map(|m| person(m).chars().count()).max().unwrap_or(0);let mw = t.machines.iter().map(|m| m.machine.chars().count()).max().unwrap_or(0);@@ -369,6 +374,26 @@ pub fn unread_notice(u: &Unread) -> Option<String> {mod tests {use super::*;+ #[test]+ fn a_team_shows_its_relay_or_the_default() {+ let mut t = TeamInfo {+ id: "00112233445566778899aabbccddeeff".into(),+ name: "vibes".into(),+ team_name: "vibes".into(),+ relay: None,+ relay_connected: None,+ person: "alex".into(),+ machine: "mbp".into(),+ machines: Vec::new(),+ };+ assert_eq!(+ team(&t),+ "team vibes · relay: https://relay-sfo1.compute.reasonmachines.com (Reason's, the default)\n"+ );+ t.relay = Some("https://relay.example.com".into());+ assert_eq!(team(&t), "team vibes · relay: https://relay.example.com\n");+ }+#[test]fn frames_cant_be_broken() {assert_eq!(diff --git a/src/setup.rs b/src/setup.rsindex 7fc608f..6963650 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -1440,9 +1440,8 @@ pub async fn doctor() -> Result<()> {let others = t.machines.len().saturating_sub(1);println!("✓ daemon running; team {} with {others} other machine(s), {online} connected", t.name);print!("{}", render::team(&t).lines().skip(1).map(|l| format!("{l}\n")).collect::<String>());- if let Some(relay) = &t.relay- && t.relay_connected == Some(false)- {+ if t.relay_connected == Some(false) {+ let relay = t.relay.clone().unwrap_or_else(render::default_relays);println!(" ! can't reach the team's relay {relay}: until it's up, teammates are only found on this network");@@ -1455,7 +1454,7 @@ pub async fn doctor() -> Result<()> {println!(" ! if the team changed relays while this machine was off, set the same one here: `{CLI} relay <url>`");- println!(" (or `default` for n0's); `{CLI} team` on a teammate's machine shows which");+ println!(" (or `default` for Reason's); `{CLI} team` on a teammate's machine shows which");}}Err(e) if e.to_string().contains("not in a team") => {diff --git a/src/team.rs b/src/team.rsindex 150a92d..949fb4a 100644--- a/src/team.rs+++ b/src/team.rs@@ -46,7 +46,7 @@ impl<T: Serialize> Signed<T> {pub struct Meta {pub name: String,/// A self-hosted iroh relay for the team (`https://relay.example.com`), which is then all its machines use: they- /// never contact n0. n0's public relays otherwise.+ /// never contact n0. The default relays otherwise (`net::DEFAULT_RELAYS`; an older Reason Network uses n0's).pub relay: Option<String>,pub ts: i64,}@@ -945,6 +945,32 @@ mod tests {assert_eq!(Ticket::decode(&t.encode()).unwrap(), t);}+ #[test]+ fn a_link_from_a_machine_on_the_default_relay_names_it_as_a_hint() {+ let (a, b, c) = (key(), key(), key());+ let default = crate::net::default_relays()[0].to_string();+ let t = Ticket {+ team: "00112233445566778899aabbccddeeff".into(),+ name: "vibes".into(),+ secret: random_secret(),+ // The team runs no relay of its own: nothing to name here, as before.+ relay: None,+ hint_relay: Some(default.clone()),+ hint_ips: vec!["192.168.1.20:51234".parse().unwrap()],+ peers: vec![a.public(), b.public(), c.public()],+ };+ let enc = t.encode();+ assert!(enc.len() < 300, "short enough for a link: {}", enc.len());+ // Spelled out, which every earlier build reads, unlike a marker of its own would be.+ let raw = BASE64URL_NOPAD.decode(enc.strip_prefix(TICKET_PREFIX).unwrap().as_bytes()).unwrap();+ assert!(raw.windows(default.len()).any(|w| w == default.as_bytes()));+ assert_eq!(Ticket::decode(&enc).unwrap(), t);+ // The machine that made it is dialed there; the others are looked up.+ let addrs = t.addrs();+ assert_eq!(addrs[0].relay_urls().map(|u| u.to_string()).collect::<Vec<_>>(), [default]);+ assert!(addrs[1..].iter().all(|a| a.relay_urls().next().is_none()));+ }+#[test]fn team_link_is_reusable_until_replaced() {let (a, b, c, d) = (key(), key(), key(), key());diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex 9b15db9..91d841d 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -5,7 +5,7 @@Needs internet (iroh relays/discovery). Run inside a Claude Code session, the simulated Claude session pushes itstest messages into that real session (they say "ignore this")."""-import json, os, re, subprocess, sys, tempfile, time+import base64, json, os, re, subprocess, sys, tempfile, timesys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from proofs import TRUST, proof@@ -114,6 +114,18 @@ def shown(who):time.sleep(0.5)p = os.path.join(D, f"notify-{who}.log")return open(p).read() if os.path.exists(p) else ""+++def link_relays(link):+ """A team link's relay fields: the team's own, and the inviting machine's (0xFF: one of n0's, by region)."""+ t = re.split(r"#rn1-|#tincan1", link)[1]+ raw, at, fields = base64.urlsafe_b64decode(t + "=" * (-len(t) % 4)), 32, []+ for _ in range(3): # the team name first+ short = raw[at] == 0xFF+ at += short+ fields.append(("n0 " if short else "") + raw[at + 1:at + 1 + raw[at]].decode())+ at += 1 + raw[at]+ return fields[1:]os.makedirs(os.path.join(D, "work"), exist_ok=True)# --- team formation, signed in with Reason ---@@ -140,6 +152,8 @@ out = cli("alice", "team")check("joiner sees alex connected, verified", re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", out) is not None, out)out = cli("alex", "team")check("founder sees alice connected, verified", re.search(r"alice \(verified\)\s+desktop\s+(direct|relay)", out) is not None, out)+check("a team without a relay of its own is on Reason's: the link names it as where alex is",+ link_relays(link.group(1)) == ["", "https://relay-sfo1.compute.reasonmachines.com/"] and "(Reason's, the default)" in out, out)j = as_json(cli("alex", "team", "--json"))check("team --json marks people verified, and each machine's proof", [(m["verified"], m["has_proof"]) for m in j.get("members", [])] == [(True, True)] * 2and j.get("link", "").startswith("https://") and j.get("team_name") == "vibes" and len(j.get("team_id", "")) == 32, j)