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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): choose which bots the network and cloud assistants reach, and who may write
leepokai63bcd807f4d0
diff --git a/host/crates/network/src/bin/codync-network/main.rs b/host/crates/network/src/bin/codync-network/main.rsindex c16be535..b68f85a7 100644--- a/host/crates/network/src/bin/codync-network/main.rs+++ b/host/crates/network/src/bin/codync-network/main.rs@@ -4,7 +4,7 @@mod control;use anyhow::{Context, Result, anyhow, bail};-use codync_network::{Address, Agent, Connector, Letter, Node, Reach, Sent};+use codync_network::{Access, Address, Agent, Connector, Letter, Node, Reach, Rule, Sent};use serde::{Deserialize, Serialize};use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};@@ -24,11 +24,15 @@ then, from any terminal or agent on this computer:agents this computer's agentspromote <computer> make a computer an admin (owner)remove <computer> [--cascade] take a computer out for good (--cascade: and what it admitted)- recover <code> make this computer the owner with the recovery code";+ recover <code> make this computer the owner with the recovery code+ rules who on the other computers may write to agents here (first match decides)+ rules allow|deny <agent@computer> <agent> [--first] add a rule (* matches any; --first puts it on top)+ rules remove <n> take out rule n";/// The agent a person at this computer's terminal speaks as.const TERMINAL: &str = "terminal";const AGENTS_FILE: &str = "agents.json";+const RULES_FILE: &str = "rules.json";#[derive(Clone, Serialize, Deserialize)]struct LocalAgent {@@ -92,7 +96,8 @@ async fn daemon(dir: &Path, connector: &Connector, args: &[String]) -> Result<()if default_dir().as_deref() == Some(dir) { String::new() } else { format!(" --dir '{}'", dir.display()) };node.set_reply_command(format!("'{}'{dir_flag}", exe.display()));}- let daemon = Arc::new(Daemon { node, dir: dir.to_path_buf(), agents: Mutex::new(load_agents(dir)?) });+ node.set_rules(load(dir, RULES_FILE)?)?;+ let daemon = Arc::new(Daemon { node, dir: dir.to_path_buf(), agents: Mutex::new(load(dir, AGENTS_FILE)?) });daemon.offer();control::serve(dir, daemon.clone())?;println!("{name} is on ({}). Commands work here and from other terminals.", daemon.node.id().fmt_short());@@ -133,6 +138,7 @@ impl Daemon {let notice = take_switch(&mut args, "--notice");let remove = take_switch(&mut args, "--remove");let cascade = take_switch(&mut args, "--cascade");+ let first = take_switch(&mut args, "--first");match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {["invite"] => self.node.invite(),["peers"] => self.peers().await,@@ -169,6 +175,27 @@ impl Daemon {self.node.promote(computer)?;Ok(format!("{computer} is an admin"))}+ ["rules"] => Ok(self.rules_listing()),+ ["rules", "remove", n] => {+ let mut rules = self.node.rules();+ let i = n+ .parse::<usize>()+ .ok()+ .filter(|i| (1..=rules.len()).contains(i))+ .ok_or_else(|| anyhow!("no rule {n}"))?;+ rules.remove(i - 1);+ self.set_rules(rules)+ }+ ["rules", access, from, to] => {+ let rule = Rule::new(access.parse::<Access>()?, from, to)?;+ let mut rules = self.node.rules();+ if first {+ rules.insert(0, rule);+ } else {+ rules.push(rule);+ }+ self.set_rules(rules)+ }["recover", ref code @ ..] if !code.is_empty() => {self.node.recover(&code.join(""))?;Ok("this computer is the owner now; remove the lost one".into())@@ -177,6 +204,21 @@ impl Daemon {}}+ fn set_rules(&self, rules: Vec<Rule>) -> Result<String> {+ codync_network::rules::check_all(&rules)?;+ save(&self.dir, RULES_FILE, &rules)?;+ self.node.set_rules(rules)?;+ Ok(self.rules_listing())+ }++ fn rules_listing(&self) -> String {+ let rules = self.node.rules();+ if rules.is_empty() {+ return "no rules: every computer in the network may write to every agent here".into();+ }+ rules.iter().enumerate().map(|(i, r)| format!("{:>3} {r}", i + 1)).collect::<Vec<_>>().join("\n")+ }+async fn peers(&self) -> Result<String> {let mut out = Vec::new();for p in self.node.peers().await? {@@ -202,7 +244,7 @@ impl Daemon {let mut agents = self.agents.lock().unwrap_or_else(std::sync::PoisonError::into_inner);agents.retain(|a| a.agent.id != id);agents.push(local);- save_agents(&self.dir, &agents)?;+ save(&self.dir, AGENTS_FILE, &agents)?;drop(agents);self.offer();Ok(format!("{id} is on the network"))@@ -215,7 +257,7 @@ impl Daemon {if agents.len() == before {bail!("no agent called {id} on this computer");}- save_agents(&self.dir, &agents)?;+ save(&self.dir, AGENTS_FILE, &agents)?;drop(agents);self.offer();Ok(format!("{id} is off the network"))@@ -250,16 +292,17 @@ fn default_dir() -> Option<PathBuf> {std::env::home_dir().map(|h| h.join(".codync-network"))}-fn load_agents(dir: &Path) -> Result<Vec<LocalAgent>> {- match std::fs::read(dir.join(AGENTS_FILE)) {- Ok(bytes) => serde_json::from_slice(&bytes).context("agents.json is damaged"),+/// A list kept in the node's folder (`agents.json`, `rules.json`); none yet is empty.+fn load<T: serde::de::DeserializeOwned>(dir: &Path, file: &str) -> Result<Vec<T>> {+ match std::fs::read(dir.join(file)) {+ Ok(bytes) => serde_json::from_slice(&bytes).with_context(|| format!("{file} is damaged")),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),- Err(e) => Err(e).context("couldn't read agents.json"),+ Err(e) => Err(e).with_context(|| format!("couldn't read {file}")),}}-fn save_agents(dir: &Path, agents: &[LocalAgent]) -> Result<()> {- std::fs::write(dir.join(AGENTS_FILE), serde_json::to_vec_pretty(agents)?).context("couldn't save agents.json")+fn save<T: Serialize>(dir: &Path, file: &str, items: &[T]) -> Result<()> {+ std::fs::write(dir.join(file), serde_json::to_vec_pretty(items)?).with_context(|| format!("couldn't save {file}"))}fn take_flag(args: &mut Vec<String>, flag: &str) -> Result<Option<String>> {@@ -277,3 +320,19 @@ fn take_switch(args: &mut Vec<String>, switch: &str) -> bool {args.retain(|a| a != switch);args.len() != before}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rules_are_kept_beside_the_agents() {+ let dir = std::env::temp_dir().join(format!("codync-network-rules-{}", std::process::id()));+ std::fs::create_dir_all(&dir).expect("a temp folder");+ assert_eq!(load::<Rule>(&dir, RULES_FILE).expect("none yet"), []);+ let rules = vec![Rule::new(Access::Deny, "*@server", "*").expect("a rule")];+ save(&dir, RULES_FILE, &rules).expect("saved");+ assert_eq!(load::<Rule>(&dir, RULES_FILE).expect("read back"), rules);+ let _ = std::fs::remove_dir_all(dir);+ }+}diff --git a/host/crates/network/src/lib.rs b/host/crates/network/src/lib.rsindex ec142010..227cb98d 100644--- a/host/crates/network/src/lib.rs+++ b/host/crates/network/src/lib.rs@@ -15,16 +15,20 @@//! the network knocks on Claude Code sessions and Codex threads itself.//! - **Budgets** ([`guard`]): nothing is sent unless an agent sends a letter or someone asks who//! is around, and the receiving computer refuses long chains, bursts and repeats.+//! - **Rules** ([`rules`]): the receiving computer decides which agents elsewhere may write to+//! which of its own; with none, every member may.pub mod guard;mod node;mod reach;mod roster;+pub mod rules;mod types;mod wire;pub use node::{INVITE_FOR, Node};pub use reach::Reach;pub use roster::Role;+pub use rules::{Access, Rule};pub use types::{Address, Connector, Letter, Message, Peer, Sent};pub use wire::{Agent, MAX_BODY};diff --git a/host/crates/network/src/node/inbound.rs b/host/crates/network/src/node/inbound.rsindex 9b6bb268..541ebad3 100644--- a/host/crates/network/src/node/inbound.rs+++ b/host/crates/network/src/node/inbound.rs@@ -4,6 +4,7 @@ use super::{Inner, check_name, locked};use crate::guard::digest;use crate::reach::Reach;use crate::roster::Change;+use crate::rules;use crate::types::Message;use crate::wire::{self, Envelope, Request, Response};use anyhow::{Result, anyhow, bail};@@ -91,6 +92,13 @@ impl Inner {// 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));+ // This computer's rules, for letters from the others that don't answer one of its own.+ if peer != self.me()+ && !self.answers(peer, envelope.reply_to.as_deref())+ && !rules::allows(&locked(&self.rules), &name(&peer), &envelope.from, &envelope.to)+ {+ return refuse(format!("{} doesn't take messages from {}@{}", envelope.to, envelope.from, name(&peer)));+ }let reach = locked(&self.agents).iter().find(|(a, _)| a.id == envelope.to).map(|(_, r)| r.clone());let reach = match reach {Some(reach) => reach,diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rsindex 16935996..d11f367a 100644--- a/host/crates/network/src/node/mod.rs+++ b/host/crates/network/src/node/mod.rs@@ -7,6 +7,7 @@ mod outbox;use crate::guard::{self, Guard};use crate::reach::{Held, Reach};use crate::roster::{self, Change, Role, Roster};+use crate::rules::{self, Rule};use crate::types::{Address, Connector, Letter, Message, Peer, Sent};use crate::wire::{self, ALPN, Agent, Request, Response, Ticket};use anyhow::{Context, Result, anyhow, bail};@@ -52,6 +53,10 @@ struct Inner {held: Mutex<Held>,/// Letters already taken, so a sender's retry isn't delivered twice.taken: Mutex<VecDeque<String>>,+ /// Who may write to this computer's agents (`rules`).+ rules: Mutex<Vec<Rule>>,+ /// Letters this computer sent, newest kept, and to whom: an answer to one passes the rules.+ asked: Mutex<VecDeque<(String, EndpointId)>>,outbox: Mutex<Vec<outbox::Queued>>,inbox: mpsc::Sender<Message>,/// The command an agent the network knocks on runs to answer.@@ -85,6 +90,8 @@ impl Node {guard: Mutex::default(),held: Mutex::default(),taken: Mutex::default(),+ rules: Mutex::default(),+ asked: Mutex::default(),outbox: Mutex::default(),inbox: tx,reply_command: Mutex::new("codync-network".into()),@@ -216,6 +223,19 @@ impl Node {}}+ /// Who on the other computers may write to this computer's agents, the first match deciding.+ /// Answers to this computer's own letters always pass, so a rule added while a request runs+ /// doesn't strand it.+ pub fn set_rules(&self, rules: Vec<Rule>) -> Result<()> {+ rules::check_all(&rules)?;+ *locked(&self.inner.rules) = rules;+ Ok(())+ }++ pub fn rules(&self) -> Vec<Rule> {+ locked(&self.inner.rules).clone()+ }+/// The command agents the network knocks on run to reply (default `codync-network`).pub fn set_reply_command(&self, command: impl Into<String>) {*locked(&self.inner.reply_command) = command.into();@@ -275,6 +295,9 @@ impl Node {let local = id == self.id();let envelope = letter.seal(wire::now_ms());wire::check(&envelope)?;+ if !local {+ self.inner.asked(&envelope.id, id);+ }let name = |id: &EndpointId| roster.as_ref().map_or_else(|| "this computer".into(), |r| r.name(id));let answer = if local {Ok(self.inner.take(id, envelope.clone()).await)@@ -313,6 +336,19 @@ impl Inner {self.endpoint.id()}+ fn asked(&self, letter: &str, to: EndpointId) {+ let mut asked = locked(&self.asked);+ if asked.len() >= HEARD_MAX {+ asked.pop_front();+ }+ asked.push_back((letter.to_owned(), to));+ }++ /// Whether a letter from `peer` answers one this computer sent it.+ pub(super) fn answers(&self, peer: EndpointId, reply_to: Option<&str>) -> bool {+ reply_to.is_some_and(|id| locked(&self.asked).iter().any(|(sent, to)| sent == id && *to == peer))+ }+fn hops_of(&self, letter: &str) -> Option<u8> {locked(&self.heard).iter().rev().find(|(id, _)| id == letter).map(|(_, hops)| *hops)}diff --git a/host/crates/network/src/rules.rs b/host/crates/network/src/rules.rsnew file mode 100644index 00000000..1f5b50b7--- /dev/null+++ b/host/crates/network/src/rules.rs@@ -0,0 +1,133 @@+//! Who on the other computers may write to this computer's agents. The receiving computer checks+//! its own rules before it takes a letter, so none depends on the sender's goodwill: the first rule+//! that matches decides, and with no rules every member may write (the default).++use anyhow::{Result, bail};+use serde::{Deserialize, Serialize};+use std::fmt;+use std::str::FromStr;++/// Matches any computer or agent.+pub const ANY: &str = "*";+/// Enough for any one person's computers, and few enough to check on every letter.+pub const MAX_RULES: usize = 100;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Access {+ Allow,+ Deny,+}++/// `deny *@server → *`: letters from `from_agent` on `from_computer` to `to_agent` here.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Rule {+ /// A computer in the network, or `*`.+ pub from_computer: String,+ /// An agent on that computer, or `*`.+ pub from_agent: String,+ /// One of this computer's agents, or `*`.+ pub to_agent: String,+ pub access: Access,+}++impl Rule {+ /// `from` is `agent@computer`, either side `*`, or `*` alone for anyone.+ pub fn new(access: Access, from: &str, to: &str) -> Result<Self> {+ let (from_agent, from_computer) = match from.trim() {+ ANY => (ANY, ANY),+ from => from.rsplit_once('@').ok_or_else(|| anyhow::anyhow!("from is agent@computer, or *"))?,+ };+ let rule = Self {+ from_computer: from_computer.trim().into(),+ from_agent: from_agent.trim().into(),+ to_agent: to.trim().into(),+ access,+ };+ rule.check()?;+ Ok(rule)+ }++ fn check(&self) -> Result<()> {+ for part in [&self.from_computer, &self.from_agent, &self.to_agent] {+ if part.is_empty() || part.len() > 64 || part.contains(char::is_whitespace) {+ bail!("each part of a rule is a name or *, without spaces");+ }+ }+ Ok(())+ }++ fn matches(&self, computer: &str, agent: &str, to: &str) -> bool {+ let fits = |pattern: &str, name: &str| pattern == ANY || pattern.eq_ignore_ascii_case(name);+ fits(&self.from_computer, computer) && fits(&self.from_agent, agent) && fits(&self.to_agent, to)+ }+}++impl fmt::Display for Rule {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let access = match self.access {+ Access::Allow => "allow",+ Access::Deny => "deny",+ };+ write!(f, "{access} {}@{} → {}", self.from_agent, self.from_computer, self.to_agent)+ }+}++impl FromStr for Access {+ type Err = anyhow::Error;++ fn from_str(s: &str) -> Result<Self> {+ match s {+ "allow" => Ok(Self::Allow),+ "deny" => Ok(Self::Deny),+ _ => bail!("a rule allows or denies"),+ }+ }+}++/// Checks a whole list before it replaces the old one.+pub fn check_all(rules: &[Rule]) -> Result<()> {+ if rules.len() > MAX_RULES {+ bail!("at most {MAX_RULES} rules");+ }+ rules.iter().try_for_each(Rule::check)+}++/// Whether `agent` on `computer` may write to `to` here: the first rule that matches decides.+pub fn allows(rules: &[Rule], computer: &str, agent: &str, to: &str) -> bool {+ rules.iter().find(|r| r.matches(computer, agent, to)).is_none_or(|r| r.access == Access::Allow)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rule(access: Access, from: &str, to: &str) -> Rule {+ Rule::new(access, from, to).expect("a valid rule")+ }++ #[test]+ fn the_first_match_decides_and_no_rules_allow_everyone() {+ assert!(allows(&[], "server", "lead", "reviewer"));+ let rules = [rule(Access::Allow, "lead@server", "reviewer"), rule(Access::Deny, "*@server", "*")];+ assert!(allows(&rules, "server", "lead", "reviewer"));+ assert!(!allows(&rules, "server", "lead", "coder"), "only the reviewer was allowed");+ assert!(!allows(&rules, "Server", "other", "reviewer"), "computer names ignore case");+ assert!(allows(&rules, "laptop", "lead", "coder"), "no rule for the laptop");+ assert!(!allows(&[rule(Access::Deny, "*", "*")], "laptop", "a", "b"));+ }++ #[test]+ fn rules_read_and_show_like_addresses() {+ let r = rule(Access::Deny, "*@server", "*");+ assert_eq!((r.from_agent.as_str(), r.from_computer.as_str()), ("*", "server"));+ assert_eq!(r.to_string(), "deny *@server → *");+ assert!(Rule::new(Access::Allow, "lead", "x").is_err(), "a bare agent needs its computer");+ assert!(Rule::new(Access::Allow, "a b@c", "x").is_err());+ assert!(check_all(&vec![r; MAX_RULES + 1]).is_err());+ let json = serde_json::to_value(rule(Access::Allow, "lead@desk", "reviewer")).expect("serializes");+ assert_eq!(json["access"], "allow");+ assert_eq!(json["fromComputer"], "desk");+ }+}diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rsindex d63bfa8b..a815b20c 100644--- a/host/crates/network/tests/two_computers.rs+++ b/host/crates/network/tests/two_computers.rs@@ -276,3 +276,40 @@ fn roles_decide_who_invites_removes_and_promotes() {assert!(!Admin.removes(Admin) && !Admin.removes(Owner) && !Member.removes(Member));assert!(Owner.promotes(Member) && !Owner.promotes(Admin) && !Admin.promotes(Member));}++#[tokio::test]+async fn the_receiving_computers_rules_decide_but_answers_always_pass() {+ use codync_network::{Access, Rule};+ let (desk_dir, laptop_dir) = (temp_dir("desk7"), temp_dir("laptop7"));+ let (desk, mut desk_inbox) = Node::start(&desk_dir, &Connector::Private).await.unwrap();+ desk.create("desk").unwrap();+ desk.set_agents([(agent("reviewer"), Reach::App), (agent("coder"), Reach::App)]);+ let (laptop, mut laptop_inbox) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();+ laptop.set_agents([(agent("lead"), Reach::App), (agent("intern"), Reach::App)]);+ laptop.join(&desk.invite().unwrap(), "laptop").await.unwrap();++ // The desk asks the laptop's lead something before the laptop locks the desk out.+ let ask = Letter::new("reviewer", to("lead@laptop"), "which branch?");+ let asked = ask.id.clone();+ desk.send(ask).await.unwrap();+ next(&mut laptop_inbox).await;+ desk.set_rules(vec![+ Rule::new(Access::Allow, "lead@laptop", "reviewer").unwrap(),+ Rule::new(Access::Deny, "*@laptop", "*").unwrap(),+ ])+ .unwrap();+ laptop.send(Letter::new("lead", to("reviewer@desk"), "review this")).await.unwrap();+ assert_eq!(next(&mut desk_inbox).await.body, "review this", "allowed by the first rule");+ let refused = laptop.send(Letter::new("intern", to("coder@desk"), "hi")).await.unwrap_err();+ assert_eq!(refused.to_string(), "desk refused it: coder doesn't take messages from intern@laptop");+ // An answer to the desk's own question still gets in, whoever sends it.+ let answer = Letter::new("intern", to("reviewer@desk"), "main").reply_to(asked);+ assert_eq!(laptop.send(answer).await.unwrap(), Sent::Delivered);+ assert_eq!(next(&mut desk_inbox).await.body, "main");+ // A made-up answer doesn't.+ let fake = Letter::new("intern", to("coder@desk"), "sneaky").reply_to("not-a-letter-of-yours");+ assert!(laptop.send(fake).await.is_err());+ for dir in [desk_dir, laptop_dir] {+ let _ = std::fs::remove_dir_all(dir);+ }+}diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex e21d119e..029f5461 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -8,7 +8,7 @@ use crate::store::BotConfig;use serde_json::{Map, Value};/// Methods that stand for one event with one fixed property.-const FIXED: [(&str, Event, &str, &str); 12] = [+const FIXED: [(&str, Event, &str, &str); 13] = [("editHandoff", Event::HandoffAnswered, "action", "edit"),("keepConversation", Event::HandoffAnswered, "action", "keep"),("credentialSaveLogin", Event::CredentialSaved, "kind", "login"),@@ -22,6 +22,7 @@ const FIXED: [(&str, Event, &str, &str); 12] = [("networkPromote", Event::NetworkChanged, "action", "promote"),("networkRemove", Event::NetworkChanged, "action", "remove"),("networkRecover", Event::NetworkChanged, "action", "recover"),+ ("setNetworkRules", Event::NetworkChanged, "action", "rules"),];/// Switches the host owns (`setting_changed`): the method and the setting it names.diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 6e65c066..ef8af81c 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -74,6 +74,8 @@ const LOCAL_ONLY: &[&str] = &["networkRemove","networkPromote","networkRecover",+ // Who may write to this computer's bots is decided at the computer, like who is in.+ "setNetworkRules",];const SCREEN: &[&str] = &["screenPrepare", "screenOffer", "screenClose", "screenTakeover"];diff --git a/host/src/api/network.rs b/host/src/api/network.rsindex bdbe12e6..56c00830 100644--- a/host/src/api/network.rs+++ b/host/src/api/network.rs@@ -21,6 +21,7 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr"networkRemove" => network::remove(hub, str_arg(&b, "computer")?, b["cascade"] == true)?,"networkPromote" => network::promote(hub, str_arg(&b, "computer")?)?,"networkRecover" => network::recover(hub, str_arg(&b, "code")?)?,+ "setNetworkRules" => network::set_rules(hub, &b["rules"])?,_ => return Ok(ControlFlow::Continue(b)),}))}diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rsindex eddbeb1a..c647fb81 100644--- a/host/src/chat/calls/context.rs+++ b/host/src/chat/calls/context.rs@@ -373,6 +373,8 @@ pub(super) mod tests {skills: vec![],computer: false,manage_team: false,+ offered_to_network: true,+ reachable_by_assistants: true,created_by: None,shared_memory: Some(true),harness_memory: false,diff --git a/host/src/chat/team.rs b/host/src/chat/team.rsindex c23b43c6..2a71459b 100644--- a/host/src/chat/team.rs+++ b/host/src/chat/team.rs@@ -349,7 +349,7 @@ pub async fn call_async(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) ->"list_bots" => {visible_bot(hub, from)?;let remote = hub.network.directory().await;- directory::list(hub, from, args, &remote)+ directory::list(hub, from, args, &remote, |_| true)}"message_bot" => {let (to, message) = message_args(args)?;@@ -366,7 +366,7 @@ pub async fn call_async(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) ->fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Result<Value> {let source = visible_bot(hub, from)?;match name {- "list_bots" => directory::list(hub, from, args, &[]),+ "list_bots" => directory::list(hub, from, args, &[], |_| true),"message_bot" => {let (to, message) = message_args(args)?;match hub.network.recipient(to)? {diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rsindex c8944094..35e3e6ea 100644--- a/host/src/chat/team/assistant.rs+++ b/host/src/chat/team/assistant.rs@@ -73,7 +73,7 @@ fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {bail!("This computer isn't in your Codync account.");}match tool {- "list_bots" => directory::list(hub, ID, args, &[]),+ "list_bots" => directory::list(hub, ID, args, &[], |bot| bot.reachable_by_assistants),"message_bot" => message(hub, args),"read_replies" => Ok(hub.assistant.read(args["requestId"].as_str())),_ => bail!("unknown tool: {tool}"),@@ -84,6 +84,9 @@ fn message(hub: &Arc<Hub>, args: &Value) -> Result<Value> {let (to, message) = message_args(args)?;check_message(message)?;let target = visible_bot(hub, to)?;+ if !target.reachable_by_assistants {+ bail!("{} isn't open to cloud assistants: Reachable by cloud assistants is off in its settings", target.name);+ }if hub.assistant.running() >= MAX_RUNNING {bail!("{MAX_RUNNING} requests are still running: read_replies first, then try again");}diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rsindex d7acad70..7e60a850 100644--- a/host/src/chat/team/assistant/tests.rs+++ b/host/src/chat/team/assistant/tests.rs@@ -81,3 +81,20 @@ async fn phones_hear_the_switch_through_the_network_view() {assert_eq!((&view["assistants"], &view["assistantsAvailable"]), (&json!(false), &json!(true)));f.shutdown().await;}++#[tokio::test]+async fn a_bot_closed_to_cloud_assistants_is_neither_listed_nor_reached() {+ let f = Fixture::new();+ let hub = &f.hub;+ set_enabled(hub, true).unwrap();+ cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));+ hub.update_bot(&json!({"id": "b", "reachableByAssistants": false})).unwrap();+ let listed = call(hub, "user_1", "list_bots", &json!({}));+ let ids: Vec<&Value> = listed["result"]["bots"].as_array().unwrap().iter().map(|b| &b["id"]).collect();+ assert!(!ids.contains(&&json!("b")), "{listed}");+ refused(+ &call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "hi"})),+ "isn't open to cloud assistants",+ );+ f.shutdown().await;+}diff --git a/host/src/chat/team/directory.rs b/host/src/chat/team/directory.rsindex 2303a83b..909240c6 100644--- a/host/src/chat/team/directory.rs+++ b/host/src/chat/team/directory.rs@@ -3,6 +3,7 @@use super::visible_bots;use crate::hub::Hub;+use crate::store::BotConfig;use anyhow::Result;use codync_network::Peer;use serde_json::{Value, json};@@ -21,19 +22,27 @@ struct Row {online: bool,}-pub(super) fn list(hub: &Hub, from: &str, args: &Value, remote: &[Peer]) -> Result<Value> {+/// `keep` picks which of this computer's bots the caller may see.+pub(super) fn list(+ hub: &Hub,+ from: &str,+ args: &Value,+ remote: &[Peer],+ keep: fn(&BotConfig) -> bool,+) -> Result<Value> {let filter = Filter::of(args);let here = hub.network.node().and_then(|n| n.name());- let rows: Vec<Row> = rows(hub, from, remote)?.into_iter().filter(|r| filter.keeps(r, here.as_deref())).collect();+ let rows: Vec<Row> =+ rows(hub, from, remote, keep)?.into_iter().filter(|r| filter.keeps(r, here.as_deref())).collect();Ok(page(&rows, args, !filter.narrows()))}/// Everyone `from` can message, nearest first: this computer's bots, then the ones on computers/// that can take a message now.-fn rows(hub: &Hub, from: &str, remote: &[Peer]) -> Result<Vec<Row>> {+fn rows(hub: &Hub, from: &str, remote: &[Peer], keep: fn(&BotConfig) -> bool) -> Result<Vec<Row>> {let mut rows: Vec<Row> = visible_bots(&hub.store)?.into_iter()- .filter(|c| c.id != from)+ .filter(|c| c.id != from && keep(c)).map(|c| Row {words: format!("{} {}", c.name, c.description).to_lowercase(),value: json!({diff --git a/host/src/network/mod.rs b/host/src/network/mod.rsindex 96bab66d..157605ca 100644--- a/host/src/network/mod.rs+++ b/host/src/network/mod.rs@@ -9,7 +9,7 @@ mod handles;use crate::LockExt;use crate::hub::Hub;use anyhow::{Context, Result, anyhow, bail};-use codync_network::{Address, Agent, Connector, Node, Peer, Reach, Role};+use codync_network::{Address, Agent, Connector, Node, Peer, Reach, Role, Rule};use serde_json::{Value, json};use std::collections::HashMap;use std::path::PathBuf;@@ -21,6 +21,8 @@ pub use handles::handle;const KV_CONNECTOR: &str = "network_connector";/// Every address name ever given to one of this computer's bots (name → bot id).const KV_HANDLES: &str = "network_handles";+/// Who on the other computers may write to this computer's bots (`codync_network::Rule`s).+const KV_RULES: &str = "network_rules";/// How long what the other computers offer is good for before a listing asks them again.const FRESH_FOR: Duration = Duration::from_mins(1);/// How long a listing waits for computers it has never heard from.@@ -132,6 +134,10 @@ async fn boot(hub: &Arc<Hub>) -> Result<Arc<Node>> {}let connector: Connector = hub.store.kv_get(KV_CONNECTOR).as_deref().unwrap_or("public").parse()?;let (node, inbox) = Node::start(&dir(), &connector).await.context("couldn't start the network")?;+ let rules: Vec<Rule> = hub.store.kv_get(KV_RULES).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default();+ if let Err(error) = node.set_rules(rules) {+ tracing::warn!(error = format!("{error:#}"), "couldn't apply the network's rules; none apply");+ }let node = Arc::new(node);hub.network.node.set(node.clone()).map_err(|_| anyhow!("the network is already starting; try again"))?;tokio::spawn(watch(hub.clone(), node.changes()));@@ -177,6 +183,7 @@ pub fn publish(hub: &Hub) {}let agents: Vec<(Agent, Reach)> = bots.iter()+ .filter(|b| b.offered_to_network).filter_map(|b| {let id = handles.handle(&b.id)?;Some((Agent { id, name: b.name.clone(), about: b.description.clone() }, Reach::App))@@ -221,6 +228,7 @@ pub fn status(hub: &Hub) -> Value {"canInvite": mine.is_some_and(Role::invites), "canRecover": mine.is_some_and(|r| r != Role::Owner),"connector": hub.store.kv_get(KV_CONNECTOR).unwrap_or_else(|| "public".into()),"computers": computers, "assistants": assistants, "assistantsAvailable": available,+ "rules": node.rules(),})}@@ -282,6 +290,17 @@ pub fn remove(hub: &Hub, computer: &str, cascade: bool) -> Result<Value> {Ok(json!({}))}+/// `setNetworkRules`: who on the other computers may write to this computer's bots, in order+/// (the first match decides); an empty list lets everyone.+pub fn set_rules(hub: &Hub, rules: &Value) -> Result<Value> {+ let rules: Vec<Rule> =+ serde_json::from_value(rules.clone()).context("rules are {fromComputer, fromAgent, toAgent, access}")?;+ joined(hub)?.set_rules(rules.clone())?;+ hub.store.kv_set(KV_RULES, &json!(rules).to_string())?;+ emit(hub);+ Ok(status(hub))+}+pub fn promote(hub: &Hub, computer: &str) -> Result<Value> {joined(hub)?.promote(computer)?;Ok(json!({}))diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex cc9be3f5..f4b9b6e9 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -177,6 +177,8 @@ mod tests {skills: vec![],computer: false,manage_team: false,+ offered_to_network: true,+ reachable_by_assistants: true,created_by: None,shared_memory: None,harness_memory: false,diff --git a/host/src/store/model.rs b/host/src/store/model.rsindex 44fa379a..2611f51d 100644--- a/host/src/store/model.rs+++ b/host/src/store/model.rs@@ -119,6 +119,12 @@ pub struct BotConfig {/// (see `chat::manage`). The user turns it on; the bots such a bot creates have it too.#[serde(default)]pub manage_team: bool,+ /// Other computers in the user's network list this bot and may message it (`network::publish`).+ #[serde(default = "yes")]+ pub offered_to_network: bool,+ /// The user's cloud assistant lists this bot and may message it (`chat::team::assistant`).+ #[serde(default = "yes")]+ pub reachable_by_assistants: bool,/// The bot that created this one with `create_bot`; none when the user did.#[serde(default, skip_serializing_if = "Option::is_none")]pub created_by: Option<String>,diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.pyindex cadd4506..f4b829f1 100644--- a/host/tests/fixtures/team_agent.py+++ b/host/tests/fixtures/team_agent.py@@ -88,6 +88,14 @@ def prompt(request):update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Message queued"}})send({"id": request["id"], "result": {"stopReason": "end_turn"}})return+ if text.startswith("TRY "):+ # TRY <target> <message>: a message that may be refused; the reply says which.+ target, message = text.split("\n", 1)[0].split(" ", 2)[1:]+ response = team_call(target, message)+ reply = ("Refused: " if response.get("isError") else "Sent: ") + response["content"][0]["text"]+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})+ returnif text.split("\n\n")[-1] == "REPORT":response = mcp_call("chat", "send_message", {"text": "Report for the user"})if "Your final reply goes back to" in text:diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex a0806071..0cf2814c 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -37,9 +37,11 @@"event:bot.bot.modelOptions": "object","event:bot.bot.name": "string","event:bot.bot.notify": "null",+ "event:bot.bot.offeredToNetwork": "bool","event:bot.bot.permission": "string","event:bot.bot.pinned": "bool","event:bot.bot.position": "number",+ "event:bot.bot.reachableByAssistants": "bool","event:bot.bot.resting": "array","event:bot.bot.rev": "number","event:bot.bot.selfFallbacks": "bool",diff --git a/host/tests/network_e2e.rs b/host/tests/network_e2e.rsindex 7468c030..f07cae48 100644--- a/host/tests/network_e2e.rs+++ b/host/tests/network_e2e.rs@@ -226,3 +226,30 @@ async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {assert_eq!(computer(&there, "desk")["canRemove"], false, "an admin doesn't remove the owner");assert_eq!(computer(&here.await.unwrap(), "laptop")["canPromote"], false, "already an admin");}++#[tokio::test]+async fn a_bot_kept_off_the_network_and_a_deny_rule_keep_letters_out() {+ let (desk, laptop, reviewer, lead) = two_computers().await;+ let secret = desk.bot("Secret").await;+ desk.call("updateBot", json!({"id": secret, "offeredToNetwork": false})).await;+ let peers = laptop.call("networkPeers", json!({})).await;+ let offered: Vec<&Value> = computer(&peers, "desk")["agents"].as_array().unwrap().iter().map(|a| &a["id"]).collect();+ assert!(offered.contains(&&json!("reviewer")), "{offered:?}");+ assert!(!offered.contains(&&json!("secret")), "kept off the network: {offered:?}");++ // The desk takes nothing from the laptop's bots; the lead's message_bot says why.+ let rules = json!([{"fromComputer": "laptop", "fromAgent": "*", "toAgent": "*", "access": "deny"}]);+ let view = desk.call("setNetworkRules", json!({"rules": rules})).await;+ assert_eq!(view["rules"][0]["access"], "deny");+ laptop.call("send", json!({"botId": lead, "text": "TRY reviewer@desk review this"})).await;+ let refused = laptop.wait_for(&lead, is_final).await;+ let text = refused["data"]["text"].as_str().unwrap();+ assert!(+ text.starts_with("Refused: ") && text.contains("reviewer doesn't take messages from lead@laptop"),+ "{text}"+ );+ let failed = laptop.wait_for(&lead, exchange("failed")).await;+ assert!(failed["data"]["botMessage"]["detail"].as_str().unwrap().contains("doesn't take messages"), "{failed}");+ let history = desk.call("history", json!({"botId": reviewer})).await;+ assert!(!history.to_string().contains("review this"), "nothing reached the reviewer");+}