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
Reason Network on its own: no account needed, and tincan machines move over
Lars Talian96034595d899
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e479562..06ac266 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,7 +1,7 @@name: release-# Push a tag like v0.10.0 to build reason-network for macOS and Linux (the targets the reason CLI installs) and-# publish a GitHub release. The reason CLI pins each archive's sha256.+# Push a tag like v0.11.0 to build reason-network for macOS, Linux and Windows and publish a GitHub release, with the+# install scripts a standalone install (and its updates) uses. The reason CLI pins the macOS and Linux archives' sha256.on:push:tags: ["v*"]@@ -20,6 +20,8 @@ jobs:- { target: x86_64-apple-darwin, os: macos-14 }- { target: x86_64-unknown-linux-musl, os: ubuntu-24.04 }- { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm }+ - { target: x86_64-pc-windows-msvc, os: windows-latest }+ - { target: aarch64-pc-windows-msvc, os: windows-11-arm }runs-on: ${{ matrix.os }}env:# Windows builds carry their C runtime, so they run without the Visual C++ redistributable.@@ -60,6 +62,7 @@ jobs:with:path: distmerge-multiple: true+ - run: cp install.sh install.ps1 dist/- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2with:files: dist/*diff --git a/README.md b/README.mdindex 27db32d..13d754e 100644--- a/README.md+++ b/README.md@@ -8,15 +8,28 @@ Every coding agent session on every teammate's computer shows up (who, which repdoing right now), and any of them can message the right one: Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI,opencode, pi and Reason.-This repository is the engine behind `reason network`. You don't install it by hand: the-[Reason CLI](https://reasonmachines.com) downloads a pinned, checksum-verified build and sets it up the first time you-run:+## Get started++No account needed. One person runs this and picks a team name:```sh-reason network+curl -fsSL https://github.com/reason-machines/reason-network/releases/latest/download/install.sh | sh+```++On Windows, in PowerShell:++```powershell+irm https://github.com/reason-machines/reason-network/releases/latest/download/install.ps1 | iex```-Everyone in your Reason workspace is on the same network.+You get a team link (it's on your clipboard). Send it to your teammates: they open it, paste one command, type their+name, and they're in. Or they tell their agent "join my Reason Network team: <link>".++**On Reason?** `reason network` does all of this with your Reason login: your workspace is the team, nobody passes+links around, and your agents also reach Reason's cloud agents. The [Reason CLI](https://reasonmachines.com) installs+and updates this engine for you.++**Coming from tincan?** Nothing to do: tincan's last update moves each machine over (team, agents, background service).## What you get@@ -31,14 +44,18 @@ Everyone in your Reason workspace is on the same network.- **A menu bar icon** on macOS shows who's online and what they're doing.```sh-reason network who # who's around and what their sessions are doing-reason network alice/api-claude "did the token format change?" # ask one of alice's agents, wait for the answer-reason network send alice/api-claude "heads up: main is red" # send without waiting-reason network send alice/api-claude --notify "approve the deploy?" # and pop it up on alice's screen-reason network send '*' "deploying api at 5" # everyone (or alice/*, repo:api): from you, never an agent-reason network setup # wire this computer's agents in again+reason-network who # who's around and what their sessions are doing+reason-network send alice/api-claude "did the token format change?" # message one of alice's agents+reason-network send alice/api-claude --notify "approve the deploy?" # and pop it up on alice's screen+reason-network send '*' "deploying api at 5" # everyone (or alice/*, repo:api): from you, never an agent+reason-network listen --as terminal # replies to what you sent from this terminal+reason-network link # the team link again+reason-network setup # which agents are on it, and how messages are handled```+With the Reason CLI, `reason network` runs the same commands (and `reason network alice/api-claude "…"` asks and waits+for the answer).+## How it worksEach computer runs a small daemon. Teammates' computers connect directly (on the same Wi-Fi, or across the internet@@ -55,7 +72,8 @@ cargo build && python3 tests/e2e/two_machines.py # two machines over iroh (neepython3 tests/e2e/hooks.py && python3 tests/e2e/guided.py```-A `v*` tag builds the macOS and Linux archives the Reason CLI installs.+A `v*` tag builds the macOS, Linux and Windows archives and the install scripts; the Reason CLI pins the macOS and+Linux ones.## Licensediff --git a/install.ps1 b/install.ps1new file mode 100644index 0000000..88433a3--- /dev/null+++ b/install.ps1@@ -0,0 +1,73 @@+# Installs Reason Network on its own (no account needed) for Windows. In PowerShell:+#+# irm <this url> | iex install, then set up (start or join a team)+# & ([scriptblock]::Create((irm <this url>))) <team link> install, then join that team+# & ([scriptblock]::Create((irm <this url>))) <team link> --as <name> the same, without questions (for agents)+# & ([scriptblock]::Create((irm <this url>))) init <team> --as <name> install and start a team, without questions+#+# From cmd or another shell, wrap it: powershell -c "<the line>".+# Environment: REASON_NETWORK_BIN_DIR (default ~\.local\bin), REASON_NETWORK_VERSION (default latest), REASON_NETWORK_REPO,+# REASON_NETWORK_DOWNLOAD_BASE (a mirror serving the release files), REASON_NETWORK_NO_PROMPT (never ask anything: updates).+& {+ $ErrorActionPreference = 'Stop'+ $ProgressPreference = 'SilentlyContinue'+ function die($msg) { throw "reason-network install: $msg" }++ $repo = if ($env:REASON_NETWORK_REPO) { $env:REASON_NETWORK_REPO } else { 'reason-machines/reason-network' }+ $bin = if ($env:REASON_NETWORK_BIN_DIR) { $env:REASON_NETWORK_BIN_DIR } else { Join-Path $HOME '.local\bin' }+ $version = if ($env:REASON_NETWORK_VERSION) { $env:REASON_NETWORK_VERSION } else { 'latest' }++ $cpu = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }+ $arch = switch ($cpu) { 'AMD64' { 'x86_64' } 'ARM64' { 'aarch64' } default { die "unsupported CPU: $cpu" } }+ $target = "$arch-pc-windows-msvc"++ if ($env:REASON_NETWORK_DOWNLOAD_BASE) { $base = $env:REASON_NETWORK_DOWNLOAD_BASE }+ elseif ($version -eq 'latest') { $base = "https://github.com/$repo/releases/latest/download" }+ else { $base = "https://github.com/$repo/releases/download/$version" }++ $tmp = Join-Path ([IO.Path]::GetTempPath()) "reason-network-$([guid]::NewGuid().ToString('n'))"+ New-Item -ItemType Directory $tmp | Out-Null+ try {+ Write-Host "Downloading reason-network for $target..."+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ $zip = Join-Path $tmp 'reason-network.zip'+ try { Invoke-WebRequest -UseBasicParsing "$base/reason-network-$target.zip" -OutFile $zip } catch { die "download failed ($base/reason-network-$target.zip)" }+ try { Invoke-WebRequest -UseBasicParsing "$base/reason-network-$target.zip.sha256" -OutFile "$zip.sha256" } catch { die 'checksum download failed; not installing' }+ $want = ([IO.File]::ReadAllText("$zip.sha256") -split '\s+')[0].ToLower()+ $file = [IO.File]::OpenRead($zip)+ try { $got = -join ([Security.Cryptography.SHA256]::Create().ComputeHash($file) | ForEach-Object { $_.ToString('x2') }) } finally { $file.Dispose() }+ if (-not $want -or $want -ne $got) { die 'checksum mismatch; not installing' }+ Add-Type -AssemblyName System.IO.Compression.FileSystem+ [IO.Compression.ZipFile]::ExtractToDirectory($zip, $tmp)++ New-Item -ItemType Directory -Force $bin | Out-Null+ $exe = Join-Path $bin 'reason-network.exe'+ # Windows can't replace a program that is running, but it can rename it: move the old one aside, and delete+ # the ones set aside before once nothing runs them.+ Get-ChildItem $bin -Filter 'reason-network.*.old' | Remove-Item -Force -ErrorAction SilentlyContinue+ $old = $null+ if (Test-Path $exe) { $old = Join-Path $bin "reason-network.$(Get-Random).old"; Move-Item $exe $old }+ try { Move-Item (Join-Path $tmp 'reason-network.exe') $exe } catch { if ($old) { Move-Item $old $exe }; throw }+ } finally {+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue+ }+ Write-Host "Installed $exe ($(& $exe --version))"++ $path = [Environment]::GetEnvironmentVariable('Path', 'User')+ if (($path -split ';') -notcontains $bin) {+ [Environment]::SetEnvironmentVariable('Path', (@($path -split ';' | Where-Object { $_ }) + $bin) -join ';', 'User')+ $env:Path = "$env:Path;$bin"+ Write-Host "Added $bin to your PATH (open a new terminal to use it there)."+ }++ # Hand over to reason-network: it asks a few questions (name, invite code, which agents) when there's someone to ask.+ if ($args.Count -eq 0) {+ if ($env:REASON_NETWORK_NO_PROMPT -or [Console]::IsInputRedirected) { Write-Host ''; Write-Host 'Next, in a terminal: reason-network'; return }+ & $exe+ } elseif ($args[0] -match '^(-.*|init|join|setup)$') {+ & $exe @args+ } else {+ & $exe join @args+ }+ if ($LASTEXITCODE) { throw "reason-network exited with code $LASTEXITCODE" }+} @argsdiff --git a/install.sh b/install.shnew file mode 100755index 0000000..e10788f--- /dev/null+++ b/install.sh@@ -0,0 +1,78 @@+#!/bin/sh+# Installs Reason Network on its own (no account needed) for macOS or Linux.+#+# curl -fsSL <this url> | sh install, then set up (start or join a team)+# curl -fsSL <this url> | sh -s -- <team link> install, then join that team+# curl -fsSL <this url> | sh -s -- <team link> --as <name> the same, without questions (for agents)+# curl -fsSL <this url> | sh -s -- init <team> --as <name> install and start a team, without questions+#+# Environment: REASON_NETWORK_BIN_DIR (default ~/.local/bin), REASON_NETWORK_VERSION (default latest), REASON_NETWORK_REPO,+# REASON_NETWORK_DOWNLOAD_BASE (a mirror serving the release files), REASON_NETWORK_NO_PROMPT (never ask anything: updates).+set -eu++repo="${REASON_NETWORK_REPO:-reason-machines/reason-network}"+bin_dir="${REASON_NETWORK_BIN_DIR:-$HOME/.local/bin}"+version="${REASON_NETWORK_VERSION:-latest}"++say() { printf '%s\n' "$*"; }+die() { say "reason-network install: $*" >&2; exit 1; }++case "$(uname -s)" in+ Darwin) os=apple-darwin ;;+ Linux) os=unknown-linux-musl ;;+ *) die "reason-network runs on macOS and Linux here (on Windows, use install.ps1)" ;;+esac+case "$(uname -m)" in+ arm64 | aarch64) arch=aarch64 ;;+ x86_64 | amd64) arch=x86_64 ;;+ *) die "unsupported CPU: $(uname -m)" ;;+esac+target="$arch-$os"++if [ -n "${REASON_NETWORK_DOWNLOAD_BASE:-}" ]; then+ base="$REASON_NETWORK_DOWNLOAD_BASE"+elif [ "$version" = latest ]; then+ base="https://github.com/$repo/releases/latest/download"+else+ base="https://github.com/$repo/releases/download/$version"+fi++tmp="$(mktemp -d)"+trap 'rm -rf "$tmp"' EXIT INT TERM++say "Downloading reason-network for $target..."+curl -fsSL "$base/reason-network-$target.tar.gz" -o "$tmp/reason-network.tar.gz" || die "download failed ($base/reason-network-$target.tar.gz)"+curl -fsSL "$base/reason-network-$target.tar.gz.sha256" -o "$tmp/sum" || die "checksum download failed; not installing"+want="$(cut -d' ' -f1 < "$tmp/sum")"+if command -v shasum >/dev/null 2>&1; then+ got="$(shasum -a 256 "$tmp/reason-network.tar.gz" | cut -d' ' -f1)"+else+ got="$(sha256sum "$tmp/reason-network.tar.gz" | cut -d' ' -f1)"+fi+[ -n "$want" ] && [ "$want" = "$got" ] || die "checksum mismatch; not installing"+tar -xzf "$tmp/reason-network.tar.gz" -C "$tmp"+mkdir -p "$bin_dir"+install -m 755 "$tmp/reason-network" "$bin_dir/reason-network"+say "Installed $bin_dir/reason-network ($("$bin_dir/reason-network" --version))"++case ":$PATH:" in+ *":$bin_dir:"*) ;;+ *) say "Note: $bin_dir is not on your PATH. Add this to your shell profile:"+ say " export PATH=\"$bin_dir:\$PATH\"" ;;+esac++# Hand over to reason-network: it asks a few questions (name, invite code, which agents) in your terminal. Under+# `curl | sh` our stdin is the script, so read answers from the terminal itself when there is one.+# (In a subshell: in dash, Ubuntu's sh, a failed redirection on `:` would end the whole script.)+if [ -z "${REASON_NETWORK_NO_PROMPT:-}" ] && (exec </dev/tty) 2>/dev/null; then+ case "${1:-}" in+ "") exec "$bin_dir/reason-network" </dev/tty ;;+ -*|init|join|setup) exec "$bin_dir/reason-network" "$@" </dev/tty ;;+ *) exec "$bin_dir/reason-network" join "$@" </dev/tty ;;+ esac+fi+case "${1:-}" in+ "") say ""; say "Next, in a terminal: reason-network" ;;+ -*|init|join|setup) exec "$bin_dir/reason-network" "$@" ;;+ *) exec "$bin_dir/reason-network" join "$@" ;;+esacdiff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex cba6f02..9a1871d 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -3,7 +3,7 @@use super::Daemon;use crate::{- agent,+ CLI, agent,claude::{self, ClaudeSession},doing,git::GitInfo,@@ -404,7 +404,7 @@ impl Daemon {self.pick(cands.iter().copied().filter(|c| c.name == spec).collect(), spec, &target)?};if targets.is_empty() {- bail!("nobody matches '{to}' right now; run list_team (or `reason network who`) to see who is around");+ bail!("nobody matches '{to}' right now; run list_team (or `{CLI} who`) to see who is around");}Ok(targets)}@@ -415,7 +415,7 @@ impl Daemon {let pool: Vec<&&Cand> = if live.is_empty() { found.iter().collect() } else { live };match pool.as_slice() {[] => bail!(- "no session called '{spec}'. Run list_team (or `reason network who`) to see who is around (sessions without Reason Network can't \+ "no session called '{spec}'. Run list_team (or `{CLI} who`) to see who is around (sessions without Reason Network can't \receive)."),[one] => Ok(vec![target(one)]),diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 6354862..5aab6f2 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -64,7 +64,7 @@ impl Inner {}}-const UPGRADE: &str = "update reason (then `reason network setup`): messages go between agent sessions now";+const UPGRADE: &str = "update Reason Network: messages go between agent sessions now";const LOOP_NOTE: &str = "refused: these two agents have exchanged a lot of messages in the last few minutes, which \looks like a loop. Check with your user before continuing.";@@ -270,7 +270,7 @@ impl Daemon {let hook_note = if matches!(l.reg.agent.as_str(), "opencode" | "pi") {"queued: delivered within seconds once the session is idle"} else if l.reg.agent == "cli" {- "queued: it gets it the next time it runs `reason network listen`"+ "queued: it gets it the next time it listens"} else {"queued: it sees it at its next tool call or when its turn ends"};diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 817b306..6f87d37 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -8,6 +8,7 @@ mod notify;mod reason;mod sessions;mod teamops;+mod update;use crate::{config::Config,@@ -65,6 +66,10 @@ pub async fn run(service: bool) -> Result<()> {if daemon.cfg.reason {tokio::spawn(daemon.clone().reason_loop());}+ tokio::spawn(crate::migrate::run(log));+ if update::allowed(daemon.cfg.auto_update) {+ tokio::spawn(daemon.clone().update_loop());+ }loop {let stream = listener.accept().await?;tokio::spawn(daemon.clone().serve(stream));diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rsindex b1a9731..fa08a62 100644--- a/src/daemon/teamops.rs+++ b/src/daemon/teamops.rs@@ -2,6 +2,7 @@use super::{Daemon, Inner, log};use crate::{+ CLI,config::Config,invite,net::{self, JoinRequest, Net, Remote, Wire},@@ -175,7 +176,7 @@ impl Daemon {relay: Option<String>,) -> Result<TeamInfo> {if let Some(t) = self.team_state() {- bail!("already in team '{}'; run `reason network leave` first", t.name());+ bail!("already in team '{}'; run `{CLI} leave` first", t.name());}let (name, person) = (name.trim(), util::slug(person));if name.is_empty() || person.is_empty() {@@ -212,7 +213,7 @@ impl Daemon {others.dedup();if !others.is_empty() {bail!(- "already in team '{}' (with {}). To switch, run `reason network leave`, then join again",+ "already in team '{}' (with {}). To switch, run `{CLI} leave`, then join again",t.name(),others.join(", "));@@ -284,9 +285,8 @@ impl Daemon {/// Makes an invite: a code (this machine listens for it until it is used or expires) and the equivalent/// long ticket (which any teammate's machine can redeem).pub(super) async fn invite(&self, me: bool, hours: u64) -> Result<InviteInfo> {- let net = self.net().ok_or_else(|| {- anyhow!("not connected to a team yet (run `reason network init` or `reason network join`)")- })?;+ let net =+ self.net().ok_or_else(|| anyhow!("not connected to a team yet (run `{CLI} init` or `{CLI} join`)"))?;net.online(Duration::from_secs(5)).await;let hours = hours.clamp(1, 24 * 30);let code = invite::generate();@@ -343,7 +343,7 @@ impl Daemon {}let state = {let mut g = self.inner.lock().unwrap();- let team = g.team.as_mut().ok_or_else(|| anyhow!("not in a team yet: run `reason network`"))?;+ let team = g.team.as_mut().ok_or_else(|| anyhow!("not in a team yet: run `{CLI}`"))?;if new || team.link_secret().is_none() {team.new_link(&self.key);}@@ -360,9 +360,9 @@ impl Daemon {}pub(super) fn team_info(&self) -> Result<TeamInfo> {- let team = self.team_state().ok_or_else(|| {- anyhow!("not in a team yet: `reason network init <team>` or `reason network join <invite>`")- })?;+ let team = self+ .team_state()+ .ok_or_else(|| anyhow!("not in a team yet: `{CLI} init <team>` or `{CLI} join <invite>`"))?;Ok(TeamInfo {name: team.name().into(),relay: team.meta.body.relay.clone(),@@ -433,7 +433,7 @@ impl Daemon {bail!("'{who}' matches machines of several people; say which: {}", opts.join(", "));}if hits.iter().any(|h| h.0 == me) {- bail!("that includes this machine; use `reason network leave` instead");+ bail!("that includes this machine; use `{CLI} leave` instead");}for (id, person, machine) in &hits {team.put_member(&self.key, *id, person, machine, false);@@ -451,10 +451,7 @@ impl Daemon {}}let names: Vec<String> = removed.iter().map(|(_, p, m)| format!("{p} on {m}")).collect();- Ok(format!(- "Removed {}. The team link changed too (`reason network link` shows the new one).",- names.join(", ")- ))+ Ok(format!("Removed {}. The team link changed too (`{CLI} link` shows the new one).", names.join(", ")))}pub(super) async fn leave(self: &Arc<Self>, force: bool) -> Result<String> {@@ -463,7 +460,7 @@ impl Daemon {if !anyone && !self.peer_ids().is_empty() && !force {bail!("no teammate is online to hear that this machine left. Try again when one is, or use --force (they'll \- need to `reason network remove` it then)"+ need to `{CLI} remove` it then)");}let state = {@@ -512,12 +509,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!("reason network relay {u}"))- }- None => ("The team now uses n0's public relays.".into(), "reason network relay default".into()),+ 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")),};- let mut out = format!("{now} Team links from before stop working: `reason network link` shows the new one.");+ 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.if !away.is_empty() {out += &format!(diff --git a/src/daemon/update.rs b/src/daemon/update.rsnew file mode 100644index 0000000..9c3fe01--- /dev/null+++ b/src/daemon/update.rs@@ -0,0 +1,122 @@+//! Keeps a standalone install up to date: every few hours the daemon looks for a newer release and, if there is one,+//! installs it over its own binary (with install.sh, or install.ps1 on Windows, checksum verified) and restarts on it.+//! Off with `auto_update = false`; never for builds run from a source tree, nor for the build the Reason CLI pins+//! (in `~/.reason/bin`), which updates with the CLI.++use super::{Daemon, log};+use anyhow::{Result, bail};+use std::{sync::Arc, time::Duration};++const EVERY: Duration = Duration::from_secs(6 * 3600);++impl Daemon {+ pub(super) async fn update_loop(self: Arc<Self>) {+ tokio::time::sleep(Duration::from_secs(90)).await;+ loop {+ match update().await {+ Ok(Some(v)) => {+ log(&format!("updated to {v}; restarting on it"));+ self.restart_soon();+ return;+ }+ Ok(None) => {}+ Err(e) => log(&format!("checking for updates: {e:#}")),+ }+ tokio::time::sleep(EVERY).await;+ }+ }+}++/// Whether this binary may replace itself.+pub(super) fn allowed(enabled: bool) -> bool {+ let from_source = crate::util::current_exe().is_ok_and(|p| p.components().any(|c| c.as_os_str() == "target"));+ enabled && !from_source && !crate::managed() && crate::paths::env_var_os("NO_UPDATE").is_none()+}++/// Installs the latest release if it is newer than this one; returns its version.+async fn update() -> Result<Option<String>> {+ let latest = latest_version().await?;+ if !newer(&latest, env!("CARGO_PKG_VERSION")) {+ return Ok(None);+ }+ let dir = crate::util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();+ let mut cmd = tokio::process::Command::from(crate::installer(&dir));+ cmd.stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true);+ // In its own process group, so a timeout kills the whole pipeline (curl and the inner sh too). (On Windows the+ // installer is one PowerShell, which `kill_on_drop` ends.)+ #[cfg(unix)]+ cmd.process_group(0);+ let child = cmd.spawn()?;+ #[cfg(unix)]+ let group = child.id();+ let out = match tokio::time::timeout(Duration::from_secs(300), child.wait_with_output()).await {+ Ok(out) => out?,+ Err(_) => {+ #[cfg(unix)]+ if let Some(pgid) = group {+ // SAFETY: signals the process group we just created.+ unsafe { libc::killpg(pgid as libc::pid_t, libc::SIGKILL) };+ }+ bail!("install timed out");+ }+ };+ if !out.status.success() {+ bail!("install failed: {}", String::from_utf8_lossy(&out.stderr).trim());+ }+ // Restart only on a binary that really is newer (a release tagged without bumping its version must not loop).+ let installed = dir.join(format!("{}{}", crate::AGENT_NAME, std::env::consts::EXE_SUFFIX));+ let installed = tokio::process::Command::new(installed).arg("--version").kill_on_drop(true).output();+ let installed = tokio::time::timeout(Duration::from_secs(30), installed).await??;+ let installed =+ String::from_utf8_lossy(&installed.stdout).trim().rsplit(' ').next().unwrap_or_default().to_string();+ if !newer(&installed, env!("CARGO_PKG_VERSION")) {+ bail!("the latest release installed as {installed:?}, which is not newer than this one; not restarting");+ }+ Ok(Some(installed))+}++/// The newest release's version, from where GitHub's "latest release" link redirects.+async fn latest_version() -> Result<String> {+ let repo = crate::paths::env_var("REPO").unwrap_or_else(|_| crate::REPO.into());+ let null = if cfg!(windows) { "NUL" } else { "/dev/null" };+ let out = tokio::process::Command::new("curl")+ .args([+ "-fsSLI",+ "--max-time",+ "50",+ "-o",+ null,+ "-w",+ "%{url_effective}",+ &format!("https://github.com/{repo}/releases/latest"),+ ])+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true)+ .output();+ let out = tokio::time::timeout(Duration::from_secs(60), out).await??;+ let url = String::from_utf8_lossy(&out.stdout).to_string();+ match url.rsplit_once("/tag/v") {+ Some((_, v)) if out.status.success() && !v.is_empty() => Ok(v.trim().to_string()),+ _ => bail!("no release found at {url}"),+ }+}++/// `a` is a later version than `b` (`major.minor.patch`).+fn newer(a: &str, b: &str) -> bool {+ let parse = |v: &str| -> Vec<u64> { v.split('.').map(|p| p.parse().unwrap_or(0)).collect() };+ parse(a) > parse(b)+}++#[cfg(test)]+mod tests {+ #[test]+ fn versions_compare_by_number() {+ assert!(super::newer("0.10.0", "0.9.3"));+ assert!(super::newer("1.0.0", "0.99.99"));+ assert!(!super::newer("0.6.3", "0.6.3"));+ assert!(!super::newer("0.6.2", "0.6.10"));+ }+}diff --git a/src/main.rs b/src/main.rsindex 3c86ffc..7001a61 100644--- a/src/main.rs+++ b/src/main.rs@@ -9,6 +9,7 @@ mod hook;mod invite;mod ipc;mod mcp;+mod migrate;mod net;mod paths;mod proto;@@ -35,9 +36,50 @@ pub const AGENT_NAME: &str = "reason-network";/// `paths` moves the state it kept under it.pub const LEGACY_NAME: &str = "tincan";-/// The one line that installs Reason and joins with `invite`.-pub fn install_line(invite: &str) -> String {- format!("curl -fsSL https://reasonmachines.com/install.sh | bash && reason network join {invite}")+/// Where releases are published: a standalone install and its updates come from here.+pub const REPO: &str = "reason-machines/reason-network";++/// Whether the Reason CLI installed this binary (in `~/.reason/bin`): then it sets up and updates with the CLI, and+/// people type `reason network`.+pub fn managed() -> bool {+ static MANAGED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *MANAGED.get_or_init(|| {+ util::current_exe().is_ok_and(|p| p.starts_with(paths::user_home().join(".reason").join("bin")))+ })+}++/// The command people type, for messages (`{CLI}`): `reason network` with the Reason CLI, `reason-network` on its own.+pub struct Command;+pub const CLI: Command = Command;+impl std::fmt::Display for Command {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str(if managed() { "reason network" } else { AGENT_NAME })+ }+}++/// The one line that installs Reason Network on its own (no account needed) and runs `reason-network <args>`: for+/// macOS and Linux, and for Windows.+pub fn install_lines(args: &str) -> [String; 2] {+ let base = format!("https://github.com/{REPO}/releases/latest/download");+ [+ format!("curl -fsSL {base}/install.sh | sh -s -- {args}"),+ format!("powershell -c \"& ([scriptblock]::Create((irm {base}/install.ps1))) {args}\""),+ ]+}++/// The install script, run without questions, installing into `dir`.+pub fn installer(dir: &std::path::Path) -> std::process::Command {+ let base = format!("https://github.com/{REPO}/releases/latest/download");+ let mut cmd;+ if cfg!(windows) {+ cmd = std::process::Command::new("powershell");+ cmd.args(["-NoProfile", "-NonInteractive", "-Command", &format!("irm {base}/install.ps1 | iex")]);+ } else {+ cmd = std::process::Command::new("sh");+ cmd.arg("-c").arg(format!("curl -fsSL {base}/install.sh | sh"));+ }+ cmd.env("REASON_NETWORK_BIN_DIR", dir).env("REASON_NETWORK_NO_PROMPT", "1");+ cmd}/// The team link: Reason Network's join page, carrying the `ticket`.@@ -49,8 +91,8 @@ pub fn join_url(ticket: &str) -> String {#[command(name = "reason-network",version,- about = "The engine behind `reason network`: your agents, talking to your teammates' agents",- after_help = "Run `reason network` on its own to get set up, then to see who's working on what."+ about = "Reason Network: your agents, talking to your teammates' agents",+ after_help = "Run it on its own to get set up, then to see who's working on what.")]struct Cli {#[command(subcommand)]@@ -174,7 +216,7 @@ enum Cmd {},/// Check that everything is workingDoctor,- /// Updates come with the Reason CLI (`reason update`)+ /// Update to the latest release (with the Reason CLI, `reason update` does it)Upgrade,/// Called by agents' hooks#[command(hide = true)]@@ -215,6 +257,7 @@ enum Cmd {#[tokio::main]async fn main() -> Result<()> {+ migrate::as_ours();let cmd = Cli::parse().cmd;paths::migrate();match cmd {@@ -236,7 +279,7 @@ async fn main() -> Result<()> {}if !in_team {println!(- "Not in a team yet. Run `reason network` in a terminal to get set up (or `reason network init <team>` / `reason network join <code>`)."+ "Not in a team yet. Run `{CLI}` in a terminal to get set up (or `{CLI} init <team>` / `{CLI} join <code>`).");return Ok(());}@@ -352,9 +395,7 @@ async fn cli(cmd: Cmd) -> Result<()> {let l: LinkInfo = link.call(Request::Link { new }).await?;let copied = wizard::interactive() && wizard::copy(&l.url);println!("Team link for {}{}:\n\n{}\n", l.team, if copied { " (on your clipboard)" } else { "" }, l.url);- println!(- "Anyone with it can join: it opens a page with one command. `reason network link --new` replaces it."- );+ println!("Anyone with it can join: it opens a page with one command. `{CLI} link --new` replaces it.");}Cmd::Invite { me: false, code: false, .. } => Box::pin(cli(Cmd::Link { new: false })).await?,Cmd::Setup { dry_run: false, remove: false, no_service: false } if wizard::interactive() => {@@ -362,7 +403,7 @@ async fn cli(cmd: Cmd) -> Result<()> {}Cmd::Init { team, person, no_setup, relay } => {let Some(team) = team else {- bail!("name the team: `reason network init <team>` (or run it in a terminal to be asked)")+ bail!("name the team: `{CLI} init <team>` (or run it in a terminal to be asked)")};let t: TeamInfo =link.call(Request::CreateTeam { name: team, person: default_person(person), relay }).await?;@@ -372,10 +413,10 @@ async fn cli(cmd: Cmd) -> Result<()> {println!();setup::run(false, false, false).await?;}- println!("\nNext: `reason network link` prints the team link to send your teammates.");+ println!("\nNext: `{CLI} link` prints the team link to send your teammates.");}Cmd::Join { invite, person, no_setup } => {- let Some(invite) = invite else { bail!("give the invite code: `reason network join <code>`") };+ let Some(invite) = invite else { bail!("give the invite code: `{CLI} join <code>`") };let t: TeamInfo = link.call(Request::Join { ticket: invite, person: default_person(person) }).await?;wait_exit(daemon_pid()).await;println!("Joined team {} as {} on {}.", t.name, t.person, t.machine);@@ -401,13 +442,15 @@ async fn cli(cmd: Cmd) -> Result<()> {let i: InviteInfo = link.call(Request::Invite { me, hours: hours.clamp(1, 24 * 30) }).await?;let who = if me { "another machine of yours" } else { "a teammate" };println!("Invite code for {who}: {}\n", i.code);- println!("They run this, which installs Reason and joins the team:\n");- println!(" {}\n", install_line(&i.code));+ let [unix, windows] = install_lines(&i.code);+ println!("They run this, which installs Reason Network and joins the team:\n");+ println!(" {unix}\n");+ println!("On Windows, in PowerShell:\n\n {windows}\n");println!(- "(or `reason network join {}` if they have reason). Works once, within {}h, while this machine is online.",+ "(or `{CLI} join {}` if it's installed). Works once, within {}h, while this machine is online.",i.code, i.hours);- println!("If this machine will be offline, use the long form instead: reason network join {}", i.ticket);+ println!("If this machine will be offline, use the long form instead: {CLI} join {}", i.ticket);if me {println!("\nFor a cloud agent of yours (Grok Bot, Dots, Muse, …), send it: join my Reason Network team as {}: {}",@@ -456,7 +499,7 @@ async fn cli(cmd: Cmd) -> Result<()> {println!("Nothing held.");} else {print!("{}", render::for_human(&msgs));- println!("`reason network approve <id>` delivers, `reason network reject <id>` drops (or --all).");+ println!("`{CLI} approve <id>` delivers, `{CLI} reject <id>` drops (or --all).");}}Cmd::Approve { ids, all } | Cmd::Reject { ids, all } if ids.is_empty() && !all => {@@ -473,7 +516,15 @@ async fn cli(cmd: Cmd) -> Result<()> {Cmd::Setup { dry_run, remove, no_service } => setup::run(dry_run, remove, no_service).await?,Cmd::Doctor => setup::doctor().await?,Cmd::Upgrade => {- bail!("the network engine updates with the reason CLI: update reason, then run `reason network setup`");+ if managed() {+ bail!("the network engine updates with the reason CLI: update reason, then run `{CLI} setup`");+ }+ let dir = util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();+ if !installer(&dir).status()?.success() {+ bail!("upgrade failed");+ }+ stop_daemon().await;+ println!("The daemon restarted on the new version. Restart agent sessions to update their tools.");}Cmd::Stop => {if !stop_daemon().await {diff --git a/src/mcp.rs b/src/mcp.rsindex d955010..20936d9 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -317,9 +317,16 @@ fn failure(e: anyhow::Error) -> CallToolResult {CallToolResult::error(vec![ContentBlock::text(format!("{e:#}"))])}-/// Getting this machine into a team: the Reason CLI does it.+/// Getting this machine into a team: the Reason CLI does it, or a team link with this binary's own path.fn join_hint() -> String {- "This machine isn't on a Reason Network yet: ask your user to run `reason network`.".into()+ 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());+ 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>`."+ )}#[cfg(test)]diff --git a/src/migrate.rs b/src/migrate.rsnew file mode 100644index 0000000..9ccec17--- /dev/null+++ b/src/migrate.rs@@ -0,0 +1,58 @@+//! A machine that ran tincan on its own moves over once. tincan's last update installed reason-network beside it,+//! with a copy under the old name for what still starts that: the old login service, agents' configs, and the old+//! updater checking the version. `paths` has already moved the state; the daemon's first start here rewires the+//! agents and swaps the login service. Agent sessions started before keep working until they end.++use crate::{AGENT_NAME, LEGACY_NAME, setup, util};++/// Started under the old name, runs as reason-network instead, so everything after this is our own binary.+pub fn as_ours() {+ let Ok(me) = util::current_exe() else { return };+ let ours = me.with_file_name(format!("{AGENT_NAME}{}", std::env::consts::EXE_SUFFIX));+ if me.file_stem().is_none_or(|s| s != LEGACY_NAME) || !ours.exists() {+ return;+ }+ let mut cmd = std::process::Command::new(ours);+ cmd.args(std::env::args_os().skip(1));+ #[cfg(unix)]+ eprintln!("{AGENT_NAME}: {}", std::os::unix::process::CommandExt::exec(&mut cmd));+ #[cfg(windows)]+ if let Ok(status) = cmd.status() {+ std::process::exit(status.code().unwrap_or(1));+ }+}++/// Moves this machine's agents and login service over from the tincan beside us, if that hasn't happened yet.+/// Lines go to `log`.+pub async fn run(log: fn(&str)) {+ let from_source = util::current_exe().is_ok_and(|p| p.components().any(|c| c.as_os_str() == "target"));+ let Ok(exe) = setup::exe() else { return };+ let old = setup::legacy_exe(&exe);+ if from_source || crate::managed() || !old.exists() {+ return;+ }+ #[cfg(unix)]+ let service = crate::paths::env_var_os("NO_SERVICE").is_none() && setup::unregister_legacy_service(&exe);+ #[cfg(windows)]+ setup::move_legacy_run_entry(&exe);+ let out = setup::apply(&exe, &setup::legacy_wiring(&exe), &[], None, false).await;+ for line in out.lines.iter().chain(&out.notes) {+ log(&format!("moved over from {LEGACY_NAME}: {line}"));+ }+ #[cfg(unix)]+ if service {+ match setup::install_service_from_daemon(&exe).await {+ Ok(s) => log(&format!("moved over from {LEGACY_NAME}: service: {s}")),+ Err(e) => log(&format!("moved over from {LEGACY_NAME}: service not installed: {e:#}")),+ }+ }+ // The copy tincan's update left under the old name. (Windows keeps it while it still runs; the next start goes.)+ if std::fs::read(&old).is_ok_and(|b| std::fs::read(&exe).is_ok_and(|o| o == b)) {+ let _ = std::fs::remove_file(&old);+ }+ // Last: the old service may be what runs this very process. Ours takes over once it has gone.+ #[cfg(unix)]+ if service {+ setup::stop_legacy_service();+ }+}diff --git a/src/render.rs b/src/render.rsindex eb04663..ab038e8 100644--- a/src/render.rs+++ b/src/render.rs@@ -1,6 +1,6 @@//! Text shown to agents (tool results, injected messages) and in the CLI.-use crate::{proto::*, util};+use crate::{CLI, proto::*, util};use std::fmt::Write;/// Terminal colours for people reading the CLI; agents, pipes and `NO_COLOR` get plain text.@@ -242,7 +242,7 @@ pub fn for_agent(msgs: &[Message], agent: Option<&str>, cli: bool) -> String {};// No Reason Network tools (Reason's agent; a Claude session from before Reason Network), but commands run on this computer.let reply = if cli || agent == Some("reason") {- format!("Reply if useful: reason network send {} --from {} \"<reply>\"", last.from, last.to)+ format!("Reply if useful: {CLI} send {} --from {} \"<reply>\"", last.from, last.to)} else {format!("Reply if useful with send_message to \"{}\".", last.from)};diff --git a/src/setup.rs b/src/setup.rsindex 45098d3..a5f280b 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -6,7 +6,7 @@//! there under that name, so an update moves an agent over and leaves nothing behind; another program of that name//! (at another path) keeps its wiring.-use crate::{AGENT_NAME, LEGACY_NAME, agent, client::Link, config::Config, paths, proto::*, render};+use crate::{AGENT_NAME, CLI, LEGACY_NAME, agent, client::Link, config::Config, paths, proto::*, render};use anyhow::{Context, Result, anyhow};use serde_json::{Map, Value, json};use std::{@@ -187,16 +187,28 @@ fn merge_hook_groups(hooks: &mut Map<String, Value>, agent: &str, groups: Vec<(&}}-/// Takes out the server an earlier build of this binary added under the upstream engine's name.+/// The tincan binary a standalone tincan install had beside this one, before its last update put this one there.+pub fn legacy_exe(exe: &Path) -> PathBuf {+ exe.with_file_name(format!("{LEGACY_NAME}{}", std::env::consts::EXE_SUFFIX))+}++/// Whether `text` (a config, or a command line) names this binary or the tincan binary it replaced.+fn ours(text: &str, exe: &Path) -> bool {+ [exe.to_path_buf(), legacy_exe(exe)]+ .iter()+ .any(|p| text.contains(&p.display().to_string()) || text.contains(&me(p)))+}++/// Takes out the server an earlier build of this binary (or the tincan it replaced) added under the upstream name.fn drop_legacy(servers: &mut Map<String, Value>, exe: &Path) {- if servers.get(LEGACY_NAME).is_some_and(|v| v.to_string().contains(&me(exe))) {+ if servers.get(LEGACY_NAME).is_some_and(|v| ours(&v.to_string(), exe)) {servers.remove(LEGACY_NAME);}}/// Removes a file this binary wrote under the upstream engine's name (a plugin, an extension, a hook file).fn drop_legacy_file(path: &Path, exe: &Path, dry: bool, r: &mut Report) -> Result<()> {- if has(path.to_path_buf(), &me(exe)) {+ if std::fs::read_to_string(path).is_ok_and(|t| ours(&t, exe)) {if !dry {std::fs::remove_file(path)?;}@@ -229,7 +241,8 @@ fn claude(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {}Ok(())};- if let (true, true) = get(LEGACY_NAME)? {+ let legacy = Command::new(&bin).args(["mcp", "get", LEGACY_NAME]).stdin(std::process::Stdio::null()).output()?;+ if legacy.status.success() && ours(&String::from_utf8_lossy(&legacy.stdout), exe) {drop(LEGACY_NAME)?;r.lines.push(format!("removed the {LEGACY_NAME} MCP server"));}@@ -284,7 +297,7 @@ fn codex(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {.and_then(|t| t.as_table_like()).and_then(|t| t.get("command")).and_then(|c| c.as_str())- .is_some_and(|c| c == exe.display().to_string());+ .is_some_and(|c| c == exe.display().to_string() || c == legacy_exe(exe).display().to_string());if ours {servers.remove(LEGACY_NAME);}@@ -594,33 +607,57 @@ fn service_path_for(name: &str) -> PathBuf {}}-/// Stops and removes the login service this binary ran under with the upstream engine's name. True if there was one.+/// Stops and removes the login service this binary (or the tincan it replaced) ran under with the upstream engine's+/// name. True if there was one.#[cfg(unix)]fn remove_legacy_service(exe: &Path, dry: bool) -> bool {+ if dry {+ return std::fs::read_to_string(service_path_for(&legacy_service_name())).is_ok_and(|t| ours(&t, exe));+ }+ let had = unregister_legacy_service(exe);+ if had {+ stop_legacy_service();+ }+ had+}++/// Takes that service off the login items without stopping it: it may be what runs this very process. True if there+/// was one.+#[cfg(unix)]+pub fn unregister_legacy_service(exe: &Path) -> bool {let name = legacy_service_name();let path = service_path_for(&name);- if !has(path.clone(), &exe.display().to_string()) {+ if !std::fs::read_to_string(&path).is_ok_and(|t| ours(&t, exe)) {return false;}- if dry {- return true;+ let systemctl =+ |args: &[&str]| Command::new("systemctl").arg("--user").args(args).stdin(std::process::Stdio::null()).output();+ if !cfg!(target_os = "macos") {+ let _ = systemctl(&["disable", &format!("{name}.service")]);}- if cfg!(target_os = "macos") {+ let _ = std::fs::remove_file(&path);+ if !cfg!(target_os = "macos") {+ let _ = systemctl(&["daemon-reload"]);+ }+ true+}++/// Stops that service, unregistered or not.+#[cfg(unix)]+pub fn stop_legacy_service() {+ let name = legacy_service_name();+ let _ = if cfg!(target_os = "macos") {let uid = unsafe { libc::getuid() };- let _ = Command::new("launchctl")+ Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{name}")]).stdin(std::process::Stdio::null())- .output();- let _ = std::fs::remove_file(&path);+ .output()} else {- let _ = Command::new("systemctl")- .args(["--user", "disable", "--now", &format!("{name}.service")])+ Command::new("systemctl")+ .args(["--user", "stop", &format!("{name}.service")]).stdin(std::process::Stdio::null())- .output();- let _ = std::fs::remove_file(&path);- let _ = Command::new("systemctl").args(["--user", "daemon-reload"]).stdin(std::process::Stdio::null()).output();- }- true+ .output()+ };}/// A PATH for the daemon that includes where agents usually live (it runs `codex queue`).@@ -634,6 +671,18 @@ fn service_path_env() -> String {#[cfg(unix)]async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {+ install_service(exe, remove, dry, true).await+}++/// Installs ours from the daemon the legacy service runs, without stopping that daemon (itself) first: it ends when+/// the legacy service is stopped, and ours takes over.+#[cfg(unix)]+pub async fn install_service_from_daemon(exe: &Path) -> Result<String> {+ install_service(exe, false, false, false).await+}++#[cfg(unix)]+async fn install_service(exe: &Path, remove: bool, dry: bool, stop: bool) -> Result<String> {let path = service_path();let uid = unsafe { libc::getuid() };let engine_home = crate::paths::env_var("HOME").ok();@@ -682,7 +731,9 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {.is_ok_and(|o| o.status.success());if !dry && (did || !loaded) {let _ = Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();- crate::stop_daemon().await;+ if stop {+ crate::stop_daemon().await;+ }let out = Command::new("launchctl").args(["bootstrap", &format!("gui/{uid}")]).arg(&path)@@ -727,7 +778,9 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {let did = write_file(&path, &unit, dry)? || legacy;if !dry {paths::ensure_home()?;- crate::stop_daemon().await;+ if stop {+ crate::stop_daemon().await;+ }Command::new("systemctl").args(["--user", "daemon-reload"]).stdin(std::process::Stdio::null()).output()?;let out = Command::new("systemctl").args(["--user", "enable", "--now", &format!("{}.service", service_name())])@@ -780,6 +833,22 @@ fn run_entry() -> Option<String> {out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())}+/// Moves the Run entry a standalone tincan install made over to this binary. True if there was one.+#[cfg(windows)]+pub fn move_legacy_run_entry(exe: &Path) -> bool {+ let reg = |args: &[&str]| Command::new("reg").args(args).stdin(std::process::Stdio::null()).output();+ let legacy = "dev.tincan.daemon";+ let had = reg(&["query", RUN_KEY, "/v", legacy])+ .is_ok_and(|o| o.status.success() && ours(&String::from_utf8_lossy(&o.stdout), exe));+ if had {+ let command = format!("\"{}\" daemon --service", exe.display());+ if reg(&["add", RUN_KEY, "/v", &service_name(), "/d", &command, "/f"]).is_ok_and(|o| o.status.success()) {+ let _ = reg(&["delete", RUN_KEY, "/v", legacy, "/f"]);+ }+ }+ had+}+#[cfg(windows)]async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {let reg = |args: &[&str]| Command::new("reg").args(args).stdin(std::process::Stdio::null()).output();@@ -912,6 +981,25 @@ const AGENTS: [Agent; 8] = [},];+/// The agents wired to the tincan binary beside `exe`, which move over to it.+pub fn legacy_wiring(exe: &Path) -> Vec<&'static str> {+ let old = legacy_exe(exe);+ let wired = |a: &Agent| match a.id {+ "claude" => agent::find_bin("claude").is_some_and(|b| {+ Command::new(b)+ .args(["mcp", "get", LEGACY_NAME])+ .stdin(std::process::Stdio::null())+ .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,+ _ => (a.wired)(&old),+ };+ AGENTS.iter().filter(|a| (a.installed)() && wired(a)).map(|a| a.id).collect()+}+/// An agent found on this machine.pub struct Found {pub id: &'static str,@@ -1031,18 +1119,18 @@ pub async fn doctor() -> Result<()> {}if others > 0 && online == 0 {println!(- " ! no teammate connected: check your internet, or that their machines are on (`reason network doctor` there)"+ " ! no teammate connected: check your internet, or that their machines are on (`{CLI} doctor` there)");// Nothing tells a machine that was off when the team changed relays where the team went.println!(- " ! if the team changed relays while this machine was off, set the same one here: `reason network relay <url>`"+ " ! if the team changed relays while this machine was off, set the same one here: `{CLI} relay <url>`");- println!(" (or `default` for n0's); `reason network team` on a teammate's machine shows which");+ println!(" (or `default` for n0's); `{CLI} team` on a teammate's machine shows which");}}Err(e) if e.to_string().contains("not in a team") => {println!("✓ daemon running");- println!("- not in a team yet: run `reason network`");+ println!("- not in a team yet: run `{CLI}`");}Err(e) => println!("✗ daemon: {e:#}"),}@@ -1050,13 +1138,13 @@ pub async fn doctor() -> Result<()> {println!("{} login service: {}",if svc { "✓" } else { "-" },- if svc { "installed" } else { "not installed (`reason network setup`)" }+ if svc { "installed".into() } else { format!("not installed (`{CLI} setup`)") });for f in detect(&exe) {if f.wired {println!("✓ {}: wired up", f.name);} else {- println!("- {}: installed, not on Reason Network (`reason network setup`)", f.name);+ println!("- {}: installed, not on Reason Network (`{CLI} setup`)", f.name);}}Ok(())diff --git a/src/skill.md b/src/skill.mdindex 629c769..7601374 100644--- a/src/skill.md+++ b/src/skill.md@@ -7,15 +7,31 @@ description: Talk with your team's coding agents over Reason Network. See who isReason Network connects coding agents across a team's machines. Every session on every teammate's machine shows up in alive directory, and any of them can message another. Agents use its tools (list_team, send_message, check_inbox);-in a terminal it is the `reason network` command.+without them, you use the `reason-network` command (`reason network` where the Reason CLI is installed).++## Not installed yet?++If your user gave you a team link (`https://…/network/join/#tincan1…`), ask what name teammates should see, then+run, with the whole link exactly as given:++```sh+curl -fsSL https://github.com/reason-machines/reason-network/releases/latest/download/install.sh | sh -s -- '<the whole link>' --as <name>+```++On Windows:++```sh+powershell -c "& ([scriptblock]::Create((irm https://github.com/reason-machines/reason-network/releases/latest/download/install.ps1))) '<the whole link>' --as <name>"+```## Commands-- `reason network who`: every person, machine and session, with what each is working on.-- `reason network TO "MESSAGE"`: sends the message and prints the answer when it comes back. `TO` is `person/session`- or a session name.-- `reason network send TO "MESSAGE"`: sends without waiting. `--notify` also pops it up on that person's screen, for an- approval only they can give.+- `reason-network who`: every person, machine and session, with what each is working on.+- `reason-network send <to> "<message>"`: `<to>` is one agent session, `person/session`. Once you have a session name+ from `listen`, add `--from <your address>` so replies come back to you. `--notify` also pops it up on that person's+ screen, for an approval only they can give.+- `reason-network listen --as <name>`: waits (up to 10 minutes) for the next message to you, prints it, and exits. You+ are reachable as `<your user>/<name>`. After handling a message and replying, run it again to keep listening.## How to behavediff --git a/src/tray.rs b/src/tray.rsindex 6a47a22..e0fd18e 100644--- a/src/tray.rs+++ b/src/tray.rs@@ -11,7 +11,7 @@ pub use mac::run;#[cfg(target_os = "macos")]mod mac {- use crate::{client::Link, config::Config, proto::*, util, wizard};+ use crate::{CLI, client::Link, config::Config, proto::*, util, wizard};use anyhow::{Result, anyhow};use objc2::MainThreadMarker;use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSCellImagePosition, NSEventMask, NSImage};@@ -151,7 +151,7 @@ mod mac {Some(t) => items.push(Box::new(info(&format!("{t} · you're {}", v.me)))),None => {items.push(Box::new(info("Not in a team yet")));- items.push(Box::new(info("Run `reason network` in a terminal to set up")));+ items.push(Box::new(info(&format!("Run `{CLI}` in a terminal to set up"))));}}items.push(Box::new(sep()));diff --git a/src/wizard.rs b/src/wizard.rsindex 6654dfd..cf69c61 100644--- a/src/wizard.rs+++ b/src/wizard.rs@@ -2,9 +2,10 @@//! runs them in a terminal. Without a terminal (an agent running them), the commands use defaults and flags.use crate::{+ CLI,client::Link,config::{Config, Policy},- install_line, invite,+ install_lines, invite,proto::*,render, setup, util,};@@ -20,7 +21,7 @@ pub fn interactive() -> bool {pub async fn guided(f: impl std::future::Future<Output = Result<()>>) -> Result<()> {match f.await {Err(e) if e.downcast_ref::<std::io::Error>().is_some_and(|e| e.kind() == std::io::ErrorKind::Interrupted) => {- let _ = outro_cancel("Stopped. Run `reason network` to pick up where you left off.");+ let _ = outro_cancel(format!("Stopped. Run `{CLI}` to pick up where you left off."));Ok(())}r => r,@@ -59,7 +60,7 @@ pub async fn onboard(let link = Link::new(None);if let Ok(t) = link.call::<TeamInfo>(Request::Team).await {log::info(format!("You're in team {} as {} on {}.", t.name, t.person, t.machine))?;- outro("`reason network` shows who's around; `reason network invite` gives you the team link.")?;+ outro(format!("`{CLI}` shows who's around; `{CLI} invite` gives you the team link."))?;return Ok(());}let mut person = match person {@@ -187,9 +188,9 @@ pub async fn agents_and_preferences() -> Result<()> {let exe = setup::exe()?;let found = setup::detect(&exe);let chosen: Vec<&str> = if found.is_empty() {- log::warning(- "No coding agents found here (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason). Install one, then run `reason network setup`.",- )?;+ log::warning(format!(+ "No coding agents found here (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason). Install one, then run `{CLI} setup`."+ ))?;Vec::new()} else {let initial: Vec<&str> = found.iter().filter(|f| f.wired).map(|f| f.id).collect();@@ -207,7 +208,7 @@ pub async fn agents_and_preferences() -> Result<()> {let mut cfg = Config::load_strict().map_err(|e| anyhow!("fix {} first: {e}", crate::paths::config().display()))?;cfg.inbound.default = select("When a teammate's agent messages one of yours").item(Policy::Accept, "Deliver it", "recommended")- .item(Policy::Hold, "Hold it until I approve", "you approve with `reason network held`")+ .item(Policy::Hold, "Hold it until I approve", format!("you approve with `{CLI} held`")).initial_value(cfg.inbound.default).interact()?;cfg.share_paths = confirm("Show teammates your full working directories? (otherwise just the folder name)")@@ -247,7 +248,9 @@ pub async fn show_link(new: bool) -> Result<String> {};note(title,- "Send it to your friends: one paste and their name, and they're in.\nIt works for everyone until `reason network link --new`.",+ format!(+ "Send it to your friends: one paste and their name, and they're in.\nIt works for everyone until `{CLI} link --new`."+ ),)?;Ok(l.url)}@@ -255,14 +258,13 @@ pub async fn show_link(new: bool) -> Result<String> {/// A one-time code (for reading out loud, or for another machine of yours).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" };note(format!("Invite code: {}", i.code),format!(- "On {who}: {}\n(or `reason network join {}` if reason is there already)\nWorks once, within {}h, while this machine is online.",- install_line(&i.code),- i.code,- i.hours+ "On {who}: {unix}\n(on Windows: {windows})\n(or `{CLI} join {}` if it's there already)\nWorks once, within {}h, while this machine is online.",+ i.code, i.hours),)?;Ok(())@@ -300,11 +302,11 @@ pub async fn invite() -> Result<()> {.interact()?;if what == 0 {let url = show_link(false).await?;- outro("They'll show up in `reason network` once they've joined.")?;+ outro(format!("They'll show up in `{CLI}` once they've joined."))?;println!("\n{url}\n");} else {show_code(true).await?;- outro("It'll show up in `reason network` once it has joined.")?;+ outro(format!("It'll show up in `{CLI}` once it has joined."))?;}Ok(())}diff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.pyindex c101888..b49c5f0 100644--- a/tests/e2e/hooks.py+++ b/tests/e2e/hooks.py@@ -131,7 +131,7 @@ out = run("send", "alex/bot", "bot: summarise the open PRs")check("a terminal send reaches a waiting `reason network listen` session", "waiting for messages" in out, out)heard = bot.communicate(timeout=30)[0]check("listen prints it, from alex/terminal, with the CLI reply line",- "summarise the open PRs" in heard and 'from="alex/terminal"' in heard and "reason network send alex/terminal --from alex/bot" in heard, heard)+ "summarise the open PRs" in heard and 'from="alex/terminal"' in heard and "reason-network send alex/terminal --from alex/bot" in heard, heard)out = run("send", "alex/terminal", "--from", "alex/bot", "two PRs open, both green")check("after listen exits, the bot can still send with --from", "alex/terminal" in out and "refused" not in out, out)out = run("listen", "--as", "terminal", "--wait", "3")@@ -175,7 +175,7 @@ out = run("send", "fix-flaky-billing-reason", "reason: the billing test is flakytime.sleep(1)sent = open(reason_log).read() if os.path.exists(reason_log) else ""check("messages go in with `reason session send`", "queued into the Reason session" in out and sent.startswith("session send r-1 --message") and "flaky on main too" in sent, out + sent)-check("…telling it how to reply with the CLI", "reason network send alex/terminal --from alex/fix-flaky-billing-reason" in sent, sent)+check("…telling it how to reply with the CLI", "reason-network send alex/terminal --from alex/fix-flaky-billing-reason" in sent, sent)run("send", "alex/terminal", "--from", "alex/fix-flaky-billing-reason", "found it: a timezone bug")out = run("listen", "--as", "terminal", "--wait", "3")check("its reply comes from the Reason session", 'from="alex/fix-flaky-billing-reason"' in out and "timezone bug" in out, out)@@ -214,7 +214,7 @@ out = run("send", "old-proj-claude", "old session: can you hear me?")time.sleep(1.5)frame = "".join(got)check("…it's delivered straight into the session", "delivered into the session" in out and "can you hear me?" in frame, out + frame)-check("…with how to reply using the CLI", "reason network send alex/terminal --from alex/old-proj-claude" in frame, frame)+check("…with how to reply using the CLI", "reason-network send alex/terminal --from alex/old-proj-claude" in frame, frame)r = subprocess.run([BIN, "send", "alex/terminal", "loud and clear"], env=dict(env, CLAUDE_CODE_SESSION_ID="old-1", CLAUDECODE="1"),capture_output=True, text=True, timeout=30)out = run("listen", "--as", "terminal", "--wait", "3")diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex 4d80db8..a33d568 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -104,7 +104,7 @@ out = cli("alex", "team")check("founder sees alice connected", re.search(r"alice\s+desktop\s+(direct|relay)", out) is not None, out)out = cli("alice", "join", link.group(1), "--as", "bob", "--no-setup")check("joining a second team is refused while yours has others, and says how to switch",- "already in team 'vibes' (with alex)" in out and "reason network leave" in out, out)+ "already in team 'vibes' (with alex)" in out and "reason-network leave" in out, out)# Installed on its own and started a team by itself first: the team link still just works.sam = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "sam"), REASON_NETWORK_MACHINE="mini")r = subprocess.run([BIN, "init", "solo", "--as", "sam", "--no-setup"], env=sam, capture_output=True, text=True, timeout=90)