Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

Guided setup and four-word invite codes

Lars Talian17bdbcafdb23
diff --git a/DESIGN.md b/DESIGN.md
index b3285e0..50a83a5 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -100,10 +100,12 @@ machine can no longer connect, but it is not made cryptographically powerless: t
**Gate.** Incoming connections on the team protocol are dropped unless the peer is an active member. A machine
that was removed while away is first sent the state that says so; strangers learn nothing.
-**Invites.** `comms invite` writes an `Invite` op (only the hash of the secret) and prints a ticket:
-`comms join cm1…` = team id + a few member `EndpointAddr`s + secret + expiry. Any online member can redeem it:
-the joiner connects on `comms/join/1`, proves the secret, gets added (`AddMachine`) and receives the roster.
-Single use, 24h expiry. `comms invite --me` lets you add your own second machine under your person.
+**Invites.** `comms invite` makes a four-word code (`goal-hug-kilt-coil`, ~41 bits from the EFF short
+wordlist). The code derives both a temporary iroh key, which the inviting machine listens on, and the invite
+secret, whose hash goes into the team state. The joiner derives the same key from the code, dials it (found
+via n0's DNS or mDNS), proves the secret and gets the roster. No server; single use; 24h; the inviting machine
+must be online. A long `comms1…` ticket (team id, secret, a few members' addresses) is the fallback for when it
+won't be: any member can redeem that one.
**Presence and directory.** Daemons keep a connection to every online member (full mesh; fine to ~50
machines). On connect they exchange roster heads (anti-entropy) and full presence. On any local change a
diff --git a/README.md b/README.md
index 756fba0..f510ed3 100644
--- a/README.md
+++ b/README.md
@@ -26,26 +26,29 @@ come from CI. Expect rough edges and tell us about them.
## Get started
-The first person creates the team:
+One person starts the team:
```sh
-curl -fsSL https://raw.githubusercontent.com/asdf9384/company-comms/main/install.sh | sh
-comms init vibes --as tal
-comms invite # prints an invite, one per teammate
+curl -fsSL https://asdf9384.github.io/company-comms/install.sh | sh
```
-Each teammate runs the line the invite prints, which installs comms and joins in one go:
+It installs comms and asks a few questions: your name, start or join (start), a team name, which of your agents
+to put on comms, and whether to invite someone. The invite is a four-word code like `goal-hug-kilt-coil`, with
+a ready-to-send line on your clipboard:
```sh
-curl -fsSL https://raw.githubusercontent.com/asdf9384/company-comms/main/install.sh | sh -s -- comms1… --as alice
+curl -fsSL https://asdf9384.github.io/company-comms/install.sh | sh -s -- goal-hug-kilt-coil
```
-`init` and `join` also run `comms setup`, which wires comms into every agent it finds on the machine and starts
-a small background service. Restart running agent sessions to pick it up. To add another machine of your own:
-`comms invite --me` there, `comms join …` on the new one.
+Your teammate runs that, answers the same few questions, and is in. Restart agent sessions that were already
+running, then ask one: "who's on the team?"
-Codex asks once to trust the new hooks: choose "Trust all and continue". Gemini CLI only runs hooks and MCP
-servers in trusted folders.
+A code works once, within a day, while your machine is online. Later: `comms invite` for another code (or for
+another machine of yours), `comms setup` to change which agents are on comms, and `comms` on its own to see
+who's around. Codex asks once to trust the new hooks: choose "Trust all and continue". Gemini CLI only runs
+hooks and MCP servers in trusted folders.
+
+Agents (or scripts) can do all of this without prompts: `comms join <code> --as <name>`, `comms init <team>`.
## What agents get
@@ -89,11 +92,11 @@ comms who [filter] [--all] # the directory (filter by person, repo, agent
comms send <to> <message> # from you, the human; also `comms send alice "lunch?"`
comms inbox [--wait 60] # your messages
comms team # people, machines, and whether each is direct or relayed
-comms invite [--me] # invite a teammate (or another machine of yours)
+comms invite # a four-word code for a teammate, or another machine of yours
comms held / approve / reject # messages waiting for your approval (see policies)
comms remove <person|machine> # take someone out of the team
comms doctor # check that everything works
-comms setup [--remove] # wire agents up (or undo it)
+comms setup # choose which agents are on comms (--remove undoes everything)
comms leave # leave the team on this machine
```
@@ -117,6 +120,8 @@ comms leave # leave the team on this machine
```
Each sender is also limited to 30 messages a minute.
+- **Invite codes** are four random words (~41 bits). The code derives a temporary key the inviting machine
+ listens on, so joining needs no server; it works once, for a day.
- **No server of ours.** Machines connect directly (on the LAN, or hole-punched across the internet). When
that fails, traffic goes through a relay that only sees encrypted bytes: n0's public relays by default, or
your own with `comms relay https://relay.example.com` (run [`iroh-relay`](https://docs.iroh.computer/concepts/relays)
diff --git a/install.sh b/install.sh
index c828fe5..16d9b27 100755
--- a/install.sh
+++ b/install.sh
@@ -1,8 +1,8 @@
#!/bin/sh
# Installs comms (company-comms) for macOS or Linux.
#
-# curl -fsSL <this url> | sh install
-# curl -fsSL <this url> | sh -s -- <invite> install, then join a team (add --as <name> to pick your name)
+# curl -fsSL <this url> | sh install, then set up (start or join a team)
+# curl -fsSL <this url> | sh -s -- <invite code> install, then join that team
#
# Environment: COMMS_BIN_DIR (default ~/.local/bin), COMMS_VERSION (default latest), COMMS_REPO,
# COMMS_DOWNLOAD_BASE (a mirror serving the release files).
@@ -60,13 +60,17 @@ case ":$PATH:" in
say " export PATH=\"$bin_dir:\$PATH\"" ;;
esac
-if [ $# -gt 0 ]; then
- case "$1" in
- comms1*) exec "$bin_dir/comms" join "$@" ;;
- *) exec "$bin_dir/comms" "$@" ;;
+# Hand over to comms: 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.
+if { : </dev/tty; } 2>/dev/null; then
+ case "${1:-}" in
+ "") exec "$bin_dir/comms" </dev/tty ;;
+ -*) exec "$bin_dir/comms" "$@" </dev/tty ;;
+ *) exec "$bin_dir/comms" join "$@" </dev/tty ;;
esac
fi
-say ""
-say "Next:"
-say " comms init <team> --as <your-name> start a team"
-say " comms join <invite> --as <your-name> or join one"
+case "${1:-}" in
+ "") say ""; say "Next, in a terminal: comms" ;;
+ -*) exec "$bin_dir/comms" "$@" ;;
+ *) exec "$bin_dir/comms" join "$@" ;;
+esac
diff --git a/site/index.html b/site/index.html
index 5ac0d84..ad829de 100644
--- a/site/index.html
+++ b/site/index.html
@@ -52,10 +52,8 @@ alice · xps · <span class="acc">direct 4ms</span>
doing: fixing flaky refresh-token test</pre>
<h2>Start a team</h2>
-<pre><code>curl -fsSL https://raw.githubusercontent.com/asdf9384/company-comms/main/install.sh | sh
-comms init vibes --as you
-comms invite</code></pre>
- <p>Teammates paste the line the invite prints. It installs comms, joins the team, and wires up every agent on their machine.</p>
+<pre><code>curl -fsSL https://asdf9384.github.io/company-comms/install.sh | sh</code></pre>
+ <p>It asks a few questions (your name, a team name, which agents to put on comms) and gives you a four-word invite code like <code>goal-hug-kilt-coil</code>. Your teammates run the same line with the code at the end, answer the same questions, and they're in.</p>
<h2>What it does</h2>
<div class="grid">
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index fbe1d3a..1d42011 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -220,7 +220,7 @@ impl Daemon {
Request::Attach { agent, cwd } => json!(self.attach(&agent, &cwd)),
Request::CreateTeam { name, person } => json!(self.create_team(&name, &person).await?),
Request::Join { ticket, person } => json!(self.join_team(&ticket, &person).await?),
- Request::Invite { me, hours } => json!(self.invite(me, hours)?),
+ Request::Invite { me, hours } => json!(self.invite(me, hours).await?),
Request::Team => json!(self.team_info()?),
Request::Remove { who } => json!(self.remove(&who)?),
Request::Leave { force } => json!(self.leave(force).await?),
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 3aef70a..edbcc88 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -5,6 +5,7 @@ use crate::{
config::Config,
net::{self, JoinRequest, Net, Remote, Wire},
proto::*,
+ invite,
team::{TeamState, Ticket},
util,
};
@@ -54,7 +55,19 @@ impl Daemon {
}
let net = Net::start(self, endpoint, remote);
log(&format!("team {} · machine {}", team.name(), net.id().fmt_short()));
- *self.net.write().unwrap() = Some(net);
+ *self.net.write().unwrap() = Some(net.clone());
+ // Invite codes made here that are still good: listen for them again.
+ let codes: Vec<(String, i64)> = {
+ let g = self.inner.lock().unwrap();
+ g.store.prefixed("code:")?.into_iter().filter_map(|(k, v)| Some((k.strip_prefix("code:")?.to_string(), v.parse().ok()?))).collect()
+ };
+ for (code, expires) in codes {
+ if team.invite_unused(&invite::secret(&code)) {
+ net.listen_invite(invite::key(&code), expires, team.meta.body.relay.as_deref(), self.cfg.lan()).await?;
+ } else {
+ self.inner.lock().unwrap().store.delete_prefix(&format!("code:{code}"))?;
+ }
+ }
Ok(())
}
@@ -122,7 +135,7 @@ impl Daemon {
let state = {
let mut g = self.inner.lock().unwrap();
let team = g.team.as_mut().ok_or_else(|| anyhow!("this machine is not in a team any more"))?;
- if req.team != team.id {
+ if !req.team.is_empty() && req.team != team.id {
bail!("this invite is for a different team");
}
team.redeem(&self.key, &req.secret, &person, joiner)?;
@@ -157,26 +170,30 @@ impl Daemon {
Ok(TeamInfo { name: name.into(), relay: None, person, machine: self.machine.clone(), machines: Vec::new() })
}
- pub(super) async fn join_team(self: &Arc<Self>, ticket: &str, person: &str) -> Result<TeamInfo> {
+ /// Joins with an invite code (`plum-tiger-lake-orbit`) or a long `comms1…` ticket.
+ pub(super) async fn join_team(self: &Arc<Self>, invite_text: &str, person: &str) -> Result<TeamInfo> {
if let Some(t) = self.team_state() {
bail!("already in team '{}'; run `comms leave` first", t.name());
}
- let ticket = Ticket::decode(ticket)?;
let person = util::slug(person);
if person.is_empty() {
bail!("your name needs letters or digits");
}
- let endpoint = net::bind(self.key.clone(), ticket.relay.as_deref(), self.cfg.lan()).await?;
- let req = JoinRequest {
- team: ticket.team.clone(),
- secret: ticket.secret.clone(),
- person: person.clone(),
- machine: self.machine.clone(),
+ // A code points at the key the inviting machine listens on for it; a ticket lists machines.
+ let (team, secret, relay, peers) = match invite::normalize(invite_text) {
+ Some(code) => (String::new(), invite::secret(&code), None, vec![EndpointAddr::new(invite::key(&code).public())]),
+ None if invite_text.trim().starts_with("comms1") => {
+ let t = Ticket::decode(invite_text)?;
+ (t.team, t.secret, t.relay, t.peers)
+ }
+ None => bail!("that's not an invite code (four words, like plum-tiger-lake-orbit)"),
};
- let res = net::join(&endpoint, &ticket, &req).await;
+ let endpoint = net::bind(self.key.clone(), relay.as_deref(), self.cfg.lan()).await?;
+ let req = JoinRequest { team: team.clone(), secret, person: person.clone(), machine: self.machine.clone() };
+ let res = net::join(&endpoint, &peers, &req).await;
endpoint.close().await;
let state = TeamState::verified(&res?)?;
- if state.id != ticket.team || !state.is_active(&self.key.public()) {
+ if (!team.is_empty() && state.id != team) || !state.is_active(&self.key.public()) {
bail!("the team did not add this machine");
}
let info = TeamInfo {
@@ -202,27 +219,32 @@ impl Daemon {
cfg.save()
}
- pub(super) fn invite(&self, me: bool, hours: u64) -> Result<String> {
+ /// 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 `comms init` or `comms join`)"))?;
- let mut g = self.inner.lock().unwrap();
- let team = g.team.as_mut().ok_or_else(|| anyhow!("not in a team"))?;
- team.prune_invites();
- let secret = team.invite(&self.key, hours.clamp(1, 24 * 30), me.then(|| self.person.clone()));
- // This machine with its addresses, plus a few teammates (found by key) in case this one is offline.
- let mut peers = vec![net.addr()];
- peers.extend(team.active().map(|m| m.endpoint).filter(|e| *e != self.key.public()).take(3).map(EndpointAddr::new));
- let ticket = Ticket {
- team: team.id.clone(),
- name: team.name().into(),
- secret,
- relay: team.meta.body.relay.clone(),
- peers,
+ let hours = hours.clamp(1, 24 * 30);
+ let code = invite::generate();
+ let secret = invite::secret(&code);
+ let expires = util::now_ms() + hours as i64 * 3_600_000;
+ let (state, ticket) = {
+ let mut g = self.inner.lock().unwrap();
+ let team = g.team.as_mut().ok_or_else(|| anyhow!("not in a team"))?;
+ team.prune_invites();
+ team.invite(&self.key, &secret, hours, me.then(|| self.person.clone()));
+ // This machine with its addresses, plus a few teammates (found by key) in case this one is offline.
+ let mut peers = vec![net.addr()];
+ peers.extend(team.active().map(|m| m.endpoint).filter(|e| *e != self.key.public()).take(3).map(EndpointAddr::new));
+ let ticket = Ticket { team: team.id.clone(), name: team.name().into(), secret, relay: team.meta.body.relay.clone(), peers };
+ let state = team.clone();
+ self.save_team(&g)?;
+ g.store.set(&format!("code:{code}"), &expires.to_string())?;
+ (state, ticket)
};
- let state = team.clone();
- self.save_team(&g)?;
- drop(g);
+ let relay = state.meta.body.relay.clone();
net.broadcast(&Wire::State { state: Box::new(state) });
- Ok(ticket.encode())
+ net.listen_invite(invite::key(&code), expires, relay.as_deref(), self.cfg.lan()).await?;
+ Ok(InviteInfo { code, ticket: ticket.encode(), hours })
}
pub(super) fn team_info(&self) -> Result<TeamInfo> {
diff --git a/src/invite.rs b/src/invite.rs
new file mode 100644
index 0000000..a56dfb7
--- /dev/null
+++ b/src/invite.rs
@@ -0,0 +1,68 @@
+//! Invite codes: four words, like `plum-tiger-lake-orbit`. The code itself derives a temporary iroh key that
+//! the inviting machine listens on, and the secret the joiner proves, so joining needs nothing but the code: no
+//! server of ours, no long string to paste. Four words from 1295 give ~41 bits; a code works once, for a day,
+//! while the inviting machine is online.
+//!
+//! Words: the EFF short wordlist (https://www.eff.org/dice), CC BY 3.0 US.
+
+use data_encoding::HEXLOWER;
+use iroh::SecretKey;
+
+const WORDS: &str = include_str!("words.txt");
+const LEN: usize = 4;
+
+fn words() -> Vec<&'static str> {
+ WORDS.lines().filter(|w| !w.is_empty()).collect()
+}
+
+pub fn generate() -> String {
+ let words = words();
+ let n = words.len() as u32;
+ let mut out = Vec::with_capacity(LEN);
+ while out.len() < LEN {
+ let mut b = [0u8; 4];
+ getrandom::fill(&mut b).expect("system randomness");
+ let r = u32::from_le_bytes(b);
+ // Rejection sampling keeps every word equally likely.
+ if r < u32::MAX - u32::MAX % n {
+ out.push(words[(r % n) as usize]);
+ }
+ }
+ out.join("-")
+}
+
+/// `Plum Tiger lake-ORBIT` -> `plum-tiger-lake-orbit`, if it is four known words.
+pub fn normalize(input: &str) -> Option<String> {
+ let words = words();
+ let parts: Vec<String> =
+ input.split(|c: char| !c.is_ascii_alphabetic()).filter(|p| !p.is_empty()).map(|p| p.to_ascii_lowercase()).collect();
+ (parts.len() == LEN && parts.iter().all(|p| words.contains(&p.as_str()))).then(|| parts.join("-"))
+}
+
+/// The key the inviting machine listens on while the code is valid.
+pub fn key(code: &str) -> SecretKey {
+ SecretKey::from_bytes(&blake3::derive_key("company-comms 2026 invite endpoint", code.as_bytes()))
+}
+
+/// The invite secret the joiner proves (its hash is in the team state, like any invite's).
+pub fn secret(code: &str) -> String {
+ HEXLOWER.encode(&blake3::derive_key("company-comms 2026 invite secret", code.as_bytes())[..16])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn codes() {
+ let c = generate();
+ assert_eq!(c.split('-').count(), 4);
+ assert_eq!(normalize(&c.to_uppercase().replace('-', " ")).as_deref(), Some(c.as_str()));
+ assert_eq!(normalize("acid acorn acre"), None);
+ assert_eq!(normalize("acid acorn acre notaword"), None);
+ assert_eq!(key(&c).public(), key(&c).public());
+ assert_ne!(key("acid-acorn-acre-acid").public(), key(&c).public());
+ assert_eq!(secret(&c).len(), 32);
+ assert_eq!(words().len(), 1295);
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 912c027..840a1ef 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,6 +5,7 @@ mod config;
mod daemon;
mod git;
mod hook;
+mod invite;
mod mcp;
mod net;
mod paths;
@@ -14,6 +15,7 @@ mod setup;
mod store;
mod team;
mod util;
+mod wizard;
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
@@ -25,14 +27,19 @@ use std::{io::Read, time::Duration};
/// `COMMS_INSTALL_URL` to the project's domain.
pub const INSTALL_URL: &str = match option_env!("COMMS_INSTALL_URL") {
Some(u) if !u.is_empty() => u,
- _ => "https://raw.githubusercontent.com/asdf9384/company-comms/main/install.sh",
+ _ => "https://asdf9384.github.io/company-comms/install.sh",
};
#[derive(Parser)]
-#[command(name = "comms", version, about = "Team directory and message bus for coding agents")]
+#[command(
+ name = "comms",
+ version,
+ about = "Your team's coding agents, talking to each other",
+ after_help = "Run `comms` on its own to get set up, then to see who's working on what."
+)]
struct Cli {
#[command(subcommand)]
- cmd: Cmd,
+ cmd: Option<Cmd>,
}
#[derive(Subcommand)]
@@ -75,9 +82,9 @@ enum Cmd {
#[arg(long)]
name: Option<String>,
},
- /// Create a team, with you as its first member
+ /// Start a team, with you as its first member
Init {
- team: String,
+ team: Option<String>,
/// Your name in the team (default: $USER)
#[arg(long = "as")]
person: Option<String>,
@@ -85,7 +92,7 @@ enum Cmd {
#[arg(long)]
no_setup: bool,
},
- /// Print an invite for a teammate (or, with --me, for another machine of yours)
+ /// Invite a teammate (or another machine of yours)
Invite {
#[arg(long)]
me: bool,
@@ -93,9 +100,9 @@ enum Cmd {
#[arg(long, default_value_t = 24)]
hours: u64,
},
- /// Join a team with an invite
+ /// Join a team with an invite code
Join {
- invite: String,
+ invite: Option<String>,
/// Your name in the team (default: $USER)
#[arg(long = "as")]
person: Option<String>,
@@ -169,14 +176,26 @@ enum Cmd {
#[tokio::main]
async fn main() -> Result<()> {
match Cli::parse().cmd {
- Cmd::Daemon { service } => daemon::run(service).await,
- Cmd::Mcp => mcp::run().await,
- Cmd::Hook { agent, event, session, state } => {
+ Some(Cmd::Daemon { service }) => daemon::run(service).await,
+ Some(Cmd::Mcp) => mcp::run().await,
+ Some(Cmd::Hook { agent, event, session, state }) => {
hook::run(&agent, &event, session, state).await;
// Don't wait on anything left behind (a stuck stdin read): the agent is waiting on us.
std::process::exit(0)
}
- cmd => cli(cmd).await,
+ Some(cmd) => cli(cmd).await,
+ // `comms` alone: get set up if needed, else show who's around.
+ None => {
+ let in_team = Link::new(None).call::<TeamInfo>(Request::Team).await.is_ok();
+ if !in_team && wizard::interactive() {
+ return wizard::guided(wizard::onboard(None, None, None, None)).await;
+ }
+ if !in_team {
+ println!("Not in a team yet. Run `comms` in a terminal to get set up (or `comms init <team>` / `comms join <code>`).");
+ return Ok(());
+ }
+ cli(Cmd::Who { filter: None, all: false, json: false }).await
+ }
}
}
@@ -235,7 +254,18 @@ async fn cli(cmd: Cmd) -> Result<()> {
let r: Registered = link.call(Request::SetStatus { key, doing, name }).await?;
println!("You are {}.", r.address);
}
+ Cmd::Init { team, person, no_setup } if !no_setup && wizard::interactive() => {
+ wizard::guided(wizard::onboard(Some(true), team, None, person)).await?
+ }
+ Cmd::Join { invite, person, no_setup } if !no_setup && wizard::interactive() => {
+ wizard::guided(wizard::onboard(Some(false), None, invite, person)).await?
+ }
+ Cmd::Invite { me: false, hours } if wizard::interactive() => wizard::guided(wizard::invite(hours.clamp(1, 24 * 30))).await?,
+ Cmd::Setup { dry_run: false, remove: false, no_service: false } if wizard::interactive() => {
+ wizard::guided(wizard::setup_agents()).await?
+ }
Cmd::Init { team, person, no_setup } => {
+ let Some(team) = team else { bail!("name the team: `comms init <team>` (or run it in a terminal to be asked)") };
let t: TeamInfo = link.call(Request::CreateTeam { name: team, person: default_person(person) }).await?;
wait_exit(daemon_pid()).await;
println!("Created team {}. You are {} on {}.", t.name, t.person, t.machine);
@@ -246,6 +276,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
println!("\nNext: `comms invite` prints an invite for each teammate.");
}
Cmd::Join { invite, person, no_setup } => {
+ let Some(invite) = invite else { bail!("give the invite code: `comms 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);
@@ -268,14 +299,13 @@ async fn cli(cmd: Cmd) -> Result<()> {
}
}
Cmd::Invite { me, hours } => {
- let hours = hours.clamp(1, 24 * 30);
- let ticket: String = link.call(Request::Invite { me, hours }).await?;
+ 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 for {who} (single use, expires in {hours}h):\n");
- let as_flag = if me { format!(" --as {}", config::Config::load().person()) } else { String::new() };
- println!(" comms join {ticket}{as_flag}\n");
- println!("Without comms installed yet, this installs and joins in one go:\n");
- println!(" curl -fsSL {INSTALL_URL} | sh -s -- {ticket}");
+ println!("Invite code for {who}: {}\n", i.code);
+ println!("They run this, which installs comms and joins the team:\n");
+ println!(" curl -fsSL {INSTALL_URL} | sh -s -- {}\n", i.code);
+ println!("(or `comms join {}` if they have comms). 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: comms join {}", i.ticket);
}
Cmd::Team => {
let t: TeamInfo = link.call(Request::Team).await?;
@@ -333,7 +363,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
println!("The daemon is not running.");
}
}
- Cmd::Daemon { .. } | Cmd::Mcp | Cmd::Hook { .. } => unreachable!(),
+ Cmd::Daemon { .. } | Cmd::Mcp | Cmd::Hook { .. } => unreachable!("handled in main"),
}
Ok(())
}
diff --git a/src/net.rs b/src/net.rs
index 1019721..bb5d61d 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -5,7 +5,7 @@
use crate::{
daemon::Daemon,
proto::{Message, SessionInfo},
- team::{TeamState, Ticket},
+ team::TeamState,
util,
};
use anyhow::{Result, anyhow, bail};
@@ -91,6 +91,8 @@ struct Link {
pub struct Net {
endpoint: Endpoint,
router: Mutex<Option<Router>>,
+ /// Endpoints listening for joins on behalf of invite codes, by their (code-derived) id.
+ invites: Mutex<HashMap<EndpointId, Router>>,
me: EndpointId,
daemon: Weak<Daemon>,
links: Mutex<HashMap<EndpointId, Link>>,
@@ -139,10 +141,10 @@ async fn read_frame<T: DeserializeOwned>(recv: &mut RecvStream) -> Result<T> {
Ok(serde_json::from_slice(&buf)?)
}
-/// Joins a team: asks the machines in the ticket, in turn, to let us in.
-pub async fn join(endpoint: &Endpoint, ticket: &Ticket, req: &JoinRequest) -> Result<TeamState> {
+/// Joins a team: asks each machine in turn (the ticket's, or the one an invite code points at) to let us in.
+pub async fn join(endpoint: &Endpoint, peers: &[EndpointAddr], req: &JoinRequest) -> Result<TeamState> {
let mut last = anyhow!("the invite lists no machines");
- for addr in &ticket.peers {
+ for addr in peers {
let attempt = async {
let conn = endpoint.connect(addr.clone(), JOIN_ALPN).await?;
let (mut send, mut recv) = conn.open_bi().await?;
@@ -157,7 +159,7 @@ pub async fn join(endpoint: &Endpoint, ticket: &Ticket, req: &JoinRequest) -> Re
// A refusal is final: another machine would say the same.
Ok(Ok(JoinReply::Err { error })) => bail!(error),
Ok(Err(e)) => last = e,
- Err(_) => last = anyhow!("timed out reaching {}", addr.id.fmt_short()),
+ Err(_) => last = anyhow!("couldn't reach the machine that made the invite (is it online?)"),
}
}
Err(last)
@@ -166,8 +168,10 @@ pub async fn join(endpoint: &Endpoint, ticket: &Ticket, req: &JoinRequest) -> Re
#[derive(Debug, Clone)]
struct PeerProto(Weak<Net>);
+/// The join protocol, on the main endpoint (tickets) or on an invite code's own endpoint (`Some(its id)`, closed
+/// once the code is used).
#[derive(Debug, Clone)]
-struct JoinProto(Weak<Net>);
+struct JoinProto(Weak<Net>, Option<EndpointId>);
impl std::fmt::Debug for Net {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -210,16 +214,19 @@ impl ProtocolHandler for JoinProto {
let (mut send, mut recv) = conn.accept_bi().await?;
let req: JoinRequest = read_frame(&mut recv).await?;
let daemon = net.daemon.upgrade().ok_or_else(|| anyhow!("shutting down"))?;
- let reply = match daemon.redeem(joiner, &req) {
+ let (reply, joined) = match daemon.redeem(joiner, &req) {
Ok(state) => {
log(&format!("{} joined as {} on {}", joiner.fmt_short(), req.person, req.machine));
- JoinReply::Ok { state: Box::new(state) }
+ (JoinReply::Ok { state: Box::new(state) }, true)
}
- Err(e) => JoinReply::Err { error: format!("{e:#}") },
+ Err(e) => (JoinReply::Err { error: format!("{e:#}") }, false),
};
write_frame(&mut send, &reply).await?;
send.finish()?;
let _ = tokio::time::timeout(Duration::from_secs(5), conn.closed()).await;
+ if joined && let Some(code) = self.1 {
+ net.close_invite(&code);
+ }
Ok(())
}
.await;
@@ -237,9 +244,10 @@ impl Net {
router: Mutex::new(Some(
Router::builder(endpoint.clone())
.accept(ALPN, PeerProto(weak.clone()))
- .accept(JOIN_ALPN, JoinProto(weak.clone()))
+ .accept(JOIN_ALPN, JoinProto(weak.clone(), None))
.spawn(),
)),
+ invites: Default::default(),
endpoint,
daemon: Arc::downgrade(daemon),
links: Default::default(),
@@ -267,6 +275,34 @@ impl Net {
if let Some(r) = router {
let _ = r.shutdown().await;
}
+ let invites: Vec<Router> = self.invites.lock().unwrap().drain().map(|(_, r)| r).collect();
+ for r in invites {
+ let _ = r.shutdown().await;
+ }
+ }
+
+ /// Listens for a joiner on an invite code's own key until `expires` (ms) or until it is used.
+ pub async fn listen_invite(self: &Arc<Self>, key: SecretKey, expires: i64, relay: Option<&str>, lan: bool) -> Result<()> {
+ let endpoint = bind(key, relay, lan).await?;
+ let id = endpoint.id();
+ let router = Router::builder(endpoint).accept(JOIN_ALPN, JoinProto(Arc::downgrade(self), Some(id))).spawn();
+ self.invites.lock().unwrap().insert(id, router);
+ let (net, left) = (Arc::downgrade(self), (expires - util::now_ms()).max(0) as u64);
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(left)).await;
+ if let Some(net) = net.upgrade() {
+ net.close_invite(&id);
+ }
+ });
+ Ok(())
+ }
+
+ pub fn close_invite(&self, id: &EndpointId) {
+ if let Some(r) = self.invites.lock().unwrap().remove(id) {
+ tokio::spawn(async move {
+ let _ = r.shutdown().await;
+ });
+ }
}
/// Dial anyone we're not connected to now, instead of at the next tick.
diff --git a/src/proto.rs b/src/proto.rs
index 6f60f55..ec08001 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -260,6 +260,15 @@ pub struct TeamInfo {
pub machines: Vec<MachineInfo>,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct InviteInfo {
+ /// Four words, like `plum-tiger-lake-orbit`.
+ pub code: String,
+ /// The same invite as a long `comms1…` string, for when the inviting machine will be offline.
+ pub ticket: String,
+ pub hours: u64,
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HookReply {
pub address: Option<String>,
diff --git a/src/setup.rs b/src/setup.rs
index fadb6d5..ec84933 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -19,7 +19,7 @@ struct Report {
notes: Vec<String>,
}
-fn exe() -> Result<PathBuf> {
+pub fn exe() -> Result<PathBuf> {
Ok(std::env::current_exe()?.canonicalize()?)
}
@@ -388,6 +388,10 @@ fn opencode(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
// ---- background service ----
+pub fn service_installed() -> bool {
+ service_path().exists()
+}
+
fn service_path() -> PathBuf {
if cfg!(target_os = "macos") {
home().join(format!("Library/LaunchAgents/{SERVICE}.plist"))
@@ -485,38 +489,147 @@ fn xml(s: &str) -> String {
}
type AgentFn = fn(&Path, bool, bool) -> Result<Option<Report>>;
-const AGENTS: [(&str, AgentFn); 6] =
- [("Claude Code", claude), ("Codex", codex), ("Cursor", cursor), ("Gemini CLI", gemini), ("Copilot CLI", copilot), ("opencode", opencode)];
-pub async fn run(dry: bool, remove: bool, no_service: bool) -> Result<()> {
- let exe = exe()?;
- let verb = if dry { "Would change" } else if remove { "Removing comms" } else { "Setting up comms" };
- println!("{verb} ({}):", crate::util::tilde(&exe.display().to_string()));
- let mut notes = Vec::new();
- let mut found = 0;
- for (name, f) in AGENTS {
- match f(&exe, remove, dry) {
+struct Agent {
+ id: &'static str,
+ name: &'static str,
+ /// How quickly it sees messages, and anything to know.
+ hint: &'static str,
+ installed: fn() -> bool,
+ wired: fn(&Path) -> bool,
+ apply: AgentFn,
+}
+
+fn has(path: PathBuf, needle: &str) -> bool {
+ std::fs::read_to_string(path).is_ok_and(|s| s.contains(needle))
+}
+
+fn me(exe: &Path) -> String {
+ exe.display().to_string()
+}
+
+const AGENTS: [Agent; 6] = [
+ Agent {
+ id: "claude",
+ name: "Claude Code",
+ hint: "messages arrive instantly",
+ installed: || agent::find_bin("claude").is_some(),
+ wired: |_| {
+ agent::find_bin("claude")
+ .is_some_and(|b| Command::new(b).args(["mcp", "get", "comms"]).output().is_ok_and(|o| o.status.success()))
+ },
+ apply: claude,
+ },
+ Agent {
+ id: "codex",
+ name: "Codex",
+ hint: "instant; asks once to trust the hooks",
+ installed: || agent::find_bin("codex").is_some() || codex_home().exists(),
+ wired: |exe| has(codex_home().join("config.toml"), &me(exe)) && has(codex_home().join("hooks.json"), "hook codex"),
+ apply: codex,
+ },
+ Agent {
+ id: "cursor",
+ name: "Cursor",
+ hint: "sees messages at its next step",
+ installed: || home().join(".cursor").exists() || agent::find_bin("cursor-agent").is_some(),
+ wired: |exe| has(home().join(".cursor/mcp.json"), &me(exe)),
+ apply: cursor,
+ },
+ Agent {
+ id: "gemini",
+ name: "Gemini CLI",
+ hint: "at its next step; trusted folders only",
+ installed: || gemini_home().exists() || agent::find_bin("gemini").is_some(),
+ wired: |exe| has(gemini_home().join("settings.json"), &me(exe)),
+ apply: gemini,
+ },
+ Agent {
+ id: "copilot",
+ name: "Copilot CLI",
+ hint: "sees messages at its next step",
+ installed: || home().join(".copilot").exists() || agent::find_bin("copilot").is_some(),
+ wired: |exe| has(home().join(".copilot/mcp-config.json"), &me(exe)),
+ apply: copilot,
+ },
+ Agent {
+ id: "opencode",
+ name: "opencode",
+ hint: "messages arrive within seconds",
+ installed: || opencode_home().exists() || agent::find_bin("opencode").is_some(),
+ wired: |_| opencode_home().join("plugins/comms.ts").exists(),
+ apply: opencode,
+ },
+];
+
+/// An agent found on this machine.
+pub struct Found {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub hint: &'static str,
+ pub wired: bool,
+}
+
+pub fn detect(exe: &Path) -> Vec<Found> {
+ AGENTS
+ .iter()
+ .filter(|a| (a.installed)())
+ .map(|a| Found { id: a.id, name: a.name, hint: a.hint, wired: (a.wired)(exe) })
+ .collect()
+}
+
+/// What `apply` did: a line per agent (and the service), and things the user should know.
+#[derive(Default)]
+pub struct Applied {
+ pub lines: Vec<String>,
+ pub notes: Vec<String>,
+}
+
+/// Wires comms into the `install` agents and out of the `remove` ones; installs (`Some(true)`) or removes
+/// (`Some(false)`) the login service.
+pub async fn apply(exe: &Path, install: &[&str], remove: &[&str], service: Option<bool>, dry: bool) -> Applied {
+ let mut out = Applied::default();
+ for a in &AGENTS {
+ let removing = remove.contains(&a.id);
+ if !removing && !install.contains(&a.id) {
+ continue;
+ }
+ match (a.apply)(exe, removing, dry) {
Ok(Some(r)) => {
- found += 1;
- println!(" {}: {}", r.agent, r.lines.join("; "));
- notes.extend(r.notes);
+ out.lines.push(format!("{}: {}", r.agent, r.lines.join("; ")));
+ out.notes.extend(r.notes);
}
Ok(None) => {}
- Err(e) => println!(" {name}: skipped ({e:#})"),
+ Err(e) => out.lines.push(format!("{}: skipped ({e:#})", a.name)),
}
}
- if found == 0 && !remove {
+ if let Some(on) = service {
+ match self::service(exe, !on, dry).await {
+ Ok(s) => out.lines.push(format!("service: {s}")),
+ Err(e) => out.lines.push(format!("service: not installed ({e:#}); the daemon still starts on demand")),
+ }
+ }
+ out
+}
+
+/// Non-interactive setup: every agent found (or, with `remove`, every agent wired).
+pub async fn run(dry: bool, remove: bool, no_service: bool) -> Result<()> {
+ let exe = exe()?;
+ let found = detect(&exe);
+ let verb = if dry { "Would change" } else if remove { "Removing comms" } else { "Setting up comms" };
+ println!("{verb} ({}):", crate::util::tilde(&exe.display().to_string()));
+ if found.is_empty() && !remove {
println!(" no supported agents found (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode)");
}
- if !no_service {
- match service(&exe, remove, dry).await {
- Ok(s) => println!(" service: {s}"),
- Err(e) => println!(" service: not installed ({e:#}); the daemon still starts on demand"),
- }
+ let ids: Vec<&str> = found.iter().map(|f| f.id).collect();
+ let (install, removing): (&[&str], &[&str]) = if remove { (&[], &ids) } else { (&ids, &[]) };
+ let out = apply(&exe, install, removing, (!no_service).then_some(!remove), dry).await;
+ for l in &out.lines {
+ println!(" {l}");
}
- if !notes.is_empty() {
+ if !out.notes.is_empty() {
println!();
- for n in notes {
+ for n in &out.notes {
println!("- {n}");
}
}
@@ -540,7 +653,7 @@ pub async fn doctor() -> Result<()> {
}
Err(e) if e.to_string().contains("not in a team") => {
println!("✓ daemon running");
- println!("- not in a team yet: `comms init <team>` or `comms join <invite>`");
+ println!("- not in a team yet: run `comms`");
}
Err(e) => println!("✗ daemon: {e:#}"),
}
@@ -550,23 +663,11 @@ pub async fn doctor() -> Result<()> {
if svc.exists() { "✓" } else { "-" },
if svc.exists() { "installed" } else { "not installed (`comms setup`)" }
);
- let me = exe.display().to_string();
- let has = |p: PathBuf, needle: &str| std::fs::read_to_string(p).is_ok_and(|s| s.contains(needle));
- let checks: [(&str, bool, bool); 6] = [
- ("Claude Code", agent::find_bin("claude").is_some(), agent::find_bin("claude").is_some_and(|b| {
- Command::new(b).args(["mcp", "get", "comms"]).output().is_ok_and(|o| o.status.success())
- })),
- ("Codex", codex_home().exists(), has(codex_home().join("config.toml"), &me) && has(codex_home().join("hooks.json"), "hook codex")),
- ("Cursor", home().join(".cursor").exists(), has(home().join(".cursor/mcp.json"), &me)),
- ("Gemini CLI", gemini_home().exists(), has(gemini_home().join("settings.json"), &me)),
- ("Copilot CLI", home().join(".copilot").exists(), has(home().join(".copilot/mcp-config.json"), &me)),
- ("opencode", opencode_home().exists(), opencode_home().join("plugins/comms.ts").exists()),
- ];
- for (name, installed, wired) in checks {
- match (installed, wired) {
- (false, _) => {}
- (true, true) => println!("✓ {name}: wired up"),
- (true, false) => println!("✗ {name}: installed but not wired up (`comms setup`)"),
+ for f in detect(&exe) {
+ if f.wired {
+ println!("✓ {}: wired up", f.name);
+ } else {
+ println!("- {}: installed, not on comms (`comms setup`)", f.name);
}
}
Ok(())
diff --git a/src/store.rs b/src/store.rs
index b4a566a..c9875c0 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -155,6 +155,12 @@ impl Store {
Ok(())
}
+ pub fn prefixed(&self, prefix: &str) -> Result<Vec<(String, String)>> {
+ let mut st = self.db.prepare_cached("SELECT key, value FROM kv WHERE key >= ?1 AND key < ?1 || x'ff'")?;
+ let rows = st.query_map([prefix], |r| Ok((r.get(0)?, r.get(1)?)))?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
pub fn delete_prefix(&self, prefix: &str) -> Result<()> {
self.db.execute("DELETE FROM kv WHERE key >= ?1 AND key < ?1 || x'ff'", [prefix])?;
Ok(())
diff --git a/src/team.rs b/src/team.rs
index 1bad1a2..5a146a0 100644
--- a/src/team.rs
+++ b/src/team.rs
@@ -170,15 +170,15 @@ impl TeamState {
self.meta = Signed::new(body, key, &self.id, "meta");
}
- /// Creates an invite and returns its secret.
- pub fn invite(&mut self, key: &SecretKey, hours: u64, person: Option<String>) -> String {
- let mut secret = [0u8; 16];
- getrandom::fill(&mut secret).expect("system randomness");
- let secret = HEXLOWER.encode(&secret);
+ /// Creates an invite for `secret` (an invite code's, or random for a ticket).
+ pub fn invite(&mut self, key: &SecretKey, secret: &str, hours: u64, person: Option<String>) {
let now = util::now_ms();
- let body = Invite { hash: hash(&secret), expires: now + hours as i64 * 3_600_000, person, used_by: None, ts: now };
+ let body = Invite { hash: hash(secret), expires: now + hours as i64 * 3_600_000, person, used_by: None, ts: now };
self.invites.insert(body.hash.clone(), Signed::new(body, key, &self.id, "invite"));
- secret
+ }
+
+ pub fn invite_unused(&self, secret: &str) -> bool {
+ self.invites.get(&hash(secret)).is_some_and(|i| i.body.used_by.is_none() && i.body.expires > util::now_ms())
}
/// Checks that `secret` admits `person`, and marks the invite used by `joiner`.
@@ -345,11 +345,16 @@ mod tests {
SecretKey::generate()
}
+ fn random_secret() -> String {
+ crate::invite::secret(&crate::invite::generate())
+ }
+
#[test]
fn found_invite_join_merge() {
let (a, b, c) = (key(), key(), key());
let mut sa = TeamState::found("vibes", "tal", "mbp", &a);
- let secret = sa.invite(&a, 24, None);
+ let secret = random_secret();
+ sa.invite(&a, &secret, 24, None);
// b joins through a: a redeems and adds b; b verifies what it receives.
sa.redeem(&a, &secret, "alice", b.public()).unwrap();
@@ -360,7 +365,8 @@ mod tests {
assert!(sa.redeem(&a, &secret, "eve", c.public()).is_err(), "invites are single use");
// b invites c; a learns about c by merging b's copy.
- let s2 = sb.invite(&b, 1, None);
+ let s2 = random_secret();
+ sb.invite(&b, &s2, 1, None);
sb.redeem(&b, &s2, "sam", c.public()).unwrap();
sb.put_member(&b, c.public(), "sam", "nuc", true);
assert!(sa.merge(&sb).unwrap());
@@ -409,7 +415,8 @@ mod tests {
let mut s = TeamState::found("vibes", "tal", "mbp", &f);
s.put_member(&f, b.public(), "alice", "xps", true);
s.put_member(&f, f.public(), "tal", "mbp", false); // founder leaves
- let secret = s.invite(&b, 24, None);
+ let secret = random_secret();
+ s.invite(&b, &secret, 24, None);
s.redeem(&b, &secret, "sam", d.public()).unwrap();
s.put_member(&b, d.public(), "sam", "nuc", true);
let sd = TeamState::verified(&s).unwrap();
@@ -433,7 +440,8 @@ mod tests {
assert_eq!(x, y);
assert!(x.is_active(&c.public()) && !x.is_active(&b.public()));
// A newcomer sees the same, including c (admitted by b, who is gone now).
- let secret = x.invite(&f, 24, None);
+ let secret = random_secret();
+ x.invite(&f, &secret, 24, None);
x.redeem(&f, &secret, "dee", d.public()).unwrap();
x.put_member(&f, d.public(), "dee", "pi", true);
let z = TeamState::verified(&x).unwrap();
@@ -444,11 +452,13 @@ mod tests {
fn invites_die_with_their_maker_and_cant_readmit() {
let (a, b, c) = (key(), key(), key());
let mut s = TeamState::found("vibes", "tal", "mbp", &a);
- let first = s.invite(&a, 24, None);
+ let first = random_secret();
+ s.invite(&a, &first, 24, None);
s.redeem(&a, &first, "alice", b.public()).unwrap();
s.put_member(&a, b.public(), "alice", "xps", true);
assert!(s.redeem(&a, &first, "alice", b.public()).is_ok(), "a retry by the same machine is fine");
- let from_b = s.invite(&b, 720, None);
+ let from_b = random_secret();
+ s.invite(&b, &from_b, 720, None);
s.put_member(&a, b.public(), "alice", "xps", false);
assert!(s.redeem(&a, &first, "alice", b.public()).is_err(), "removed: the old invite doesn't readmit");
assert!(s.redeem(&a, &from_b, "sam", c.public()).is_err(), "invites by a removed machine are dead");
@@ -471,9 +481,11 @@ mod tests {
fn names_are_unique_unless_invited_for_self() {
let (a, b) = (key(), key());
let mut s = TeamState::found("vibes", "tal", "mbp", &a);
- let open = s.invite(&a, 24, None);
+ let open = random_secret();
+ s.invite(&a, &open, 24, None);
assert!(s.redeem(&a, &open, "tal", b.public()).is_err());
- let mine = s.invite(&a, 24, Some("tal".into()));
+ let mine = random_secret();
+ s.invite(&a, &mine, 24, Some("tal".into()));
assert!(s.redeem(&a, &mine, "alice", b.public()).is_err());
s.redeem(&a, &mine, "tal", b.public()).unwrap();
}
diff --git a/src/wizard.rs b/src/wizard.rs
new file mode 100644
index 0000000..8b2094f
--- /dev/null
+++ b/src/wizard.rs
@@ -0,0 +1,219 @@
+//! The guided setup: what `comms`, `comms init`, `comms join`, `comms invite` and `comms setup` do when a person
+//! runs them in a terminal. Without a terminal (an agent running them), the commands use defaults and flags.
+
+use crate::{
+ INSTALL_URL,
+ client::Link,
+ config::{Config, Policy},
+ invite,
+ proto::*,
+ render, setup, util,
+};
+use anyhow::{Result, anyhow};
+use cliclack::{confirm, input, intro, log, multiselect, note, outro, outro_cancel, select, spinner};
+use std::io::IsTerminal;
+
+pub fn interactive() -> bool {
+ std::io::stdin().is_terminal() && std::io::stderr().is_terminal() && std::env::var_os("COMMS_NO_PROMPT").is_none()
+}
+
+/// Runs a guided flow, turning Ctrl-C at a prompt into a quiet exit.
+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 `comms` to pick up where you left off.");
+ Ok(())
+ }
+ r => r,
+ }
+}
+
+fn name_ok(s: &str) -> Result<(), &'static str> {
+ if util::slug(s).is_empty() { Err("letters or digits, please") } else { Ok(()) }
+}
+
+/// Start or join a team, then set up agents. `start`: `Some(true)` from `comms init`, `Some(false)` from
+/// `comms join`, `None` to ask.
+pub async fn onboard(start: Option<bool>, team: Option<String>, code: Option<String>, person: Option<String>) -> Result<()> {
+ intro(" comms ")?;
+ 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("`comms` shows who's around; `comms invite` adds someone; `comms setup` changes your agents.")?;
+ return Ok(());
+ }
+ let mut person = match person {
+ Some(p) => util::slug(&p),
+ None => util::slug(
+ &input("What should teammates call you?").default_input(&Config::load().person()).validate(|s: &String| name_ok(s)).interact::<String>()?,
+ ),
+ };
+ let start = match (start, &code) {
+ (Some(s), _) => s,
+ (None, Some(_)) => false,
+ (None, None) => select("Start a new team, or join one?")
+ .item(false, "Join a team", "I have an invite code")
+ .item(true, "Start a new team", "")
+ .interact()?,
+ };
+
+ if start {
+ let name: String = match team {
+ Some(t) => t,
+ None => input("Name your team").placeholder("vibes").validate(|s: &String| name_ok(s)).interact()?,
+ };
+ let sp = spinner();
+ sp.start("Creating the team...");
+ let t: TeamInfo = link.call(Request::CreateTeam { name, person }).await.inspect_err(|e| sp.error(format!("{e:#}")))?;
+ crate::wait_exit(crate::daemon_pid()).await;
+ sp.stop(format!("Created team {}. You are {} on {}.", t.name, t.person, t.machine));
+ } else {
+ let mut code = code;
+ loop {
+ let c: String = match code.take() {
+ Some(c) => c,
+ None => input("Invite code")
+ .placeholder("plum-tiger-lake-orbit")
+ .validate(|s: &String| {
+ if invite::normalize(s).is_some() || s.trim().starts_with("comms1") {
+ Ok(())
+ } else {
+ Err("four words, like plum-tiger-lake-orbit")
+ }
+ })
+ .interact()?,
+ };
+ let sp = spinner();
+ sp.start("Finding the team...");
+ match link.call::<TeamInfo>(Request::Join { ticket: c.clone(), person: person.clone() }).await {
+ Ok(t) => {
+ crate::wait_exit(crate::daemon_pid()).await;
+ sp.stop(format!("Joined team {} as {} on {}.", t.name, t.person, t.machine));
+ break;
+ }
+ Err(e) if e.to_string().contains("already in this team") => {
+ sp.error(format!("Someone in the team is already called {person}."));
+ person = util::slug(&input("Pick another name").validate(|s: &String| name_ok(s)).interact::<String>()?);
+ code = Some(c);
+ }
+ Err(e) => {
+ sp.error(format!("{e:#}"));
+ if !confirm("Try again?").initial_value(true).interact()? {
+ return Err(anyhow!("not joined"));
+ }
+ code = Some(c).filter(|_| e.to_string().contains("reach"));
+ }
+ }
+ }
+ }
+
+ agents_and_preferences(true).await?;
+
+ if start {
+ if confirm("Invite a teammate now?").initial_value(true).interact()? {
+ show_invite(false, 24).await?;
+ }
+ } else if let Ok(t) = Link::new(None).call::<TeamInfo>(Request::Team).await {
+ note("Your team", render::team(&t).trim_end())?;
+ }
+ outro("All set. Restart agent sessions that were already running, then ask one: \"who's on the team?\"")?;
+ Ok(())
+}
+
+/// Which agents are on comms, the background service, and how teammates' messages are handled.
+pub async fn agents_and_preferences(first: bool) -> 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). Install one, then run `comms setup`.")?;
+ Vec::new()
+ } else {
+ let initial: Vec<&str> = found.iter().filter(|f| first || f.wired).map(|f| f.id).collect();
+ let mut pick = multiselect("Which agents should be on comms? (space to toggle, enter to confirm)").required(false).initial_values(initial);
+ for f in &found {
+ pick = pick.item(f.id, f.name, f.hint);
+ }
+ pick.interact()?
+ };
+ let service = confirm("Keep comms running in the background, so teammates can always reach you?").initial_value(true).interact()?;
+ 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 `comms held`")
+ .initial_value(cfg.inbound.default)
+ .interact()?;
+ cfg.share_paths = confirm("Show teammates your full working directories? (otherwise just the folder name)")
+ .initial_value(cfg.share_paths)
+ .interact()?;
+ cfg.save()?;
+
+ let remove: Vec<&str> = found.iter().filter(|f| f.wired && !chosen.contains(&f.id)).map(|f| f.id).collect();
+ let sp = spinner();
+ sp.start("Setting up...");
+ // The daemon reads its config at start: restart it (the service manager or the next command brings it back).
+ crate::stop_daemon().await;
+ let service = if service { Some(true) } else { setup::service_installed().then_some(false) };
+ let out = setup::apply(&exe, &chosen, &remove, service, false).await;
+ sp.stop("Done");
+ for l in &out.lines {
+ log::success(l)?;
+ }
+ for n in &out.notes {
+ log::warning(n)?;
+ }
+ Ok(())
+}
+
+/// Makes an invite and shows it, ready to send.
+pub async fn show_invite(me: bool, hours: u64) -> Result<()> {
+ let i: InviteInfo = Link::new(None).call(Request::Invite { me, hours }).await?;
+ let one_liner = format!("curl -fsSL {INSTALL_URL} | sh -s -- {}", i.code);
+ let copied = copy(&one_liner);
+ let who = if me { "your other machine" } else { "your teammate" };
+ note(
+ format!("Invite code: {}", i.code),
+ format!(
+ "Send {who} this line, which installs comms and joins the team:\n\n {one_liner}\n\n{}Already have comms? `comms join {}`\nWorks once, within {}h, while this machine is online.",
+ if copied { "(It's on your clipboard.)\n" } else { "" },
+ i.code,
+ i.hours
+ ),
+ )?;
+ Ok(())
+}
+
+/// Puts text on the clipboard, if there's a clipboard tool. True if it worked.
+fn copy(text: &str) -> bool {
+ use std::io::Write;
+ let tools: [(&str, &[&str]); 3] = [("pbcopy", &[]), ("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])];
+ tools.iter().any(|(bin, args)| {
+ let Ok(mut child) = std::process::Command::new(bin)
+ .args(*args)
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ else {
+ return false;
+ };
+ let wrote = child.stdin.take().is_some_and(|mut s| s.write_all(text.as_bytes()).is_ok());
+ child.wait().is_ok_and(|st| st.success()) && wrote
+ })
+}
+
+/// `comms invite` in a terminal: ask who it's for.
+pub async fn invite(hours: u64) -> Result<()> {
+ intro(" comms invite ")?;
+ let me = select("Who's this invite for?").item(false, "A teammate", "").item(true, "Another machine of mine", "").interact()?;
+ show_invite(me, hours).await?;
+ outro("They'll show up in `comms` once they've joined.")?;
+ Ok(())
+}
+
+/// `comms setup` in a terminal.
+pub async fn setup_agents() -> Result<()> {
+ intro(" comms setup ")?;
+ agents_and_preferences(false).await?;
+ outro("Restart agent sessions that were already running to pick up changes.")?;
+ Ok(())
+}
diff --git a/src/words.txt b/src/words.txt
new file mode 100644
index 0000000..028ca87
--- /dev/null
+++ b/src/words.txt
@@ -0,0 +1,1295 @@
+acid
+acorn
+acre
+acts
+afar
+affix
+aged
+agent
+agile
+aging
+agony
+ahead
+aide
+aids
+aim
+ajar
+alarm
+alias
+alibi
+alien
+alike
+alive
+aloe
+aloft
+aloha
+alone
+amend
+amino
+ample
+amuse
+angel
+anger
+angle
+ankle
+apple
+april
+apron
+aqua
+area
+arena
+argue
+arise
+armed
+armor
+army
+aroma
+array
+arson
+art
+ashen
+ashes
+atlas
+atom
+attic
+audio
+avert
+avoid
+awake
+award
+awoke
+axis
+bacon
+badge
+bagel
+baggy
+baked
+baker
+balmy
+banjo
+barge
+barn
+bash
+basil
+bask
+batch
+bath
+baton
+bats
+blade
+blank
+blast
+blaze
+bleak
+blend
+bless
+blimp
+blink
+bloat
+blob
+blog
+blot
+blunt
+blurt
+blush
+boast
+boat
+body
+boil
+bok
+bolt
+boned
+boney
+bonus
+bony
+book
+booth
+boots
+boss
+botch
+both
+boxer
+breed
+bribe
+brick
+bride
+brim
+bring
+brink
+brisk
+broad
+broil
+broke
+brook
+broom
+brush
+buck
+bud
+buggy
+bulge
+bulk
+bully
+bunch
+bunny
+bunt
+bush
+bust
+busy
+buzz
+cable
+cache
+cadet
+cage
+cake
+calm
+cameo
+canal
+candy
+cane
+canon
+cape
+card
+cargo
+carol
+carry
+carve
+case
+cash
+cause
+cedar
+chain
+chair
+chant
+chaos
+charm
+chase
+cheek
+cheer
+chef
+chess
+chest
+chew
+chief
+chili
+chill
+chip
+chomp
+chop
+chow
+chuck
+chump
+chunk
+churn
+chute
+cider
+cinch
+city
+civic
+civil
+clad
+claim
+clamp
+clap
+clash
+clasp
+class
+claw
+clay
+clean
+clear
+cleat
+cleft
+clerk
+click
+cling
+clink
+clip
+cloak
+clock
+clone
+cloth
+cloud
+clump
+coach
+coast
+coat
+cod
+coil
+coke
+cola
+cold
+colt
+coma
+come
+comic
+comma
+cone
+cope
+copy
+coral
+cork
+cost
+cot
+couch
+cough
+cover
+cozy
+craft
+cramp
+crane
+crank
+crate
+crave
+crawl
+crazy
+creme
+crepe
+crept
+crib
+cried
+crisp
+crook
+crop
+cross
+crowd
+crown
+crumb
+crush
+crust
+cub
+cult
+cupid
+cure
+curl
+curry
+curse
+curve
+curvy
+cushy
+cut
+cycle
+dab
+dad
+daily
+dairy
+daisy
+dance
+dandy
+darn
+dart
+dash
+data
+date
+dawn
+deaf
+deal
+dean
+debit
+debt
+debug
+decaf
+decal
+decay
+deck
+decor
+decoy
+deed
+delay
+denim
+dense
+dent
+depth
+derby
+desk
+dial
+diary
+dice
+dig
+dill
+dime
+dimly
+diner
+dingy
+disco
+dish
+disk
+ditch
+ditzy
+dizzy
+dock
+dodge
+doing
+doll
+dome
+donor
+donut
+dose
+dot
+dove
+down
+dowry
+doze
+drab
+drama
+drank
+draw
+dress
+dried
+drift
+drill
+drive
+drone
+droop
+drove
+drown
+drum
+dry
+duck
+duct
+dude
+dug
+duke
+duo
+dusk
+dust
+duty
+dwarf
+dwell
+eagle
+early
+earth
+easel
+east
+eaten
+eats
+ebay
+ebony
+ebook
+echo
+edge
+eel
+eject
+elbow
+elder
+elf
+elk
+elm
+elope
+elude
+elves
+email
+emit
+empty
+emu
+enter
+entry
+envoy
+equal
+erase
+error
+erupt
+essay
+etch
+evade
+even
+evict
+evil
+evoke
+exact
+exit
+fable
+faced
+fact
+fade
+fall
+false
+fancy
+fang
+fax
+feast
+feed
+femur
+fence
+fend
+ferry
+fetal
+fetch
+fever
+fiber
+fifth
+fifty
+film
+filth
+final
+finch
+fit
+five
+flag
+flaky
+flame
+flap
+flask
+fled
+flick
+fling
+flint
+flip
+flirt
+float
+flock
+flop
+floss
+flyer
+foam
+foe
+fog
+foil
+folic
+folk
+food
+fool
+found
+fox
+foyer
+frail
+frame
+fray
+fresh
+fried
+frill
+frisk
+from
+front
+frost
+froth
+frown
+froze
+fruit
+gag
+gains
+gala
+game
+gap
+gas
+gave
+gear
+gecko
+geek
+gem
+genre
+gift
+gig
+gills
+given
+giver
+glad
+glass
+glide
+gloss
+glove
+glow
+glue
+goal
+going
+golf
+gong
+good
+gooey
+goofy
+gore
+gown
+grab
+grain
+grant
+grape
+graph
+grasp
+grass
+grave
+gravy
+gray
+green
+greet
+grew
+grid
+grief
+grill
+grip
+grit
+groom
+grope
+growl
+grub
+grunt
+guide
+gulf
+gulp
+gummy
+guru
+gush
+gut
+guy
+habit
+half
+halo
+halt
+happy
+harm
+hash
+hasty
+hatch
+hate
+haven
+hazel
+hazy
+heap
+heat
+heave
+hedge
+hefty
+help
+herbs
+hers
+hub
+hug
+hula
+hull
+human
+humid
+hump
+hung
+hunk
+hunt
+hurry
+hurt
+hush
+hut
+ice
+icing
+icon
+icy
+igloo
+image
+ion
+iron
+islam
+issue
+item
+ivory
+ivy
+jab
+jam
+jaws
+jazz
+jeep
+jelly
+jet
+jiffy
+job
+jog
+jolly
+jolt
+jot
+joy
+judge
+juice
+juicy
+july
+jumbo
+jump
+junky
+juror
+jury
+keep
+keg
+kept
+kick
+kilt
+king
+kite
+kitty
+kiwi
+knee
+knelt
+koala
+kung
+ladle
+lady
+lair
+lake
+lance
+land
+lapel
+large
+lash
+lasso
+last
+latch
+late
+lazy
+left
+legal
+lemon
+lend
+lens
+lent
+level
+lever
+lid
+life
+lift
+lilac
+lily
+limb
+limes
+line
+lint
+lion
+lip
+list
+lived
+liver
+lunar
+lunch
+lung
+lurch
+lure
+lurk
+lying
+lyric
+mace
+maker
+malt
+mama
+mango
+manor
+many
+map
+march
+mardi
+marry
+mash
+match
+mate
+math
+moan
+mocha
+moist
+mold
+mom
+moody
+mop
+morse
+most
+motor
+motto
+mount
+mouse
+mousy
+mouth
+move
+movie
+mower
+mud
+mug
+mulch
+mule
+mull
+mumbo
+mummy
+mural
+muse
+music
+musky
+mute
+nacho
+nag
+nail
+name
+nanny
+nap
+navy
+near
+neat
+neon
+nerd
+nest
+net
+next
+niece
+ninth
+nutty
+oak
+oasis
+oat
+ocean
+oil
+old
+olive
+omen
+onion
+only
+ooze
+opal
+open
+opera
+opt
+otter
+ouch
+ounce
+outer
+oval
+oven
+owl
+ozone
+pace
+pagan
+pager
+palm
+panda
+panic
+pants
+panty
+paper
+park
+party
+pasta
+patch
+path
+patio
+payer
+pecan
+penny
+pep
+perch
+perky
+perm
+pest
+petal
+petri
+petty
+photo
+plank
+plant
+plaza
+plead
+plot
+plow
+pluck
+plug
+plus
+poach
+pod
+poem
+poet
+pogo
+point
+poise
+poker
+polar
+polio
+polka
+polo
+pond
+pony
+poppy
+pork
+poser
+pouch
+pound
+pout
+power
+prank
+press
+print
+prior
+prism
+prize
+probe
+prong
+proof
+props
+prude
+prune
+pry
+pug
+pull
+pulp
+pulse
+puma
+punch
+punk
+pupil
+puppy
+purr
+purse
+push
+putt
+quack
+quake
+query
+quiet
+quill
+quilt
+quit
+quota
+quote
+rabid
+race
+rack
+radar
+radio
+raft
+rage
+raid
+rail
+rake
+rally
+ramp
+ranch
+range
+rank
+rant
+rash
+raven
+reach
+react
+ream
+rebel
+recap
+relax
+relay
+relic
+remix
+repay
+repel
+reply
+rerun
+reset
+rhyme
+rice
+rich
+ride
+rigid
+rigor
+rinse
+riot
+ripen
+rise
+risk
+ritzy
+rival
+river
+roast
+robe
+robin
+rock
+rogue
+roman
+romp
+rope
+rover
+royal
+ruby
+rug
+ruin
+rule
+runny
+rush
+rust
+rut
+sadly
+sage
+said
+saint
+salad
+salon
+salsa
+salt
+same
+sandy
+santa
+satin
+sauna
+saved
+savor
+sax
+say
+scale
+scam
+scan
+scare
+scarf
+scary
+scoff
+scold
+scoop
+scoot
+scope
+score
+scorn
+scout
+scowl
+scrap
+scrub
+scuba
+scuff
+sect
+sedan
+self
+send
+sepia
+serve
+set
+seven
+shack
+shade
+shady
+shaft
+shaky
+sham
+shape
+share
+sharp
+shed
+sheep
+sheet
+shelf
+shell
+shine
+shiny
+ship
+shirt
+shock
+shop
+shore
+shout
+shove
+shown
+showy
+shred
+shrug
+shun
+shush
+shut
+shy
+sift
+silk
+silly
+silo
+sip
+siren
+sixth
+size
+skate
+skew
+skid
+skier
+skies
+skip
+skirt
+skit
+sky
+slab
+slack
+slain
+slam
+slang
+slash
+slate
+slaw
+sled
+sleek
+sleep
+sleet
+slept
+slice
+slick
+slimy
+sling
+slip
+slit
+slob
+slot
+slug
+slum
+slurp
+slush
+small
+smash
+smell
+smile
+smirk
+smog
+snack
+snap
+snare
+snarl
+sneak
+sneer
+sniff
+snore
+snort
+snout
+snowy
+snub
+snuff
+speak
+speed
+spend
+spent
+spew
+spied
+spill
+spiny
+spoil
+spoke
+spoof
+spool
+spoon
+sport
+spot
+spout
+spray
+spree
+spur
+squad
+squat
+squid
+stack
+staff
+stage
+stain
+stall
+stamp
+stand
+stank
+stark
+start
+stash
+state
+stays
+steam
+steep
+stem
+step
+stew
+stick
+sting
+stir
+stock
+stole
+stomp
+stony
+stood
+stool
+stoop
+stop
+storm
+stout
+stove
+straw
+stray
+strut
+stuck
+stud
+stuff
+stump
+stung
+stunt
+suds
+sugar
+sulk
+surf
+sushi
+swab
+swan
+swarm
+sway
+swear
+sweat
+sweep
+swell
+swept
+swim
+swing
+swipe
+swirl
+swoop
+swore
+syrup
+tacky
+taco
+tag
+take
+tall
+talon
+tamer
+tank
+taper
+taps
+tarot
+tart
+task
+taste
+tasty
+taunt
+thank
+thaw
+theft
+theme
+thigh
+thing
+think
+thong
+thorn
+those
+throb
+thud
+thumb
+thump
+thus
+tiara
+tidal
+tidy
+tiger
+tile
+tilt
+tint
+tiny
+trace
+track
+trade
+train
+trait
+trap
+trash
+tray
+treat
+tree
+trek
+trend
+trial
+tribe
+trick
+trio
+trout
+truce
+truck
+trump
+trunk
+try
+tug
+tulip
+tummy
+turf
+tusk
+tutor
+tutu
+tux
+tweak
+tweet
+twice
+twine
+twins
+twirl
+twist
+uncle
+uncut
+undo
+unify
+union
+unit
+untie
+upon
+upper
+urban
+used
+user
+usher
+utter
+value
+vapor
+vegan
+venue
+verse
+vest
+veto
+vice
+video
+view
+viral
+virus
+visa
+visor
+vixen
+vocal
+voice
+void
+volt
+voter
+vowel
+wad
+wafer
+wager
+wages
+wagon
+wake
+walk
+wand
+wasp
+watch
+water
+wavy
+wheat
+whiff
+whole
+whoop
+wick
+widen
+widow
+width
+wife
+wifi
+wilt
+wimp
+wind
+wing
+wink
+wipe
+wired
+wiry
+wise
+wish
+wispy
+wok
+wolf
+womb
+wool
+woozy
+word
+work
+worry
+wound
+woven
+wrath
+wreck
+wrist
+xerox
+yahoo
+yam
+yard
+year
+yeast
+yelp
+yield
+yodel
+yoga
+yoyo
+yummy
+zebra
+zero
+zesty
+zippy
+zone
+zoom
diff --git a/tests/e2e/guided.py b/tests/e2e/guided.py
new file mode 100644
index 0000000..56bcf64
--- /dev/null
+++ b/tests/e2e/guided.py
@@ -0,0 +1,158 @@
+"""The guided setup, driven through a pseudo-terminal like a person would: start a team on one 'machine', join it
+on another with the four-word code.
+
+ cargo build && python3 tests/e2e/guided.py
+
+Uses throwaway homes (agent configs are edited there, not yours) and answers "no" to the background service.
+"""
+import os, pty, re, select, subprocess, tempfile, time
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+BIN = os.path.join(ROOT, "target", "debug", "comms")
+D = tempfile.mkdtemp(prefix="comms-guided-")
+ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b[()][A-Z0-9]|\r")
+DOWN, ENTER = "\x1b[B", "\r"
+results = []
+
+
+def check(name, ok, detail=""):
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'}: {name}" + ("" if ok else f"\n {detail[-1500:]}"))
+
+
+def env(who):
+ home = os.path.join(D, who, "home")
+ os.makedirs(os.path.join(home, ".codex"), exist_ok=True) # a "Codex" to set up
+ e = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE")}
+ e.update(HOME=home, COMMS_HOME=os.path.join(D, who, "comms"), COMMS_MACHINE=who + "-box", COMMS_NO_MDNS="1",
+ COMMS_CLAUDE_BIN="/nonexistent", TERM="xterm-256color")
+ return e
+
+
+class Term:
+ def __init__(self, args, env):
+ self.pid, self.fd = pty.fork()
+ if self.pid == 0:
+ os.execve(BIN, [BIN, *args], env)
+ self.buf = ""
+
+ def expect(self, pattern, timeout=60):
+ end = time.time() + timeout
+ while time.time() < end:
+ m = re.search(pattern, self.buf)
+ if m:
+ self.seen = self.buf[: m.end()]
+ self.buf = self.buf[m.end():]
+ return m
+ r, _, _ = select.select([self.fd], [], [], 0.2)
+ if r:
+ try:
+ self.buf += ANSI.sub("", os.read(self.fd, 65536).decode(errors="replace"))
+ except OSError:
+ break
+ raise AssertionError(f"never saw {pattern!r}; screen so far:\n{self.buf[-1500:]}")
+
+ def send(self, keys, pause=0.3):
+ time.sleep(pause)
+ os.write(self.fd, keys.encode())
+
+ def wait(self):
+ try:
+ self.expect(r"\Z(?!x)", timeout=5) # drain
+ except AssertionError:
+ pass
+ return os.waitpid(self.pid, 0)[1]
+
+
+def stop(who):
+ subprocess.run([BIN, "stop"], env=env(who), capture_output=True)
+
+
+code = None
+try:
+ t = Term([], env("tal"))
+ t.expect(r"What should teammates call you\?")
+ t.send("tal" + ENTER)
+ t.expect(r"Start a new team, or join one\?")
+ t.send(DOWN + ENTER)
+ t.expect(r"Name your team")
+ t.send("vibes" + ENTER)
+ t.expect(r"Created team vibes\. You are tal on tal-box\.")
+ t.expect(r"Which agents should be on comms\?")
+ t.expect(r"Codex")
+ t.send(ENTER)
+ t.expect(r"Keep comms running in the background")
+ t.send("n")
+ t.expect(r"When a teammate's agent messages one of yours")
+ t.send(ENTER)
+ t.expect(r"full working directories")
+ t.send("n")
+ t.expect(r"Codex: updated")
+ t.expect(r"Invite a teammate now\?")
+ t.send("y")
+ m = t.expect(r"Invite code: ([a-z]+(?:-[a-z]+){3})")
+ code = m.group(1)
+ t.expect(r"All set")
+ box = re.sub(r"[\s│]+", " ", t.seen)
+ check("the invite box has the one line to send", f"install.sh | sh -s -- {code}" in box, box)
+ t.wait()
+ check("start a team, set up agents and get an invite code, all by prompts", True)
+ cfg = open(os.path.join(env("tal")["HOME"], ".codex", "config.toml")).read()
+ check("the chosen agent was wired up", "[mcp_servers.comms]" in cfg, cfg)
+except AssertionError as e:
+ check("start a team by prompts", False, str(e))
+
+if code:
+ try:
+ t = Term([], env("alice"))
+ t.expect(r"What should teammates call you\?")
+ t.send("alice" + ENTER)
+ t.expect(r"Start a new team, or join one\?")
+ t.send(ENTER) # "Join a team" is first
+ t.expect(r"Invite code")
+ t.send(code.replace("-", " ") + ENTER)
+ t.expect(r"Joined team vibes as alice on alice-box\.", timeout=90)
+ t.expect(r"Which agents should be on comms\?")
+ t.send(ENTER)
+ t.expect(r"Keep comms running in the background")
+ t.send("n")
+ t.expect(r"When a teammate's agent messages one of yours")
+ t.send(DOWN + ENTER) # hold for approval
+ t.expect(r"full working directories")
+ t.send("n")
+ t.expect(r"Your team")
+ t.expect(r"tal\s+tal-box")
+ t.expect(r"All set")
+ t.wait()
+ check("join with the code by prompts", True)
+ cfg = open(os.path.join(env("alice")["COMMS_HOME"], "config.toml")).read()
+ check("the inbound choice was saved", 'default = "hold"' in cfg, cfg)
+ except AssertionError as e:
+ check("join with the code by prompts", False, str(e))
+
+ try:
+ t = Term([], env("alice"))
+ t.expect(r"(tal · tal-box|team vibes)")
+ t.wait()
+ check("`comms` after setup shows the team instead of asking again", True)
+ except AssertionError as e:
+ check("`comms` after setup shows the team", False, str(e))
+
+ t = Term(["join"], env("bob"))
+ try:
+ t.expect(r"What should teammates call you\?")
+ t.send("bob" + ENTER)
+ t.expect(r"Invite code")
+ t.send("not a real code" + ENTER)
+ t.expect(r"four words, like")
+ t.send("\x03") # Ctrl-C
+ t.expect(r"Stopped")
+ check("a bad code is caught at the prompt, and Ctrl-C exits cleanly", True)
+ except AssertionError as e:
+ check("bad code / Ctrl-C", False, str(e))
+ t.wait()
+
+for who in ("tal", "alice", "bob"):
+ stop(who)
+print(f"\n{sum(results)}/{len(results)} guided checks passed (state in {D})")
+raise SystemExit(0 if all(results) else 1)
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index 0193bd5..6ddc96c 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -80,15 +80,20 @@ os.makedirs(os.path.join(D, "work"), exist_ok=True)
out = cli("tal", "init", "vibes", "--as", "tal", "--no-setup")
check("init creates team", "Created team vibes. You are tal on laptop." in out, out)
out = cli("tal", "invite")
+code = re.search(r"Invite code for a teammate: ([a-z]+(?:-[a-z]+){3})", out)
ticket = re.search(r"comms join (comms1\S+)", out)
-check("invite prints a ticket", bool(ticket), out)
-out = cli("alice", "join", ticket.group(1), "--as", "alice", "--no-setup")
-check("join succeeds", "Joined team vibes as alice on desktop." in out, out)
+check("invite prints a four-word code (and a long fallback)", bool(code) and bool(ticket), out)
+out = cli("alice", "join", code.group(1).replace("-", " ").upper(), "--as", "alice", "--no-setup")
+check("join with just the code succeeds", "Joined team vibes as alice on desktop." in out, out)
check("joiner sees tal connected", re.search(r"tal\s+laptop\s+(direct|relay)", out) is not None, out)
out = cli("tal", "team")
check("founder sees alice connected", re.search(r"alice\s+desktop\s+(direct|relay)", out) is not None, out)
out = cli("alice", "join", ticket.group(1), "--as", "bob", "--no-setup")
check("second join is refused (already in a team)", "already in team" in out, out)
+os.makedirs(os.path.join(D, "bob"), exist_ok=True)
+bob = dict(env("alice"), COMMS_HOME=os.path.join(D, "bob"), COMMS_MACHINE="nuc")
+r = subprocess.run([BIN, "join", code.group(1), "--as", "bob", "--no-setup"], env=bob, capture_output=True, text=True, timeout=90)
+check("a used code doesn't work twice", "Joined" not in r.stdout + r.stderr, r.stdout + r.stderr)
# --- sessions on both machines ---
claude = Mcp("tal", "claude-code", strip_claude=False, cwd=ROOT)