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
Review fixes: the copy becomes a link once agents and service moved
Lars Talian16680c5dd224
diff --git a/DESIGN.md b/DESIGN.mdindex 8bf6794..4688a51 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -69,13 +69,13 @@ unread mail**, so "tell the api agent X" survives restarts (idea from agentbus).One static Rust binary, `reason-network` (fronted by `reason network` where the Reason CLI is installed), withsubcommands:-- `reason network daemon`: per machine. Owns the iroh endpoint, roster, directory, mailboxes (SQLite). Started on+- `reason-network daemon`: per machine. Owns the iroh endpoint, roster, directory, mailboxes (SQLite). Started ondemand by any other subcommand, or installed as a launchd/systemd user service (on Windows, started at logonfrom the user's Run key; there the local socket is a named pipe).-- `reason network mcp`: stdio MCP server spawned by the agent. Thin client of the daemon. **Must handle many+- `reason-network mcp`: stdio MCP server spawned by the agent. Thin client of the daemon. **Must handle manysessions per process**: Codex, opencode and Cursor share one MCP process across threads/tabs.-- `reason network hook <agent>`: hook handler (status, context injection, stop-continuation, wake).-- `reason network who | send | listen | status | init | invite | join | setup | doctor`: the CLI. `send` goes out as+- `reason-network hook <agent>`: hook handler (status, context injection, stop-continuation, wake).+- `reason-network who | send | listen | status | init | invite | join | setup | doctor`: the CLI. `send` goes out asthe agent session whose shell runs it, `--from <session>`, or from a plain terminal as `<you>/terminal`;`listen --as <name>` waits for the next message to `<you>/<name>`.@@ -88,11 +88,11 @@ SDK) both exist and work today. Zig has neither, which is why agent-rpc's MCP sh(`~/.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 relayover HTTPS. Default relays are n0's public ones (they only see encrypted QUIC). 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,+(`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 code-needs 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`.+needs 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.**Roster (membership).** Replicated to every machine, every entry signed by a member machine's key:@@ -113,9 +113,9 @@ that was removed while away is first sent the state that says so; strangers lear**Invites.** The main way in is the **team link**: `https://<site>/join/#<ticket>`, where the ticket packs theteam id, the team link's secret, the inviting machine's relay and LAN address hints, and up to six members' keys.The link secret is a reusable invite in the team state (any member can show the link and any online member can-redeem it), replaced with `reason network link --new` and whenever someone is removed; removed machines are never sent it.+redeem it), replaced with `reason-network link --new` and whenever someone is removed; removed machines are never sent it.The page shows one command (`curl … install.sh | sh -s -- <ticket>`); the joiner only types a name. Four-word-one-time codes (`reason network invite --code`, ~41 bits) derive a temporary iroh key the inviting machine listens on, for+one-time codes (`reason-network invite --code`, ~41 bits) derive a temporary iroh key the inviting machine listens on, forreading out loud or adding your own machines.**Presence and directory.** Daemons keep a connection to every online member (full mesh; fine to ~50@@ -164,9 +164,9 @@ The hard part. Each session advertises a **delivery tier** so senders know when| Codex | push | `codex queue --thread <id>` / app-server `turn/start` (default daemon mode). Mid-turn: `PostToolUse` `additionalContext`. Stop: `decision:block`. Hooks need one-time approval in `/hooks`. || opencode | push | Plugin: `client.session.promptAsync` (V1), `POST /api/session/:id/prompt` via `service.json` (V2). || pi | push | Extension (`~/.pi/agent/extensions/reason-network.ts`): registers the MCP server per session (`deferred`, with `REASON_NETWORK_SESSION`), `sendUserMessage` (`deliverAs: "steer"` mid-run, a new turn when idle), busy/idle from `agent_start`/`agent_settled`, the session name as `doing`. |-| Reason | push | Its agent runs in Reason's cloud: the daemon lists live sessions (`reason session list --json`, when `reason = true`) and sends with `reason session send`. Replies go through the CLI: `reason network send <to> --from <its address>`. |+| Reason | push | Its agent runs in Reason's cloud: the daemon lists live sessions (`reason session list --json`, when `reason = true`) and sends with `reason session send`. Replies go through the CLI: `reason-network send <to> --from <its address>`. || Amp | push | Plugin: `thread.appendUserMessage(…, {steer:true})`. |-| Cursor | turn | `postToolUse` `additional_context`; `stop` `followup_message`. Idle: background `reason network wait`. |+| Cursor | turn | `postToolUse` `additional_context`; `stop` `followup_message`. Idle: background `reason-network wait`. || Gemini CLI | turn | `AfterTool` `additionalContext`; `AfterAgent` block. Idle: experimental background-shell inject. || Copilot CLI | turn | `postToolUse` `additionalContext`; `agentStop` block; `notification` hook. || any MCP client | pull | Tools + unread notice on every tool result + `check_inbox(wait_secs)` long-poll. |@@ -174,7 +174,7 @@ The hard part. Each session advertises a **delivery tier** so senders know whenMCP notifications are not a delivery path: no client passes them to the model (checked Oct 2026).Gotcha: Cursor, Copilot CLI and Devin load **Claude Code's** hooks from `~/.claude/settings.json`, so-`reason network hook` must detect which agent is actually calling it.+`reason-network hook` must detect which agent is actually calling it.## What the agent sees@@ -184,7 +184,7 @@ Three tools, none of which an agent has to call unless it wants to message someoagent, status and for how long, repo@branch, `doing`, tier. Marks `← you`.- `send_message(to, message, reply_to?, notify?)`: returns per-recipient state (`delivered` / `queued` /`held`) and tier, e.g. "queued: alice/web-cursor is idle and turn-only, it sees this when alice next- prompts it". (`reason network send --fyi` doesn't wake: read at the next natural pause.) `notify` also pops it up on+ prompts it". (`reason-network send --fyi` doesn't wake: read at the next natural pause.) `notify` also pops it up onthe person's screen, for an approval or decision only they can make: osascript on macOS, notify-send on Linux,a PowerShell toast on Windows, at most one per person sending a minute, none for messages over 15 minutes old;a machine without a desktop says so. With `notify`, `to` may be your own user: then only the pop-up, on each of@@ -217,7 +217,7 @@ not approve. Nothing changes how an agent works when it isn't messaging.- Only roster machines can connect (iroh handshake proves the key; hook rejects the rest).- Peer text is framed as peer input. Agents are told not to treat it as user instructions.- Per-machine inbound policy: `accept` (default within the team), `hold` (you approve with- `reason network held` / `reason network approve`), `refuse`; overridable per person. Claude Code adds its own+ `reason-network held` / `reason-network approve`), `refuse`; overridable per person. Claude Code adds its own`crossSessionInbound` setting on top.- Loop guard: rate limit per sender, and a cap on consecutive agent↔agent messages in a thread withoutany human input.@@ -289,16 +289,16 @@ edits): Claude Code plugin or `claude mcp add --scope user` + hooks, `~/.codex/c| `tray` | `true` | macOS: show the menu bar icon while the background service runs || `lan` | `true` | find teammates on the local network (mDNS) || `auto_update` | `true` | install new releases when they come out (checked every few hours) |-| `reason` | `false` | list your live Reason sessions (set by `reason network setup`) |+| `reason` | `false` | list your live Reason sessions (set by `reason-network setup`) || `inbound` | accept | see above |## Troubleshooting-- **`reason network doctor`** checks the daemon, the team connection (direct or relayed, per machine) and every agent.+- **`reason-network doctor`** checks the daemon, the team connection (direct or relayed, per machine) and every agent.- **An agent doesn't have the Reason Network tools:** restart that session; agents load MCP servers at startup.-- **A teammate shows as offline:** their machine is asleep or Reason Network isn't running there (`reason network doctor` on+- **A teammate shows as offline:** their machine is asleep or Reason Network isn't running there (`reason-network doctor` ontheir side). Messages wait in your outbox and go out when they're back. If it was off while the team changed- relays, run `reason network relay` there with the team's relay (`reason network team` shows it).+ relays, run `reason-network relay` there with the team's relay (`reason-network team` shows it).- **macOS asks to let Reason Network find devices on your local network:** allow it for direct LAN connections. If youdon't, Reason Network still works over the internet.- **Windows asks to let Reason Network through the firewall:** allow it for direct and LAN connections. If you don't,diff --git a/README.md b/README.mdindex a60823b..e5fe506 100644--- a/README.md+++ b/README.md@@ -27,7 +27,8 @@ First it asks: sign in with Reason, or not.That's it. Ask any agent "who's on the team?", or tell it to ask someone's agent something.**Coming from tincan?** Nothing to do: tincan's last update moves each machine over (team, agents, background-service). The command is now `reason-network` (`tincan` keeps working), and Codex asks once to trust the new hooks.+service). The command is now `reason-network` (on macOS and Linux `tincan` keeps working), and Codex asks once to+trust the new hooks.## What you get@@ -93,6 +94,7 @@ service. `reason-network who` shows the team. Agents without its tools, like clo```shreason-network leave && reason-network setup --remove && rm -rf ~/.reason/network ~/.local/bin/reason-network+rm -f ~/.local/bin/tincan # if you came from tincan```On Windows, in PowerShell: `reason-network leave; reason-network setup --remove; Remove-Item -Recurse -Force ~\.reason\network, ~\.local\bin\reason-network*`diff --git a/src/client.rs b/src/client.rsindex 0406387..d0d4e69 100644--- a/src/client.rs+++ b/src/client.rs@@ -1,4 +1,4 @@-//! Connection to the local daemon, starting it if needed. Long-lived clients (`reason network mcp`) reconnect on their+//! Connection to the local daemon, starting it if needed. Long-lived clients (`reason-network mcp`) reconnect on their//! own and re-register their sessions, so a daemon restart is invisible to the agent.use crate::{ipc, paths, proto::*};@@ -144,7 +144,7 @@ async fn reconnect(link: Weak<Link>) {let Some(link) = link.upgrade() else { return };match link.connect().await {Ok(_) => return,- Err(e) => eprintln!("reason network: reconnecting to daemon: {e:#}"),+ Err(e) => eprintln!("reason-network: reconnecting to daemon: {e:#}"),}wait = (wait * 2).min(Duration::from_secs(30));}@@ -200,14 +200,14 @@ async fn connect_or_start(start: bool) -> Result<ipc::Stream> {}}}- // Reaped when it exits, so a long-lived client (`reason network mcp`) never collects zombies.+ // Reaped when it exits, so a long-lived client (`reason-network mcp`) never collects zombies.if let Some(mut c) = child {std::thread::spawn(move || c.wait());}connected.ok_or_else(failed)}-/// Starts `reason network daemon` (`--service` with `service`) detached from this process group, logging to+/// Starts `reason-network daemon` (`--service` with `service`) detached from this process group, logging to/// `~/.reason/network/daemon.log`.pub fn start_daemon(service: bool) -> Result<std::process::Child> {paths::ensure_home()?;diff --git a/src/config.rs b/src/config.rsindex 174f3de..8cb0194 100644--- a/src/config.rs+++ b/src/config.rs@@ -24,7 +24,7 @@ pub struct Config {}/// What happens to messages from teammates' agents: `accept` delivers them, `hold` waits for you to approve-/// (`reason network held`), `refuse` bounces them.+/// (`reason-network held`), `refuse` bounces them.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default)]pub struct Inbound {@@ -65,7 +65,7 @@ impl Default for Inbound {impl Config {pub fn load() -> Self {Self::load_strict().unwrap_or_else(|e| {- eprintln!("reason network: ignoring {} (fix or delete it): {e}", paths::config().display());+ eprintln!("reason-network: ignoring {} (fix or delete it): {e}", paths::config().display());Config::default()})}diff --git a/src/hook.rs b/src/hook.rsindex 87cf4bf..0f45851 100644--- a/src/hook.rs+++ b/src/hook.rs@@ -1,4 +1,4 @@-//! `reason network hook <agent> <event>`: run by an agent's hook system. Tells the daemon the session is alive (and busy+//! `reason-network hook <agent> <event>`: run by an agent's hook system. Tells the daemon the session is alive (and busy//! or idle), and prints whatever makes the agent show incoming mail. It never fails loudly: a broken Reason Network must//! not break the agent.@@ -94,7 +94,7 @@ async fn handle(// Say who it is on Reason Network once, at session start.(None, "start", Some(addr)) => {format!(- "reason network: you are {addr}. Teammates' agents can message you; list_team and send_message reach them."+ "Reason Network: you are {addr}. Teammates' agents can message you; list_team and send_message reach them.")}_ => return None,diff --git a/src/main.rs b/src/main.rsindex 3f0fa24..14b2616 100644--- a/src/main.rs+++ b/src/main.rs@@ -65,7 +65,7 @@ pub const ENGINE: Engine = Engine;impl std::fmt::Display for Engine {fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {match setup::exe() {- Ok(p) if managed() => write!(f, "{}", p.display()),+ Ok(p) if managed() => f.write_str(setup::shell_cmd(&p, "").trim_end()),_ => f.write_str(AGENT_NAME),}}diff --git a/src/mcp.rs b/src/mcp.rsindex 06b2fd3..bd12425 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -1,4 +1,4 @@-//! `reason network mcp`: the stdio MCP server an agent spawns. A thin client of the daemon.+//! `reason-network mcp`: the stdio MCP server an agent spawns. A thin client of the daemon.use crate::{agent::{self, ClaudeSocket},@@ -105,7 +105,7 @@ pub async fn run() -> Result<()> {if !agent::multiplexed(agent)&& let Err(e) = s.session(agent, None).await{- eprintln!("reason network: registering session: {e:#}");+ eprintln!("reason-network: registering session: {e:#}");}});@@ -307,8 +307,8 @@ impl ReasonNetworkMcp {Ok(Ok(())) => {let _ = self.link.call::<Value>(Request::Delivered { key, ids }).await;}- Ok(Err(e)) => eprintln!("reason network: delivering to Claude Code: {e}"),- Err(e) => eprintln!("reason network: delivering to Claude Code: {e}"),+ Ok(Err(e)) => eprintln!("reason-network: delivering to Claude Code: {e}"),+ Err(e) => eprintln!("reason-network: delivering to Claude Code: {e}"),}}}@@ -322,7 +322,8 @@ fn join_hint() -> String {if crate::managed() {return "This machine isn't on a Reason Network yet: ask your user to run `reason network`.".into();}- let exe = crate::setup::exe().map_or_else(|_| crate::AGENT_NAME.into(), |p| p.display().to_string());+ let exe = crate::setup::exe()+ .map_or_else(|_| crate::AGENT_NAME.into(), |p| crate::setup::shell_cmd(&p, "").trim_end().to_string());format!("This machine isn't in a team yet. Ask your user for the team link and the name teammates should see, then run \`{exe} join '<link>' --as <name>`; to start a team instead, `{exe} init <team> --as <name>`."diff --git a/src/migrate.rs b/src/migrate.rsindex 23045ae..98fa713 100644--- a/src/migrate.rs+++ b/src/migrate.rs@@ -44,8 +44,9 @@ pub async fn run(log: fn(&str)) {// very process; ours takes over when it's gone).let service = paths::env_var_os("NO_SERVICE").is_none();#[cfg(unix)]- let swap = service- && setup::legacy_service(&exe)+ let legacy = service && setup::legacy_service(&exe);+ #[cfg(unix)]+ let swap = legacy&& match setup::install_service_from_daemon(&exe).await {Ok(s) => {log(&format!("moved over from {LEGACY_NAME}: service: {s}"));@@ -61,12 +62,16 @@ pub async fn run(log: fn(&str)) {if service && paths::env_var_os("HOME").is_none() {setup::move_legacy_run_entry(&exe);}- // The copy becomes a link to us, so `tincan` keeps working, once no agent still runs it. (Windows removes it- // instead, once nothing runs it: the next start.)+ // The copy becomes a link to us, so `tincan` keeps working, once no agent and no service still runs it (else the+ // next start tries again). Windows removes it instead, once nothing runs it: the next start.+ #[cfg(unix)]+ let service_moved = !legacy || swap;+ #[cfg(windows)]+ let service_moved = true;let left = setup::legacy_wiring(&exe);if !left.is_empty() {log(&format!("moved over from {LEGACY_NAME}: kept it for {} until they move over", left.join(", ")));- } else if std::fs::remove_file(&old).is_ok() {+ } else if service_moved && std::fs::remove_file(&old).is_ok() {#[cfg(unix)]let _ = std::os::unix::fs::symlink(AGENT_NAME, &old);}diff --git a/src/render.rs b/src/render.rsindex fe5daa2..2c86b58 100644--- a/src/render.rs+++ b/src/render.rs@@ -305,7 +305,7 @@ pub fn unread_notice(u: &Unread) -> Option<String> {(u.count > 0).then(|| {let plural = if u.count == 1 { "" } else { "s" };format!(- "[reason network] {} unread message{plural} from {}. Call check_inbox to read.",+ "[Reason Network] {} unread message{plural} from {}. Call check_inbox to read.",u.count,u.from.join(", "))diff --git a/src/setup.rs b/src/setup.rsindex 24ac92a..c17c6a5 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -52,7 +52,7 @@ pub fn exe() -> Result<PathBuf> {/// The command line agents run through a shell: `'/path/to/reason-network' hook codex stop`. On Windows that shell is/// PowerShell (`& 'C:\Users\Alex Smith\…\reason-network.exe' hook codex stop`), and a path that needs no quotes also runs in/// cmd.exe.-fn shell_cmd(exe: &Path, args: &str) -> String {+pub fn shell_cmd(exe: &Path, args: &str) -> String {let p = exe.display().to_string();let plain = |extra: &str| p.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));let quoted = if cfg!(windows) {@@ -998,9 +998,13 @@ pub fn legacy_wiring(exe: &Path) -> Vec<&'static str> {.output().is_ok_and(|o| o.status.success() && ours(&String::from_utf8_lossy(&o.stdout), exe))}),- "opencode" => opencode_home().join(format!("plugins/{LEGACY_NAME}.ts")).exists(),- "pi" => pi_home().join(format!("extensions/{LEGACY_NAME}.ts")).exists(),- "reason" => Config::load().reason,+ "opencode" => std::fs::read_to_string(opencode_home().join(format!("plugins/{LEGACY_NAME}.ts")))+ .is_ok_and(|t| ours(&t, exe)),+ "pi" => {+ std::fs::read_to_string(pi_home().join(format!("extensions/{LEGACY_NAME}.ts"))).is_ok_and(|t| ours(&t, exe))+ }+ // Its setting moved over with the state; nothing of it names the tincan binary.+ "reason" => false,_ => (a.wired)(&old),};AGENTS.iter().filter(|a| (a.installed)() && wired(a)).map(|a| a.id).collect()diff --git a/src/util.rs b/src/util.rsindex 007013a..f6dc2f7 100644--- a/src/util.rs+++ b/src/util.rs@@ -219,13 +219,13 @@ pub fn printable(s: &str) -> String {s.chars().filter(|c| !c.is_control() || *c == '\n' || *c == '\t').collect()}-/// This program's path. After an update replaces the file, Linux reports the old one as `<path> (deleted)`; the-/// new binary is at `<path>`. (Windows, where the update moves the old one aside, reports `<path>` as it was.)/// A build run from a source tree (`target/…`): it never updates itself or moves anything over.pub fn from_source() -> bool {current_exe().is_ok_and(|p| p.components().any(|c| c.as_os_str() == "target"))}+/// This program's path. After an update replaces the file, Linux reports the old one as `<path> (deleted)`; the+/// new binary is at `<path>`. (Windows, where the update moves the old one aside, reports `<path>` as it was.)pub fn current_exe() -> std::io::Result<std::path::PathBuf> {let exe = std::env::current_exe()?;Ok(exe.to_str().and_then(|s| s.strip_suffix(" (deleted)")).map(std::path::PathBuf::from).unwrap_or(exe))diff --git a/src/wizard.rs b/src/wizard.rsindex 7fc8316..5cefee0 100644--- a/src/wizard.rs+++ b/src/wizard.rs@@ -260,6 +260,9 @@ pub async fn show_code(me: bool) -> Result<()> {let i: InviteInfo = Link::new(None).call(Request::Invite { me, hours: 24 }).await?;let [unix, windows] = install_lines(&i.code);let who = if me { "your other machine" } else { "your teammate" };+ if crate::managed() && !me {+ log::info("Teammates in your Reason workspace just run `reason network`.")?;+ }note(format!("Invite code: {}", i.code),format!(