Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(network): no letter or reply goes missing, and every computer keeps its own name

leepokaicaae10c0a71c
diff --git a/docs/features/codync-network.md b/docs/features/codync-network.md
index c3e4205d..ea2d8dcc 100644
--- a/docs/features/codync-network.md
+++ b/docs/features/codync-network.md
@@ -21,7 +21,8 @@ codync-host network peers | promote <computer> | remove <computer> [--cascade] |
`create` prints the **recovery code** once: the network's root key, kept on no computer. The connector picks the
fallback when two computers can't connect directly: iroh's public relays (`public`, the default), the user's own
`iroh-relay` (a URL), or none (`private`: same network, Tailscale or a VPN). A computer's name defaults to its host
-name; a taken name gets a number (`laptop-2`).
+name; a taken name gets a number (`laptop-2`), also when two admins admit the same name before their copies meet
+(the later admission gets the number, on every copy).
## Who may do what
@@ -65,8 +66,10 @@ that was off learns of a removal.
from a bot the computer no longer offers (renamed or deleted while it worked).
- Exchange notices carry `botMessage.peerName` ("Reviewer on desk") for the bot on the other computer, whose id
isn't in this computer's bot list; every client shows that name in the row, the pair sheet and its author labels.
-- A letter to a computer that is away waits in the sender's outbox for up to a day. The chain's hop limit counts
- across computers (replies carry it back), and the receiving computer enforces its own budgets:
+- A letter to a computer that is away waits in the sender's outbox for up to a day, and so does one for a computer
+ that has started but not offered its bots yet (it answers *later*; offering them calls everyone back). A reply
+ reaches its request even when the asking bot was renamed or hidden meanwhile. The chain's hop limit counts
+ across computers (replies carry it back, one more handoff each), and the receiving computer enforces its own budgets:
8 handoffs per chain, a burst of 5 messages per pair of agents then one every 2 minutes, the same words twice in
10 minutes refused. A letter that isn't a request (a notice, or a reply nobody waits for after a restart) shows as
a "Note from …" notice in the bot's chat.
@@ -82,6 +85,9 @@ that was off learns of a removal.
- Bots can't reach Claude Code or Codex sessions on another computer through the host (the standalone daemon can).
- The cloud assistant connector ([cloud assistants](cloud-assistants.md)) reaches only the bots of the computer it
talks to, not that computer's network.
+- Each computer's share of the roster is capped (256 entries) and keeps its oldest: an owner or admin that has
+ made 256 admissions, promotions and removals can't make more. Hellos sending changes since the last one, instead
+ of the whole roster, would lift the cap.
## Code and verification
diff --git a/host/Cargo.lock b/host/Cargo.lock
index 581f3651..23547798 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -770,7 +770,7 @@ dependencies = [
[[package]]
name = "codync-network"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"anyhow",
"base64 0.23.1",
diff --git a/host/crates/network/Cargo.toml b/host/crates/network/Cargo.toml
index 436b1d50..04d67cab 100644
--- a/host/crates/network/Cargo.toml
+++ b/host/crates/network/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "codync-network"
-version = "0.1.0"
+version = "0.1.1"
edition = "2024"
# iroh 1.4 needs 1.91.
rust-version = "1.91"
diff --git a/host/crates/network/src/node/inbound.rs b/host/crates/network/src/node/inbound.rs
index 4b2230bd..230981ac 100644
--- a/host/crates/network/src/node/inbound.rs
+++ b/host/crates/network/src/node/inbound.rs
@@ -12,6 +12,7 @@ use iroh::endpoint::{Connection, RecvStream, SendStream};
use iroh::protocol::{AcceptError, ProtocolHandler};
use std::fmt;
use std::sync::Arc;
+use std::sync::atomic::Ordering;
use std::time::Instant;
/// Letters remembered as taken, for spotting a sender's retry.
@@ -84,12 +85,19 @@ impl Inner {
if let Err(e) = wire::check(&envelope) {
return refuse(e.to_string());
}
+ if !self.ready.load(Ordering::Acquire) {
+ return Response::Later { reason: "this computer is still starting".into() };
+ }
// Without a network, only this computer's own agents write here.
let roster = locked(&self.roster).clone();
let name = |id: &EndpointId| roster.as_ref().map_or_else(|| "local".into(), |r| r.name(id));
let reach = locked(&self.agents).iter().find(|(a, _)| a.id == envelope.to).map(|(_, r)| r.clone());
- let Some(reach) = reach else {
- return refuse(format!("{} has no agent called {}", name(&self.me()), envelope.to));
+ let reach = match reach {
+ Some(reach) => reach,
+ // An answer to an agent that has since been renamed or gone: the app knows its request
+ // by id and still takes it.
+ None if envelope.reply_to.is_some() => Reach::App,
+ None => return refuse(format!("{} has no agent called {}", name(&self.me()), envelope.to)),
};
let key = format!("{peer}:{}", envelope.id);
if locked(&self.taken).contains(&key) {
@@ -103,8 +111,10 @@ impl Inner {
if let Err(reason) = locked(&self.guard).admit(pair.clone(), envelope.hops, said, Instant::now()) {
return refuse(reason);
}
+ let (id, hops) = (envelope.id.clone(), envelope.hops);
match self.hand_over(&reach, envelope.open(name(&peer))).await {
Ok(()) => {
+ self.heard(&id, hops);
let mut taken = locked(&self.taken);
if taken.len() >= TAKEN_MAX {
taken.pop_front();
diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rs
index a5a82989..355d3966 100644
--- a/host/crates/network/src/node/mod.rs
+++ b/host/crates/network/src/node/mod.rs
@@ -15,6 +15,7 @@ use iroh::protocol::Router;
use iroh::{Endpoint, EndpointId, RelayMode, RelayUrl, SecretKey};
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
@@ -26,6 +27,8 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Long enough for the other computer to knock on its agent's harness.
const CALL_TIMEOUT: Duration = Duration::from_secs(20);
const INBOX_SIZE: usize = 256;
+/// Letters whose handoff count a reply may need, newest kept.
+const HEARD_MAX: usize = 1000;
pub struct Node {
inner: Arc<Inner>,
@@ -37,6 +40,10 @@ struct Inner {
dir: PathBuf,
roster: Mutex<Option<Roster>>,
agents: Mutex<Vec<(Agent, Reach)>>,
+ /// The app offered its agents since the node started: until then, letters wait at the sender.
+ ready: AtomicBool,
+ /// The handoff count of letters taken here, by id, so a reply carries the chain on.
+ heard: Mutex<VecDeque<(String, u8)>>,
/// What each other computer offered when it last answered or wrote.
seen: Mutex<HashMap<EndpointId, directory::Seen>>,
invites: Mutex<HashMap<String, Instant>>,
@@ -67,6 +74,8 @@ impl Node {
dir: dir.to_path_buf(),
roster: Mutex::new(Roster::load(dir)?),
agents: Mutex::default(),
+ ready: AtomicBool::new(false),
+ heard: Mutex::default(),
seen: Mutex::default(),
invites: Mutex::default(),
guard: Mutex::default(),
@@ -188,8 +197,13 @@ impl Node {
/// The agents this computer offers, and how each is reached. Others see them the next time
/// they ask.
+ /// What this computer offers. The first call opens it to letters, and the others hear at once,
+ /// so what waited for it while it started comes now.
pub fn set_agents(&self, agents: impl IntoIterator<Item = (Agent, Reach)>) {
*locked(&self.inner.agents) = agents.into_iter().collect();
+ if !self.inner.ready.swap(true, Ordering::AcqRel) {
+ self.inner.clone().hello_all();
+ }
}
/// The command agents the network knocks on run to reply (default `codync-network`).
@@ -226,6 +240,13 @@ impl Node {
if letter.reply_to.is_none() && !self.inner.offered().iter().any(|a| a.id == letter.from) {
bail!("{} isn't one of this computer's agents", letter.from);
}
+ // A reply carries on the chain of the letter it answers (one more handoff).
+ let mut letter = letter;
+ if letter.hops == 0
+ && let Some(hops) = letter.reply_to.as_deref().and_then(|id| self.inner.hops_of(id))
+ {
+ letter.hops = hops.saturating_add(1);
+ }
guard::check_hops(letter.hops).map_err(anyhow::Error::msg)?;
let roster = locked(&self.inner.roster).clone();
let id = match &roster {
@@ -246,6 +267,12 @@ impl Node {
match answer {
Ok(Response::Stored) => Ok(Sent::Delivered),
Ok(Response::Refused { reason }) => bail!("{} refused it: {reason}", name(&id)),
+ Ok(Response::Later { reason }) if local => bail!("{reason}"),
+ Ok(Response::Later { reason }) => {
+ tracing::info!(to = %name(&id), reason, "queued for a computer that is starting");
+ self.inner.queue(id, envelope)?;
+ Ok(Sent::Queued)
+ }
Ok(_) => bail!("{} gave an unexpected answer", name(&id)),
Err(e) => {
tracing::info!(to = %name(&id), error = format!("{e:#}"), "queued for a computer that is away");
@@ -269,6 +296,18 @@ impl Inner {
self.endpoint.id()
}
+ fn hops_of(&self, letter: &str) -> Option<u8> {
+ locked(&self.heard).iter().rev().find(|(id, _)| id == letter).map(|(_, hops)| *hops)
+ }
+
+ fn heard(&self, letter: &str, hops: u8) {
+ let mut heard = locked(&self.heard);
+ if heard.len() >= HEARD_MAX {
+ heard.pop_front();
+ }
+ heard.push_back((letter.to_owned(), hops));
+ }
+
fn offered(&self) -> Vec<Agent> {
locked(&self.agents).iter().map(|(agent, _)| agent.clone()).collect()
}
diff --git a/host/crates/network/src/node/outbox.rs b/host/crates/network/src/node/outbox.rs
index 3c3d9e4d..954493e9 100644
--- a/host/crates/network/src/node/outbox.rs
+++ b/host/crates/network/src/node/outbox.rs
@@ -48,13 +48,14 @@ impl Inner {
// ponytail: dropped with a log line; a delivery-report channel when the host needs it.
tracing::warn!(id = %q.envelope.id, reason, "a waiting letter was refused");
}
- Ok(_) => {}
- Err(_) => {
+ // Still starting there, or away again: it waits for the next answer.
+ Ok(Response::Later { .. }) | Err(_) => {
let mut outbox = locked(&self.outbox);
outbox.push(q);
outbox.extend(left);
return;
}
+ Ok(_) => {}
}
}
});
diff --git a/host/crates/network/src/roster.rs b/host/crates/network/src/roster.rs
index 63862f4c..0000b6ad 100644
--- a/host/crates/network/src/roster.rs
+++ b/host/crates/network/src/roster.rs
@@ -306,15 +306,19 @@ impl Roster {
let voided = |by: &EndpointId| removed.get(by).is_some_and(|&(_, cascade)| cascade);
let may_admit = |s: &Signed| !voided(&s.by) && (top(&s.by, s.at) || admin_at(&s.by, s.at));
- let mut admitted: BTreeMap<EndpointId, String> = BTreeMap::new();
- for (_, id, name) in &owners {
- admitted.entry(*id).or_insert_with(|| name.clone());
+ // Each computer with the time it got in and the name it got in with.
+ let mut admitted: BTreeMap<EndpointId, (u64, String)> = BTreeMap::new();
+ for (at, id, name) in &owners {
+ admitted.entry(*id).or_insert_with(|| (*at, name.clone()));
}
for s in &log {
if let Change::Admit { id, name } = &s.change
&& may_admit(s)
{
- admitted.entry(*id).or_insert_with(|| name.clone());
+ let first = admitted.entry(*id).or_insert_with(|| (s.at, name.clone()));
+ if s.at < first.0 {
+ *first = (s.at, name.clone());
+ }
}
}
let addrs = newest_locations(&self.log);
@@ -324,9 +328,9 @@ impl Roster {
deciders: tops.chain(promoted.keys().copied()).collect(),
};
self.removed = removed.keys().copied().collect();
- self.members = admitted
+ admitted.retain(|id, _| !self.removed.contains(id));
+ self.members = distinct_names(admitted)
.into_iter()
- .filter(|(id, _)| !self.removed.contains(id))
.map(|(id, name)| {
let role = if Some(id) == owner {
Role::Owner
@@ -391,6 +395,27 @@ fn newest_locations(log: &BTreeSet<Signed>) -> BTreeMap<EndpointId, (&Signed, &E
newest
}
+/// Names every computer uniquely. Two admins can admit a `laptop` each before their copies meet:
+/// the one admitted later (by time, then id) gets the first free number, the same on every copy.
+fn distinct_names(admitted: BTreeMap<EndpointId, (u64, String)>) -> BTreeMap<EndpointId, String> {
+ let mut order: Vec<(u64, EndpointId, String)> =
+ admitted.into_iter().map(|(id, (at, name))| (at, id, name)).collect();
+ order.sort();
+ let mut taken = BTreeSet::new();
+ let mut names = BTreeMap::new();
+ for (_, id, name) in order {
+ let mut unique = name.clone();
+ for n in 2.. {
+ if taken.insert(unique.to_lowercase()) {
+ break;
+ }
+ unique = format!("{name}-{n}");
+ }
+ names.insert(id, unique);
+ }
+ names
+}
+
/// Notes that `id` was removed at `at`: the earliest removal counts, and a cascade from any.
fn note_removal(removed: &mut BTreeMap<EndpointId, (u64, bool)>, id: EndpointId, at: u64, cascade: bool) {
let e = removed.entry(id).or_insert((at, cascade));
diff --git a/host/crates/network/src/roster/tests.rs b/host/crates/network/src/roster/tests.rs
index 014c4b0e..1eb1414c 100644
--- a/host/crates/network/src/roster/tests.rs
+++ b/host/crates/network/src/roster/tests.rs
@@ -161,3 +161,19 @@ fn a_stolen_owner_cannot_undo_its_replacement() {
retired.merge(&forge(&retired));
assert_eq!(retired.role(&laptop.public()), Some(Role::Owner));
}
+
+#[test]
+fn two_admins_naming_a_laptop_at_once_still_get_distinct_names() {
+ let (desk, server, laptop, other) = (key(), key(), key(), key());
+ let (mut a, _root) = Roster::create(&desk, "desk".into(), addr(&desk), 1);
+ a.sign(&desk, 2, Change::Admit { id: server.public(), name: "server".into() }).unwrap();
+ a.sign(&desk, 3, Change::Promote { id: server.public() }).unwrap();
+ let mut b = a.clone();
+ // Each admits a "laptop" before hearing of the other's.
+ a.sign(&desk, 4, Change::Admit { id: laptop.public(), name: "laptop".into() }).unwrap();
+ b.sign(&server, 5, Change::Admit { id: other.public(), name: "Laptop".into() }).unwrap();
+ assert!(a.merge(&b) && b.merge(&a));
+ assert_eq!(a.members(), b.members());
+ assert_eq!((a.name(&laptop.public()), a.name(&other.public())), ("laptop".into(), "Laptop-2".into()));
+ assert_eq!(a.find("laptop-2"), Some(other.public()));
+}
diff --git a/host/crates/network/src/wire.rs b/host/crates/network/src/wire.rs
index 7fe83bd1..ea7aba51 100644
--- a/host/crates/network/src/wire.rs
+++ b/host/crates/network/src/wire.rs
@@ -73,10 +73,22 @@ pub enum Request {
#[derive(Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Response {
- Welcome { roster: Roster },
- Hello { roster: Roster, agents: Vec<Agent> },
+ Welcome {
+ roster: Roster,
+ },
+ Hello {
+ roster: Roster,
+ agents: Vec<Agent>,
+ },
Stored,
- Refused { reason: String },
+ Refused {
+ reason: String,
+ },
+ /// Not yet: the receiving computer hasn't offered its agents since it started. The sender
+ /// keeps the letter and tries again (an older sender, which can't read this, does the same).
+ Later {
+ reason: String,
+ },
}
/// An invite: where to find the inviting computer and the one-time secret it waits for.
diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rs
index b96d234a..46918a3a 100644
--- a/host/crates/network/tests/two_computers.rs
+++ b/host/crates/network/tests/two_computers.rs
@@ -182,3 +182,53 @@ async fn without_a_network_agents_on_one_computer_still_reach_each_other() {
assert_eq!(next(&mut inbox).await.from.to_string(), "a@local");
let _ = std::fs::remove_dir_all(dir);
}
+
+#[tokio::test]
+async fn a_computer_still_starting_gets_its_letters_once_it_offers_its_agents() {
+ let (desk_dir, laptop_dir) = (temp_dir("desk4"), temp_dir("laptop4"));
+ let (desk, _) = Node::start(&desk_dir, &Connector::Private).await.unwrap();
+ desk.create("desk").unwrap();
+ offer(&desk, "lead");
+ let (laptop, _) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();
+ offer(&laptop, "coder");
+ laptop.join(&desk.invite().unwrap(), "laptop").await.unwrap();
+ laptop.shutdown().await;
+ assert_eq!(desk.send(Letter::new("lead", to("coder@laptop"), "while you were off")).await.unwrap(), Sent::Queued);
+
+ // Back on, but its app hasn't offered the agents yet: the desk's letter waits instead of going.
+ let (laptop, mut inbox) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert!(inbox.try_recv().is_err());
+ offer(&laptop, "coder");
+ assert_eq!(next(&mut inbox).await.body, "while you were off");
+ for dir in [desk_dir, laptop_dir] {
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}
+
+#[tokio::test]
+async fn a_reply_reaches_an_agent_renamed_since_it_asked_and_carries_the_chain_on() {
+ let (desk_dir, laptop_dir) = (temp_dir("desk5"), temp_dir("laptop5"));
+ let (desk, mut desk_inbox) = Node::start(&desk_dir, &Connector::Private).await.unwrap();
+ desk.create("desk").unwrap();
+ offer(&desk, "lead");
+ let (laptop, mut laptop_inbox) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();
+ offer(&laptop, "reviewer");
+ laptop.join(&desk.invite().unwrap(), "laptop").await.unwrap();
+
+ let ask = Letter::new("lead", to("reviewer@laptop"), "review this").hops(3);
+ let asked = ask.id.clone();
+ desk.send(ask).await.unwrap();
+ assert_eq!(next(&mut laptop_inbox).await.hops, 3);
+ // The lead is renamed while the review runs: the desk no longer offers "lead".
+ offer(&desk, "lead-2");
+ laptop.send(Letter::new("reviewer", to("lead@desk"), "looks good").reply_to(asked.clone())).await.unwrap();
+ let reply = next(&mut desk_inbox).await;
+ assert_eq!((reply.reply_to.as_deref(), reply.hops), (Some(asked.as_str()), 4));
+ // A new letter (no reply_to) for an agent that's gone is still refused.
+ let gone = laptop.send(Letter::new("reviewer", to("lead@desk"), "and another thing")).await.unwrap_err();
+ assert!(gone.to_string().contains("no agent called lead"), "{gone}");
+ for dir in [desk_dir, laptop_dir] {
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}