Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
Folders whose sessions are never shared
Lars Talian8bb2cbc97948
diff --git a/DESIGN.md b/DESIGN.mdindex 94807a3..be17dc4 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -386,6 +386,7 @@ edits): Claude Code plugin or `claude mcp add --scope user` + hooks, `~/.codex/c| `auto_update` | `true` | install new releases when they come out (checked every few hours) || `reason` | `false` | list your live Reason sessions (set by `reason-network setup`) || `inbound` | accept | see above |+| `folders` | none | folders whose sessions are never shared, e.g. `"~/personal" = "off"` (`reason-network folder <path> off`, `on` undoes it) |## Troubleshootingdiff --git a/README.md b/README.mdindex e2dfad0..4989c2e 100644--- a/README.md+++ b/README.md@@ -73,6 +73,7 @@ reason-network send '*' "deploying api at 5" # everyone (or alice/*, repo:api)reason-network listen --as terminal # replies to what you sent from this terminalreason-network link # the invite line again: Join the Reason Network: <link>reason-network setup # which agents are on it, and how messages are handled+reason-network folder ~/personal off # sessions in ~/personal stay off the network (on undoes it)```With the Reason CLI, `reason network who` and `reason network send` work too, anddiff --git a/src/client.rs b/src/client.rsindex d0d4e69..f30d0bf 100644--- a/src/client.rs+++ b/src/client.rs@@ -92,7 +92,13 @@ impl Link {let c = self.spawn_io(connect_or_start(self.start).await?);let regs: Vec<SessionReg> = self.regs.lock().unwrap().values().cloned().collect();for reg in regs {- self.raw(&c, &Request::Register { session: reg }).await?;+ if let Err(e) = self.raw(&c, &Request::Register { session: reg.clone() }).await {+ // Its folder was turned off meanwhile: it stays off, and the rest reconnect.+ if e.to_string() != crate::config::OFF_HERE {+ return Err(e);+ }+ self.regs.lock().unwrap().remove(®.key);+ }}*slot = Some(c.clone());Ok(c)diff --git a/src/config.rs b/src/config.rsindex 8cb0194..f02d946 100644--- a/src/config.rs+++ b/src/config.rs@@ -1,5 +1,5 @@use crate::{paths, util};-use anyhow::Result;+use anyhow::{Result, anyhow};use serde::{Deserialize, Serialize};use std::collections::BTreeMap;@@ -21,8 +21,15 @@ pub struct Config {/// Install new releases when they come out (the daemon checks every few hours).pub auto_update: bool,pub inbound: Inbound,+ /// Folders whose sessions stay off the network, e.g. `"~/personal" = "off"` (`reason-network folder`). The deepest+ /// entry that holds a session's folder decides; `off` is the only value so far.+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]+ pub folders: BTreeMap<String, String>,}+/// What an agent's tools say in a folder whose sessions are off the network.+pub const OFF_HERE: &str = "Reason Network is off in this folder";+/// What happens to messages from teammates' agents: `accept` delivers them, `hold` waits for you to approve/// (`reason-network held`), `refuse` bounces them.#[derive(Debug, Clone, Serialize, Deserialize)]@@ -52,6 +59,7 @@ impl Default for Config {reason: false,auto_update: true,inbound: Inbound::default(),+ folders: BTreeMap::new(),}}}@@ -105,4 +113,177 @@ impl Config {pub fn tray(&self) -> bool {cfg!(target_os = "macos") && self.tray && crate::paths::env_var_os("NO_TRAY").is_none()}++ /// Whether sessions working in `cwd` stay off the network.+ pub fn off_in(&self, cwd: &str) -> bool {+ if self.folders.is_empty() {+ return false;+ }+ let off = |cwd: &str| folder_rule(&self.folders, &home(), cwd).is_some_and(|(_, v)| v == "off");+ // An agent may report the folder by a path with a link in it (`/var/…` for macOS's `/private/var/…`).+ off(cwd) || std::fs::canonicalize(cwd).is_ok_and(|real| off(&real.display().to_string()))+ }++ /// `folders` entries this version ignores: a value other than `off`, or not a full path.+ pub fn odd_folders(&self) -> Vec<(&String, &String)> {+ self.folders.iter().filter(|(k, v)| !rule_holds(k, v, &home())).collect()+ }+}++fn home() -> String {+ paths::user_home().to_string_lossy().into_owned()+}++/// The `folders` entry that decides for `cwd`: of those that hold it, the deepest.+fn folder_rule<'a>(folders: &'a BTreeMap<String, String>, home: &str, cwd: &str) -> Option<(&'a str, &'a str)> {+ let at = parts(cwd, home);+ folders+ .iter()+ .filter(|(k, v)| rule_holds(k, v, home))+ .map(|(k, v)| (k, v, parts(k, home)))+ .filter(|(_, _, p)| at.starts_with(p))+ .max_by_key(|(_, _, p)| p.len())+ .map(|(k, v, _)| (k.as_str(), v.as_str()))+}++fn rule_holds(folder: &str, value: &str, home: &str) -> bool {+ value == "off" && full(&expand(folder, home))+}++/// `~` is the home folder.+fn expand(path: &str, home: &str) -> String {+ match path.trim().strip_prefix('~') {+ Some(rest) if rest.is_empty() || rest.starts_with(['/', '\\']) => format!("{home}{rest}"),+ _ => path.trim().to_string(),+ }+}++/// `/…`, `\\…`, or `C:\…`, whichever system it is on.+fn full(path: &str) -> bool {+ let b = path.as_bytes();+ path.starts_with(['/', '\\'])+ || (b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'/' | b'\\'))+}++/// A path's folder names, `~` expanded, either slash; without case where the file system ignores it.+fn parts(path: &str, home: &str) -> Vec<String> {+ let path = expand(path, home);+ let path = path.strip_prefix(r"\\?\").unwrap_or(&path);+ path.split(['/', '\\'])+ .filter(|p| !p.is_empty() && *p != ".")+ .map(|p| if cfg!(any(windows, target_os = "macos")) { p.to_lowercase() } else { p.to_string() })+ .collect()+}++/// Sets `folder`'s entry in the config file, keeping the rest of the file as it is: `off`, or none (`on`). Returns the+/// entry's name (`~/personal`), and whether that changes which sessions are off.+pub fn set_folder(folder: &str, off: bool) -> Result<(String, bool)> {+ let home = home();+ let path = real(&std::path::absolute(expand(folder, &home))?).display().to_string();+ let name = util::tilde(path.strip_prefix(r"\\?\").unwrap_or(&path));+ let file = paths::config();+ let text = match std::fs::read_to_string(&file) {+ Ok(s) => s,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),+ Err(e) => return Err(e.into()),+ };+ let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| anyhow!("fix {} first: {e}", file.display()))?;+ let table = doc.entry("folders").or_insert(toml_edit::table());+ let table =+ table.as_table_like_mut().ok_or_else(|| anyhow!("fix {} first: `folders` is a table", file.display()))?;+ // The same folder, however it was written.+ let same: Vec<String> =+ table.iter().map(|(k, _)| k.to_string()).filter(|k| parts(k, &home) == parts(&name, &home)).collect();+ let was_off = same.iter().any(|k| table.get(k).and_then(|v| v.as_str()) == Some("off"));+ for k in &same {+ table.remove(k);+ }+ if off {+ table.insert(&name, toml_edit::value("off"));+ }+ if table.is_empty() {+ doc.remove("folders");+ }+ if doc.to_string() != text {+ paths::ensure_home()?;+ std::fs::write(&file, doc.to_string())?;+ }+ Ok((name, was_off != off))+}++/// `path` as agents report their folder, links followed (on macOS, /tmp is /private/tmp), even before it exists.+fn real(path: &std::path::Path) -> std::path::PathBuf {+ let mut rest = Vec::new();+ let mut at = path;+ loop {+ if let Ok(r) = at.canonicalize() {+ return rest.iter().rev().fold(r, |p, n| p.join(n));+ }+ match (at.parent(), at.file_name()) {+ (Some(p), Some(n)) => {+ rest.push(n);+ at = p;+ }+ _ => return path.to_path_buf(),+ }+ }+}++/// The entry that keeps `folder` off when it has none of its own (`~/personal` for `~/personal/notes`).+pub fn off_by(folder: &str) -> Option<String> {+ let cfg = Config::load();+ let (k, v) = folder_rule(&cfg.folders, &home(), folder)?;+ (v == "off").then(|| k.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn folders(entries: &[(&str, &str)]) -> BTreeMap<String, String> {+ entries.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()+ }++ #[test]+ fn the_deepest_folder_that_holds_a_session_decides() {+ let f = folders(&[("~/work", "off"), ("/Users/alex/work/oss", "off"), ("/srv", "off")]);+ let rule = |cwd: &str| folder_rule(&f, "/Users/alex", cwd).map(|(k, _)| k);+ assert_eq!(rule("/Users/alex/work/oss/engine"), Some("/Users/alex/work/oss"));+ assert_eq!(rule("/Users/alex/work/api/"), Some("~/work"));+ assert_eq!(rule("/Users/alex/work"), Some("~/work"));+ assert_eq!(rule("/srv/./x"), Some("/srv"));+ // Whole folder names only.+ assert_eq!(rule("/Users/alex/workshop"), None);+ assert_eq!(rule("/Users/alex"), None);+ assert_eq!(rule("/"), None);+ }++ #[test]+ fn home_and_windows_paths() {+ let home = r"C:\Users\alex";+ let f = folders(&[("~/Personal", "off"), (r"D:\scratch", "off")]);+ let off = |cwd: &str| folder_rule(&f, home, cwd).is_some();+ assert!(off(r"C:\Users\alex\Personal\taxes"));+ assert!(off("C:/Users/alex/Personal"));+ assert!(off(r"\\?\C:\Users\alex\Personal"));+ assert!(off(r"D:\scratch\x") && !off(r"D:\scratchpad") && !off(r"C:\Users\alex"));+ // `~` alone is the home folder; `~alex` is no one's.+ let f = folders(&[("~", "off"), ("~alex", "off")]);+ assert!(folder_rule(&f, "/home/alex", "/home/alex/x").is_some());+ assert!(folder_rule(&f, "/home/alex", "/home/bob").is_none());+ }++ #[test]+ fn only_off_counts_and_the_rest_is_ignored() {+ let f = folders(&[("~/work", "off"), ("~/work/team", "work"), ("relative", "off")]);+ let cfg = Config { folders: f.clone(), ..Config::default() };+ // `work` (a network to come) isn't understood yet: the folder above it decides.+ assert_eq!(folder_rule(&f, "/home/alex", "/home/alex/work/team/x"), Some(("~/work", "off")));+ assert!(folder_rule(&f, "/home/alex", "/relative").is_none());+ assert_eq!(cfg.odd_folders().len(), 2);+ // No entries: nothing is off.+ assert!(!Config::default().off_in("/home/alex/work"));+ let parsed: Config = toml::from_str("[folders]\n\"~/personal\" = \"off\"\n").unwrap();+ assert!(parsed.off_in(&format!("{}/personal/x", home())));+ }}diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex 823c8c4..ec936ad 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -9,6 +9,7 @@ use crate::{git::GitInfo,net::{Presence, Remote},proto::*,+ store::Remembered,util,};use anyhow::{Result, bail};@@ -52,7 +53,7 @@ enum Place {impl Daemon {/// This machine's sessions: running ones, plus (if `unmanaged`) Claude Code sessions without Reason Network.pub(super) async fn local_rows(self: &Arc<Self>, me: Option<&str>, unmanaged: bool) -> Result<Vec<SessionInfo>> {- let claude = tokio::task::spawn_blocking(claude::scan).await?;+ let claude = self.shared(tokio::task::spawn_blocking(claude::scan).await?);let mut cwds: Vec<String> = self.inner.lock().unwrap().live.values().map(|l| l.reg.cwd.clone()).collect();cwds.extend(claude.iter().filter_map(|c| c.cwd.clone()));let mut gits: HashMap<String, GitInfo> = HashMap::new();@@ -188,9 +189,27 @@ impl Daemon {}}+ /// Claude Code sessions outside the folders that are off.+ fn shared(&self, mut claude: Vec<ClaudeSession>) -> Vec<ClaudeSession> {+ claude.retain(|c| !c.cwd.as_deref().is_some_and(|d| self.cfg.off_in(d)));+ claude+ }++ /// Sessions this machine remembers (gone for now), but none from a folder that is off.+ fn remembered(&self, g: &super::Inner) -> Vec<Remembered> {+ let live: HashSet<&str> = g.live.values().map(|l| l.name.as_str()).collect();+ let mut known = g.store.sessions().unwrap_or_default();+ known.retain(|r| !live.contains(r.name.as_str()) && !self.cfg.off_in(&r.cwd));+ known+ }+/// What this machine tells teammates about itself.pub async fn presence(self: &Arc<Self>) -> Presence {- let mut sessions = self.local_rows(None, self.cfg.share_unmanaged).await.unwrap_or_default();+ let sessions = self.local_rows(None, self.cfg.share_unmanaged).await.unwrap_or_default();+ self.presence_of(sessions)+ }++ fn presence_of(&self, mut sessions: Vec<SessionInfo>) -> Presence {if !self.cfg.share_paths {for s in &mut sessions {s.cwd =@@ -198,9 +217,7 @@ impl Daemon {}}let g = self.inner.lock().unwrap();- let live: HashSet<&str> = g.live.values().map(|l| l.name.as_str()).collect();- let mut known = g.store.sessions().unwrap_or_default();- known.retain(|r| !live.contains(r.name.as_str()));+ let mut known = self.remembered(&g);known.sort_by_key(|r| -r.last_seen);Presence {sessions,@@ -218,8 +235,7 @@ impl Daemon {let mut rows = self.local_rows(me.as_deref(), true).await?;if all {let g = self.inner.lock().unwrap();- let live: HashSet<&str> = g.live.values().map(|l| l.name.as_str()).collect();- for r in g.store.sessions()?.into_iter().filter(|r| !live.contains(r.name.as_str())) {+ for r in self.remembered(&g) {let git = GitInfo { root: None, repo: r.repo.clone(), branch: r.branch.clone() };let mut row = self.row(&r.name, &r.agent, &r.cwd, Some(&git));row.status = "offline".into();@@ -284,7 +300,6 @@ impl Daemon {/// Every address target we know about, here and on teammates' machines.fn candidates(&self, g: &super::Inner, remotes: &HashMap<EndpointId, Remote>) -> Vec<Cand> {let mut out = Vec::new();- let live: HashSet<&str> = g.live.values().map(|l| l.name.as_str()).collect();for l in g.live.values() {out.push(Cand {person: self.person.clone(),@@ -295,7 +310,7 @@ impl Daemon {place: Place::Local(Some(l.reg.key.clone())),});}- for r in g.store.sessions().unwrap_or_default().into_iter().filter(|r| !live.contains(r.name.as_str())) {+ for r in self.remembered(g) {out.push(Cand {person: self.person.clone(),name: r.name,@@ -435,3 +450,44 @@ impl Daemon {fn claude_match(c: &ClaudeSession, reg: &SessionReg) -> bool {(reg.agent_session_id.is_some() && c.session_id == reg.agent_session_id) || reg.pid == Some(c.pid)}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn presence_leaves_out_sessions_in_a_folder_that_is_off() {+ let cfg = crate::config::Config {+ folders: [("/work/private".to_string(), "off".to_string())].into(),+ share_unmanaged: true,+ ..Default::default()+ };+ let d = super::super::test_daemon(cfg);+ // Remembered from before the folder was off, and one that wasn't in it.+ for (name, cwd) in [("taxes-claude", "/work/private/taxes"), ("api-claude", "/work/api")] {+ let r = Remembered {+ name: name.into(),+ key: format!("claude-code:{name}"),+ agent: agent::CLAUDE_CODE.into(),+ cwd: cwd.into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Push,+ last_seen: util::now_ms(),+ };+ d.inner.lock().unwrap().store.upsert_session(&r).unwrap();+ }+ assert_eq!(d.presence_of(Vec::new()).known, ["api-claude"]);+ // Claude Code's own list: neither registered nor shown without Reason Network.+ let claude = |pid: u32, cwd: &str| -> ClaudeSession {+ serde_json::from_value(serde_json::json!({ "pid": pid, "cwd": cwd })).unwrap()+ };+ let shown = d.shared(vec![claude(1, "/work/private"), claude(2, "/work/api"), claude(3, "/work/private/x")]);+ assert_eq!(shown.iter().map(|c| c.pid).collect::<Vec<_>>(), [2]);+ // Nor can a message reach the remembered one.+ let g = d.inner.lock().unwrap();+ let names: Vec<String> = d.candidates(&g, &HashMap::new()).into_iter().map(|c| c.name).collect();+ assert_eq!(names, ["api-claude"]);+ }+}diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 225277d..3215a30 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -495,7 +495,7 @@ impl Daemon {let mut g = self.inner.lock().unwrap();self.prune(&mut g);let key = g.live.iter().find(|(_, l)| l.name == name).map(|(k, _)| k.clone());- if key.is_none() && g.store.session_by_name(name)?.is_none() {+ if key.is_none() && g.store.session_by_name(name)?.is_none_or(|r| self.cfg.off_in(&r.cwd)) {return Ok(("refused".into(), format!("no session called {} on {}", msg.to, self.machine)));}if g.store.has(&msg.id)? {diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 9cc98f0..ebe94bf 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -173,11 +173,12 @@ pub fn load_key() -> Result<SecretKey> {impl Daemon {fn open() -> Result<Self> {- let cfg = Config::load();- let store = Store::open(&paths::db(), paths::inbox())?;+ Self::with(Config::load(), Store::open(&paths::db(), paths::inbox())?, load_key()?)+ }++ fn with(cfg: Config, store: Store, key: SecretKey) -> Result<Self> {let team: Option<TeamState> =store.get("team")?.and_then(|s| serde_json::from_str(&s).ok()).map(TeamState::without_odd_names);- let key = load_key()?;// In a team, who we are is what the signed roster says, whatever the config file says.let member = team.as_ref().and_then(|t| t.member(&key.public()).cloned());Ok(Daemon {@@ -365,3 +366,11 @@ impl Daemon {info}}++/// A daemon on an in-memory store, outside any team, with `cfg`.+#[cfg(test)]+fn test_daemon(cfg: Config) -> Daemon {+ let inbox = std::env::temp_dir().join(format!("reason-network-inbox-{}", ulid::Ulid::new()));+ let store = Store::open(std::path::Path::new(":memory:"), inbox).unwrap();+ Daemon::with(cfg, store, SecretKey::generate()).unwrap()+}diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex a8a2d73..cc3a29c 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -2,7 +2,7 @@//! kept alive by hook events and the agent's process).use super::{Daemon, Inner, Live, log};-use crate::{agent, git::GitInfo, proto::*, render, store::Remembered, util};+use crate::{agent, config::OFF_HERE, git::GitInfo, proto::*, render, store::Remembered, util};use anyhow::{Result, anyhow, bail};use std::{collections::HashSet, sync::Arc, time::Instant};@@ -39,6 +39,10 @@ impl Daemon {mut reg: SessionReg,git: GitInfo,) -> Result<(Registered, (String, Vec<Message>))> {+ // Every session comes in here: one in a folder that is off never does.+ if self.cfg.off_in(®.cwd) {+ bail!(OFF_HERE);+ }let now = util::now_ms();let others = self.my_names_elsewhere();let mut g = self.inner.lock().unwrap();@@ -329,3 +333,33 @@ fn pick_name(g: &Inner, reg: &SessionReg, git: &GitInfo, elsewhere: &HashSet<Str}Ok((2..).map(|i| util::joined(&base, &i.to_string())).find(|n| !taken(n)).expect("some suffix is free"))}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_session_in_a_folder_that_is_off_never_registers() {+ let cfg = crate::config::Config {+ folders: [("/work/private".to_string(), "off".to_string())].into(),+ ..Default::default()+ };+ let d = super::super::test_daemon(cfg);+ let reg = |key: &str, cwd: &str| SessionReg {+ key: key.into(),+ agent: "codex".into(),+ cwd: cwd.into(),+ agent_session_id: None,+ pid: None,+ tier: Tier::Pull,+ name: None,+ };+ let err = d.register_quiet(None, reg("codex:1", "/work/private/notes"), GitInfo::default()).unwrap_err();+ assert_eq!(err.to_string(), OFF_HERE);+ let (r, _) = d.register_quiet(Some(1), reg("codex:2", "/work/private-api"), GitInfo::default()).unwrap();+ assert_eq!(r.name, "private-api-codex");+ let g = d.inner.lock().unwrap();+ assert_eq!(g.live.keys().collect::<Vec<_>>(), ["codex:2"]);+ assert!(g.store.session_by_key("codex:1").unwrap().is_none());+ }+}diff --git a/src/hook.rs b/src/hook.rsindex 31b2b58..6f6bd68 100644--- a/src/hook.rs+++ b/src/hook.rs@@ -64,6 +64,10 @@ async fn handle(["CURSOR_PROJECT_DIR", "GEMINI_CWD", "CLAUDE_PROJECT_DIR"].iter().find_map(|k| std::env::var(k).ok())}).or_else(|| std::env::current_dir().ok().map(|p| p.display().to_string()));+ // A folder that is off: not a word, to the agent or the daemon.+ if cwd.as_deref().is_some_and(|c| crate::config::Config::load_strict().unwrap_or_default().off_in(c)) {+ return None;+ }let ev = match (event, state.as_deref()) {("session-start", _) => "start",("user-prompt-submit", _) => "prompt",diff --git a/src/main.rs b/src/main.rsindex 97bf981..ed68c31 100644--- a/src/main.rs+++ b/src/main.rs@@ -234,6 +234,12 @@ enum Cmd {},/// Use your own iroh relay for the team, so its machines never contact n0 (or `default` for Reason's relays)Relay { url: String },+ /// Keep the agent sessions in a folder (and the folders in it) off the network, or put them back on+ Folder {+ path: String,+ #[arg(value_parser = ["off", "on"])]+ state: String,+ },/// List messages waiting for your approval (when `inbound` is `hold`)Held,/// Deliver held messages@@ -590,6 +596,23 @@ async fn cli(cmd: Cmd) -> Result<()> {println!("{}", shown(&link.call::<String>(Request::SetRelay { url }).await?));wait_exit(daemon_pid()).await;}+ Cmd::Folder { path, state } => {+ let off = state == "off";+ let (name, changed) = config::set_folder(&path, off)?;+ // The daemon reads the config when it starts.+ if changed && stop_daemon().await {+ let _ = Link::new(None).call::<TeamInfo>(Request::Team).await;+ }+ if off {+ println!(+ "Reason Network is off in {name}: teammates don't see its sessions and can't message them. `{CLI} folder {name} on` undoes it."+ );+ } else if let Some(by) = config::off_by(&name) {+ println!("{name} is still off: it is in {by}.");+ } else {+ println!("Reason Network is on in {name}.");+ }+ }Cmd::Held => {let msgs: Vec<Message> = link.call(Request::Held).await?;if msgs.is_empty() {diff --git a/src/mcp.rs b/src/mcp.rsindex f3db203..b7508e9 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -3,6 +3,7 @@use crate::{agent::{self, ClaudeSocket},client::Link,+ config::OFF_HERE,proto::*,render,};@@ -117,6 +118,7 @@ pub async fn run() -> Result<()> {tokio::time::sleep(Duration::from_secs(3)).await;let agent = s.agent(&peer, None);if !agent::multiplexed(agent)+ && !off_here()&& let Err(e) = s.session(agent, None).await{eprintln!("reason-network: registering session: {e:#}");@@ -294,6 +296,9 @@ impl ReasonNetworkMcp {/// Registers the session on first use and returns its key.async fn session(&self, agent: &'static str, meta_id: Option<String>) -> Result<String> {+ if off_here() {+ anyhow::bail!(OFF_HERE);+ }if meta_id.is_none()&& agent::multiplexed(agent)&& let Ok(Some(key)) =@@ -365,6 +370,11 @@ impl ReasonNetworkMcp {}}+/// Whether this session's folder is off the network (read each time: `folder` may have changed it since).+fn off_here() -> bool {+ crate::config::Config::load_strict().unwrap_or_default().off_in(&agent::cwd())+}+/// The files an agent asked to send, read only from its own folder: its repository (or where it works), none of its/// hidden files, nothing where credentials or Reason Network's state are kept. A person's `send --file` has no such/// limit; an agent can be talked into sending what its harness wouldn't let it read.diff --git a/src/setup.rs b/src/setup.rsindex 57577d4..34dfe31 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -1464,6 +1464,15 @@ pub async fn doctor() -> Result<()> {}Err(e) => println!("✗ daemon: {}", crate::shown(&format!("{e:#}"))),}+ let cfg = crate::config::Config::load();+ let (odd, off): (Vec<_>, Vec<_>) = cfg.folders.iter().partition(|e| cfg.odd_folders().contains(e));+ if !off.is_empty() {+ println!("- Reason Network is off in {}", off.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(", "));+ }+ for (k, v) in odd {+ let why = if v == "off" { "not a full path" } else { "\"off\" is the only setting so far" };+ println!(" ! folders: \"{k}\" = \"{v}\" is ignored: {why}");+ }let svc = service_installed();println!("{} login service: {}",diff --git a/src/skill.md b/src/skill.mdindex 55505cf..d7285e6 100644--- a/src/skill.md+++ b/src/skill.md@@ -26,6 +26,7 @@ to join.they paste it to their agent.- `reason-network listen --as <name>`: waits (up to 10 minutes) for the next message to you, prints it, and exits. Youare reachable as `<your user>/<name>`. After handling a message and replying, run it again to keep listening.+- `reason-network folder <path> off`: keeps the sessions in that folder off the network (`on` puts them back).## How to behavediff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex 945b391..a267cd1 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -298,8 +298,19 @@ run(eve, "stop")out = cli("alice", "team")check("the others are still connected", re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", out) is not None, out)+# --- a folder that is off: its sessions are never shared ---+PRIVATE = os.path.join(D, "private")+os.makedirs(PRIVATE, exist_ok=True)+out = cli("alex", "folder", PRIVATE, "off")+check("folder <path> off turns Reason Network off there", "Reason Network is off in" in out and "private on` undoes it" in out, out)+check("…in the config's [folders]", re.search(r'\[folders\]\n".*private" = "off"', open(os.path.join(H["alex"], "config.toml")).read()) is not None)+out = cli("alex", "folder", os.path.join(PRIVATE, "sub"), "on")+check("…and a folder in it stays off", "sub is still off: it is in" in out, out)+time.sleep(3)+# --- sessions on both machines ---claude = Mcp("alex", "claude-code", strip_claude=False, cwd=ROOT)+hidden = Mcp("alex", "claude-code", strip_claude=True, cwd=PRIVATE)codex = Mcp("alice", "codex-mcp-client", strip_claude=True, cwd=os.path.join(D, "work"))meta = {"sessionId": "11111111-aaaa", "threadId": "11111111-aaaa"}time.sleep(7) # Claude's session registers after 3s; presence propagates every 2s@@ -307,6 +318,16 @@ out = codex.tool("list_team", {}, meta)claude_name = os.path.basename(ROOT).lower() + "-claude"check("alice's agent sees alex's session across machines", claude_name in out and "alex (verified) · laptop" in out, out)check("list_team gives the invite line", "Invite people with this line: Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)+check("…but not the one in alex's folder that is off", "private-claude" not in out, out)+out = hidden.tool("list_team", {})+check("in a folder that is off, the tools say so", out == "Reason Network is off in this folder", out)+out = hook("alex", "codex", "session-start", {"session_id": "33333333-cccc", "cwd": PRIVATE, "hook_event_name": "SessionStart"})+check("…and hooks say nothing", out == "", out)+out = cli("alex", "who")+check("…nor is either session on alex's own list", "private-" not in out and claude_name in out, out)+out = cli("alice", "send", "alex/private-claude", "x")+check("…and a teammate can't message it", "no session called 'alex/private-claude'" in out, out)+hidden.close()# (After Codex's first tool call registered it.) Nobody reports a status: Reason Network reads the plan step in progress from Codex's own transcript.rollout = os.path.join(D, "rollout.jsonl")plan = {"plan": [{"step": "set up fixtures", "status": "completed"}, {"step": "testing cross-machine Reason Network", "status": "in_progress"}]}@@ -525,6 +546,9 @@ time.sleep(10)out = cli("alice", "team")check("alice's machine learns it was removed when it reconnects", "not in a team" in out, out)+out = cli("alex", "folder", PRIVATE, "on")+check("folder <path> on puts it back", "Reason Network is on in" in out and "private" not in open(os.path.join(H["alex"], "config.toml")).read(), out)+claude.close()cli("alex", "stop")cli("alice", "stop")