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
Fix what the rc testing found
Lars Talian1a51873b1629
diff --git a/src/client.rs b/src/client.rsindex 3a93925..ce07572 100644--- a/src/client.rs+++ b/src/client.rs@@ -153,7 +153,18 @@ async fn reconnect(link: Weak<Link>) {/// The daemon that holds the lock, if it is alive (it may still be starting).pub fn running_daemon() -> Option<u32> {- std::fs::read_to_string(paths::lock()).ok()?.trim().parse().ok().filter(|p| crate::util::pid_alive(*p))+ holder(&paths::lock())+}++/// Who holds the lock at `path`. Asked of the lock, not the pid: a daemon that exited holds none, even when a+/// parent that never reaps (a container's `sleep` as PID 1) leaves it a zombie whose pid still "exists".+fn holder(path: &std::path::Path) -> Option<u32> {+ use std::os::unix::io::AsRawFd;+ let f = std::fs::File::open(path).ok()?;+ if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) } == 0 {+ return None;+ }+ std::fs::read_to_string(path).ok()?.trim().parse().ok()}async fn connect_or_start(start: bool) -> Result<UnixStream> {@@ -212,3 +223,21 @@ fn start_daemon() -> Result<std::process::Child> {.process_group(0).spawn()?)}++#[cfg(test)]+mod tests {+ #[test]+ fn a_daemon_runs_only_while_it_holds_the_lock() {+ let dir = std::env::temp_dir().join(format!("tincan-lock-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("daemon.lock");+ // A pid left behind by a daemon that exited (or a zombie): the lock is free.+ std::fs::write(&path, std::process::id().to_string()).unwrap();+ assert_eq!(super::holder(&path), None);+ let held = crate::util::lock(&path, false).unwrap().expect("free lock");+ assert_eq!(super::holder(&path), Some(std::process::id()));+ drop(held);+ assert_eq!(super::holder(&path), None);+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex d1a2a27..6440b45 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -383,7 +383,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 to see who is around");+ bail!("nobody matches '{to}' right now; run list_team (or `tincan who`) to see who is around");}Ok(targets)}@@ -394,7 +394,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 to see who is around (sessions without tincan can't \+ "no session called '{spec}'. Run list_team (or `tincan who`) to see who is around (sessions without tincan can't \receive)."),[one] => Ok(vec![target(one)]),diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex ede3965..5245f71 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -383,6 +383,10 @@ impl Daemon {}};self.arrived.notify_waiters();+ // The sender's session can be answered right away, before its machine's next presence names it.+ if let (Some(net), Some((_, from))) = (self.net(), msg.from.split_once('/')) {+ net.note_session(&peer, from);+ }Ok(res)}diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 92ac8b4..282cbf9 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -189,6 +189,13 @@ impl Daemon {self.net.read().unwrap().clone()}+ /// A session here came or went: teammates hear about it right away.+ fn presence_changed(&self) {+ if let Some(net) = self.net() {+ net.presence_changed();+ }+ }+async fn serve(self: Arc<Self>, stream: UnixStream) {let (rd, mut wr) = stream.into_split();let (tx, mut rx) = mpsc::unbounded_channel::<String>();diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex 8953747..216f5ec 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -77,6 +77,7 @@ impl Daemon {stop_gen: 0,},);+ self.presence_changed();}let l = &g.live[&key];g.store.upsert_session(&remembered(l, now))?;@@ -154,6 +155,7 @@ impl Daemon {{let _ = g.store.touch_session(&l.name, now);log(&format!("session {} ({key}) ended", self.addr(&l.name)));+ self.presence_changed();}return Ok(HookReply::default());}@@ -243,6 +245,7 @@ impl Daemon {if let Some(l) = g.live.remove(&key) {let _ = g.store.touch_session(&l.name, now);log(&format!("session {} ({key}) left", self.addr(&l.name)));+ self.presence_changed();}}}diff --git a/src/main.rs b/src/main.rsindex c99cab0..ef8df88 100644--- a/src/main.rs+++ b/src/main.rs@@ -259,6 +259,9 @@ fn default_person(p: Option<String>) -> String {}async fn cli(cmd: Cmd) -> Result<()> {+ // Like other command-line tools, stop quietly when whatever reads our output goes away. (`listen` marks+ // messages read only after printing them, so nothing is lost.)+ unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };let link = Link::new(None);match cmd {Cmd::Who { filter, all, json } => {@@ -271,20 +274,30 @@ async fn cli(cmd: Cmd) -> Result<()> {}Cmd::Send { to, message, reply_to, fyi, from } => {let mut body = message.join(" ");- if body.is_empty() || body == "-" {+ if message.is_empty() || body == "-" {body.clear();std::io::stdin().read_to_string(&mut body)?;}- // Messages come from agent sessions: this agent's, `--from`'s, or from a plain terminal, `<you>/terminal`.- let from = match from.or_else(current_session) {- Some(f) => f,+ if body.trim().is_empty() {+ bail!("empty message");+ }+ // Messages come from agent sessions: `--from`'s, this agent's, or from a plain terminal, `<you>/terminal`.+ // An agent shell tincan doesn't know (its tools aren't loaded) counts as a terminal.+ let send = |from: String| Request::Send { from, to: to.clone(), body: body.clone(), reply_to: reply_to.clone(), wake: !fyi };+ let explicit = from.is_some();+ let r: SendResult = match from.or_else(current_session) {+ Some(f) => match link.call(send(f)).await {+ Err(e) if !explicit && e.to_string().contains("isn't registered") => {+ cli_session(&link, "terminal", "stop").await?;+ link.call(send("cli:terminal".into())).await?+ }+ r => r?,+ },None => {cli_session(&link, "terminal", "stop").await?;- "cli:terminal".to_string()+ link.call(send("cli:terminal".into())).await?}};- let req = Request::Send { from, to, body, reply_to, wake: !fyi };- let r: SendResult = link.call(req).await?;print!("{}", render::send_result(&r));}Cmd::Status { doing, name } => {@@ -450,7 +463,7 @@ fn daemon_pid() -> Option<u32> {async fn wait_exit(pid: Option<u32>) {let Some(pid) = pid else { return };for _ in 0..50 {- if !util::pid_alive(pid) {+ if daemon_pid() != Some(pid) {return;}tokio::time::sleep(Duration::from_millis(100)).await;diff --git a/src/net.rs b/src/net.rsindex e673d29..eb3df38 100644--- a/src/net.rs+++ b/src/net.rs@@ -100,6 +100,8 @@ pub struct Net {acks: Mutex<HashMap<String, oneshot::Sender<(String, String)>>>,dialing: Mutex<HashSet<EndpointId>>,wake: Notify,+ /// A local session came or went: announce it now, not at the next tick.+ changed: Notify,next_link: AtomicU64,}@@ -271,6 +273,7 @@ impl Net {acks: Default::default(),dialing: Default::default(),wake: Notify::new(),+ changed: Notify::new(),next_link: AtomicU64::new(1),});tokio::spawn(net.clone().dial_loop());@@ -434,12 +437,34 @@ impl Net {/// Every 2s: tell teammates if anything here changed (and at least every minute). Every 30s: resend what/// the outbox still holds for connected machines (lost in a reconnect, or deferred by a busy receiver).+ /// A local session came or went: teammates hear about it right away.+ pub fn presence_changed(&self) {+ self.changed.notify_one();+ }++ /// `peer` just sent from its session `name`: make it addressable at once, before its next presence.+ pub fn note_session(&self, peer: &EndpointId, name: &str) {+ let mut remote = self.remote.lock().unwrap();+ let rem = remote.entry(*peer).or_insert_with(|| Remote {+ presence: Presence { sessions: Vec::new(), known: Vec::new() },+ last_seen: util::now_ms(),+ online: true,+ });+ let p = &mut rem.presence;+ if !p.sessions.iter().any(|s| s.name == name) && !p.known.iter().any(|k| k == name) {+ p.known.push(name.to_string());+ }+ }+async fn presence_loop(self: Arc<Self>) {let mut last: Option<Presence> = None;let mut sent = Instant::now();let mut flushed = Instant::now();loop {- tokio::time::sleep(Duration::from_secs(2)).await;+ tokio::select! {+ _ = tokio::time::sleep(Duration::from_secs(2)) => {}+ _ = self.changed.notified() => {}+ }let Some(daemon) = self.daemon.upgrade() else { return };let p = daemon.presence().await;if last.as_ref() != Some(&p) || sent.elapsed() > Duration::from_secs(60) {diff --git a/src/render.rs b/src/render.rsindex b908f94..d467942 100644--- a/src/render.rs+++ b/src/render.rs@@ -212,7 +212,11 @@ pub fn for_agent(msgs: &[Message], agent: Option<&str>, cli: bool) -> String {let Some(last) = msgs.last() else { return out };// Every message comes from an agent session (`person/session`).let person = last.from.split_once('/').map_or(last.from.as_str(), |(p, _)| p);- let who = format!("From {person}'s agent.");+ let who = if last.from.ends_with("/terminal") {+ format!("From {person}, typed in a terminal.")+ } else {+ format!("From {person}'s agent.")+ };// No tincan tools (Reason's agent; a Claude session from before tincan), but commands run on this computer.let reply = if cli || agent == Some("reason") {format!("Reply if useful: tincan send {} --from {} \"<reply>\"", last.from, last.to)diff --git a/src/setup.rs b/src/setup.rsindex 971b9af..d6c58e2 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -552,18 +552,30 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {}return Ok("removed the login service".into());}+ // Containers and WSL often have no user systemd: say so plainly, and leave no unit behind.+ let user_systemd = Command::new("systemctl")+ .args(["--user", "show-environment"])+ .stdin(std::process::Stdio::null())+ .output()+ .is_ok_and(|o| o.status.success());+ if !user_systemd {+ return Err(anyhow!("systemctl --user isn't available here"));+ }let home_env = tincan_home.map(|h| format!("Environment=\"TINCAN_HOME={h}\"\n")).unwrap_or_default();let unit = format!(- "[Unit]\nDescription=tincan daemon\n\n[Service]\nExecStart={} daemon --service\nRestart=always\nRestartSec=3\nEnvironment=\"PATH={}\"\n{home_env}\n[Install]\nWantedBy=default.target\n",+ "[Unit]\nDescription=tincan daemon\n\n[Service]\nExecStart={} daemon --service\nRestart=always\nRestartSec=3\nEnvironment=\"PATH={}\"\n{home_env}StandardError=append:{}\n\n[Install]\nWantedBy=default.target\n",shell_cmd(exe, "").trim_end(),- service_path_env()+ service_path_env(),+ paths::log().display());let did = write_file(&path, &unit, dry)?;if !dry {+ paths::ensure_home()?;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())]).stdin(std::process::Stdio::null()).output()?;if !out.status.success() {+ let _ = std::fs::remove_file(&path);return Err(anyhow!("systemctl: {}", String::from_utf8_lossy(&out.stderr).trim()));}// Keep running after logout (servers, SSH boxes). Best effort: some systems want a password.@@ -728,8 +740,7 @@ pub async fn apply(exe: &Path, install: &[&str], remove: &[&str], service: Optioout.service = Some(on);}Err(e) => {- out.lines.push(format!("service: not installed ({e:#}); the daemon still starts on demand"));- out.notes.push(format!("Not running in the background ({e:#}); tincan starts when you use it."));+ out.notes.push(format!("Not running in the background: {e:#}; tincan starts when you use it."));}}}diff --git a/src/util.rs b/src/util.rsindex aebdb90..9b6d968 100644--- a/src/util.rs+++ b/src/util.rs@@ -70,8 +70,14 @@ pub fn lock(path: &Path, wait: bool) -> std::io::Result<Option<File>> {use std::io::Write;let mut f = File::options().create(true).truncate(false).write(true).open(path)?;let flags = if wait { libc::LOCK_EX } else { libc::LOCK_EX | libc::LOCK_NB };- if unsafe { libc::flock(f.as_raw_fd(), flags) } != 0 {- return Ok(None);+ // A client checking whether a daemon runs holds the lock for an instant: try again before giving up.+ let mut tries = 0;+ while unsafe { libc::flock(f.as_raw_fd(), flags) } != 0 {+ tries += 1;+ if tries == 3 {+ return Ok(None);+ }+ std::thread::sleep(std::time::Duration::from_millis(20));}f.set_len(0)?;write!(f, "{}", std::process::id())?;diff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.pyindex 9d11c65..39bf2d0 100644--- a/tests/e2e/hooks.py+++ b/tests/e2e/hooks.py@@ -138,6 +138,12 @@ out = run("listen", "--as", "terminal", "--wait", "3")check("the terminal reads the reply with `tincan listen --as terminal`", "both green" in out and 'from="alex/bot"' in out, out)out = run("listen", "--as", "terminal", "--wait", "0")check("…once", "No messages." in out, out)+out = run("send", "alex/bot", "")+check("an empty message is an error", "empty message" in out, out)+r = subprocess.run([BIN, "send", "alex/bot", "from a shell tincan doesn't know"], env=dict(env, CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="not-on-tincan"),+ capture_output=True, text=True, timeout=30)+out = run("listen", "--as", "bot", "--wait", "3")+check("an agent shell tincan doesn't know sends as <me>/terminal", 'from="alex/terminal"' in out and "a shell tincan doesn't know" in out, r.stdout + r.stderr + out)# Reason: its agent runs in the cloud; tincan lists the live sessions and sends with its CLI.fake_reason, reason_log = os.path.join(D, "fake-reason.sh"), os.path.join(D, "reason.log")diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex b791390..c314b10 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -146,12 +146,19 @@ check("…and is gone once read", out.startswith("No messages."), out)out = cli("alice", "send", "alex", "dinner at 8?")check("a person is not an address: the error lists their agent sessions","messages go to agent sessions; alex's are:" in out and f"alex/{claude_name}" in out, out)-time.sleep(3) # alex's new terminal session reaches alice with his next presence update+# No waiting for presence: the terminal that just messaged alice can be answered at once.out = codex.tool("send_message", {"to": "alex/terminal", "message": "codex here: replying to your terminal"}, meta)-check("an agent can reply to a terminal across machines", "→ alex/terminal: queued" in out or "→ alex/terminal: delivered" in out, out)+check("an agent can reply at once to a terminal that just messaged it", "→ alex/terminal: queued" in out or "→ alex/terminal: delivered" in out, out)time.sleep(1)out = cli("alex", "listen", "--as", "terminal", "--wait", "5")check("…and `tincan listen --as terminal` shows the reply", "replying to your terminal" in out and 'from="alice/work-codex"' in out, out)+cli("alice", "listen", "--as", "fresh", "--wait", "0")+cli("alice", "send", "alex/terminal", "--from", "alice/fresh", "first words from a new session")+out = cli("alex", "send", "alice/fresh", "answered at once")+check("a brand-new session that just messaged can be answered at once", "→ alice/fresh" in out and "no session" not in out, out)+out = cli("alice", "listen", "--as", "fresh", "--wait", "5")+check("…and it gets the answer", "answered at once" in out, out)+cli("alex", "listen", "--as", "terminal", "--wait", "0")out = cli("alex", "send", "*", "broadcast from alex (e2e test, ignore)")check("broadcast reaches alice's session", "alice/work-codex" in out, out)codex.tool("check_inbox", {}, meta)