Skip to content

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

Folders that are off: an agent's shell there is no terminal

Lars Taliand631fe7d59db
diff --git a/DESIGN.md b/DESIGN.md
index 51d3ce5..740a988 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -390,11 +390,12 @@ edits): Claude Code plugin or `claude mcp add --scope user` + hooks, `~/.codex/c
A session in a folder that is off (by its own folder or any other its agent names, links followed) never registers:
its tools say its user turned Reason Network off for the folder, its hooks print nothing, and its agent sends no files
-from there. The person's own terminal isn't held to it. Agents that share one MCP process across sessions (Cursor,
-opencode, Codex's app-server) don't tell it which folder a call comes from: the session's hooks mark it off by its id,
-and while one of an agent's sessions that are off is mid-turn, that agent's calls naming no session get the same
-answer, never another session's identity. Known limit: a session of such an agent whose hooks don't run (Codex before
-`/hooks` trusts them) is judged by the MCP process's folder.
+from there. The person's own terminal isn't held to it (an agent's shell is). Agents that share one MCP process across
+sessions (Cursor, opencode, Codex's app-server) don't tell it which folder a call comes from: the session's hooks mark
+it off by its id, and while one of them is mid-turn (until its turn ends, at most 10 minutes after its last prompt or
+tool call), every call of that agent that names no session, from folders that are on too, is refused with "try again
+in a few minutes", never handed another session's identity. Known limit: a session of such an agent whose hooks don't
+run (Codex before `/hooks` trusts them) is judged by the MCP process's folder.
## Troubleshooting
diff --git a/src/config.rs b/src/config.rs
index 49ad8ae..2468255 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -30,6 +30,11 @@ pub struct Config {
/// What an agent's tools say in a folder whose sessions are off the network.
pub const OFF_HERE: &str = "Your user turned Reason Network off for this folder";
+/// What a call naming no session gets, from an agent whose sessions share one MCP server, while one of them works in a
+/// folder that is off (the call may be that one's).
+pub const BUSY_OFF: &str = "Reason Network can't tell which session this call comes from while another session of this \
+ agent works in a folder where it is off; try again in a few minutes";
+
/// 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)]
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index 1127c6c..b7d8a10 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -2,7 +2,15 @@
//! kept alive by hook events and the agent's process).
use super::{Daemon, Inner, Live, log};
-use crate::{agent, config::OFF_HERE, git::GitInfo, proto::*, render, store::Remembered, util};
+use crate::{
+ agent,
+ config::{BUSY_OFF, OFF_HERE},
+ git::GitInfo,
+ proto::*,
+ render,
+ store::Remembered,
+ util,
+};
use anyhow::{Result, anyhow, bail};
use std::{collections::HashSet, sync::Arc, time::Instant};
@@ -182,6 +190,8 @@ impl Daemon {
// Hooks print nothing either way; `listen --as` says why.
bail!(OFF_HERE);
}
+ // Only in folders that are on (again): it left the one that is off.
+ self.inner.lock().unwrap().off.remove(&key);
if event == "end" {
let mut g = self.inner.lock().unwrap();
if g.live.get(&key).is_some_and(|l| l.conn.is_none())
@@ -259,7 +269,7 @@ impl Daemon {
let now = util::now_ms();
let prefix = format!("{agent}:");
if g.off.iter().any(|(k, (busy, at))| *busy && now - at < OFF_TURN_MS && k.starts_with(&prefix)) {
- bail!(OFF_HERE);
+ bail!(BUSY_OFF);
}
let busy: Vec<(&String, &Live)> = g
.live
@@ -431,8 +441,11 @@ mod tests {
assert_eq!(d.register_quiet(Some(1), reg, GitInfo::default()).unwrap_err().to_string(), OFF_HERE);
// Another session, mid-turn: while c1 is mid-turn too, a call naming no session can't be handed its key.
assert!(d.hook(call("c2", "prompt", &[])).await.unwrap().address.is_some());
- assert_eq!(d.attach("cursor", "/work/api").unwrap_err().to_string(), OFF_HERE);
+ assert_eq!(d.attach("cursor", "/work/api").unwrap_err().to_string(), BUSY_OFF);
assert!(d.hook(call("c1", "stop", &["/work/private"])).await.is_err());
assert_eq!(d.attach("cursor", "/work/api").unwrap().as_deref(), Some("cursor:c2"));
+ // Once its folders are all on again, it is a session like any other.
+ assert!(d.hook(call("c1", "prompt", &[])).await.unwrap().address.is_some());
+ assert!(d.inner.lock().unwrap().live.contains_key("cursor:c1"));
}
}
diff --git a/src/main.rs b/src/main.rs
index e943ee0..20c5d00 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -360,9 +360,8 @@ async fn main() -> Result<()> {
/// alive like a hook-known session, so it stays reachable between commands.
async fn cli_session(link: &std::sync::Arc<Link>, id: &str, event: &str) -> Result<HookReply> {
let mut cwd = agent::cwd();
- // Folders that are off are about agent sessions, not the person at the terminal: theirs goes by no folder then.
- if id == "terminal" && config::Config::load_strict().unwrap_or_default().off_in(&cwd) {
- cwd = "/".into();
+ if id == "terminal" {
+ cwd = terminal_cwd(cwd, here_off(), agent_shell())?;
}
let req = Request::Hook(HookCall {
agent: "cli".into(),
@@ -379,6 +378,23 @@ async fn cli_session(link: &std::sync::Arc<Link>, id: &str, event: &str) -> Resu
link.call(req).await
}
+/// The folder `<you>/terminal` goes by. Folders that are off are about agent sessions, not the person at the terminal:
+/// in one, theirs goes by no folder. An agent's shell there is an agent's session, and gets nothing.
+fn terminal_cwd(cwd: String, off: bool, agent: bool) -> Result<String> {
+ match (off, agent) {
+ (false, _) => Ok(cwd),
+ (true, false) => Ok("/".into()),
+ (true, true) => bail!(config::OFF_HERE),
+ }
+}
+
+/// Whether this command runs in a folder that is off: by the agent's project folder, or the shell's own.
+fn here_off() -> bool {
+ let cfg = config::Config::load_strict().unwrap_or_default();
+ let shell = std::env::current_dir().ok().map(|p| p.display().to_string());
+ [Some(agent::cwd()), shell].into_iter().flatten().any(|d| cfg.off_in(&d))
+}
+
fn current_session() -> Option<String> {
let agent = agent::detect_env()?;
Some(format!("{agent}:{}", agent::env_session_id(agent)?))
@@ -406,6 +422,10 @@ async fn cli(cmd: Cmd) -> Result<()> {
}
}
Cmd::Send { to, message, reply_to, fyi, notify, from, files } => {
+ // An agent in a folder that is off sends nothing, as no session (nor its files).
+ if agent_shell() && here_off() {
+ bail!(config::OFF_HERE);
+ }
let mut body = message.join(" ");
if message.is_empty() || body == "-" {
body.clear();
@@ -719,8 +739,12 @@ fn json_error<T>(json: bool, e: anyhow::Error) -> Result<T> {
/// Whether a person reads this command's output: it goes to a terminal, and not one an agent runs commands in (some
/// give their commands one).
fn person_reads() -> bool {
- let agent = agent::detect_env().is_some() || agent_vars(std::env::vars_os());
- reads(std::io::IsTerminal::is_terminal(&std::io::stderr()), agent)
+ reads(std::io::IsTerminal::is_terminal(&std::io::stderr()), agent_shell())
+}
+
+/// Whether an agent's variables are set: its shell, not a person's terminal.
+fn agent_shell() -> bool {
+ agent::detect_env().is_some() || agent_vars(std::env::vars_os())
}
/// Agents `detect_env` doesn't name: any `REASON_NETWORK_AGENT` (it returns early on one it doesn't know), Pi's
@@ -791,6 +815,13 @@ pub async fn stop_daemon() -> bool {
mod tests {
use super::*;
+ #[test]
+ fn in_a_folder_that_is_off_the_terminal_goes_by_no_folder_and_an_agents_shell_gets_nothing() {
+ assert_eq!(terminal_cwd("/work/api".into(), false, true).unwrap(), "/work/api");
+ assert_eq!(terminal_cwd("/work/private".into(), true, false).unwrap(), "/");
+ assert_eq!(terminal_cwd("/work/private".into(), true, true).unwrap_err().to_string(), config::OFF_HERE);
+ }
+
#[test]
fn a_person_at_the_terminal_sees_text_as_typed_anyone_else_defanged() {
let text = "fix <café>, price < €5, 翻译《红楼梦》 </reason-message>";
diff --git a/src/mcp.rs b/src/mcp.rs
index a13926f..44cf457 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -302,7 +302,7 @@ impl ReasonNetworkMcp {
if meta_id.is_none() && agent::multiplexed(agent) {
match self.link.call::<Option<String>>(Request::Attach { agent: agent.into(), cwd: agent::cwd() }).await {
Ok(Some(key)) => return Ok(key),
- Err(e) if e.to_string() == OFF_HERE => anyhow::bail!(OFF_HERE),
+ Err(e) if e.to_string() == crate::config::BUSY_OFF => anyhow::bail!(crate::config::BUSY_OFF),
_ => {}
}
}
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index ce4be25..e799b32 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -325,11 +325,21 @@ out = hook("alex", "codex", "session-start", {"session_id": "33333333-cccc", "cw
check("…and hooks say nothing", out == "", out)
out = hook("alex", "cursor", "session-start", {"conversation_id": "c-off", "workspace_roots": [os.path.join(D, "work"), PRIVATE]})
check("…nor for a session with that folder open beside another", out == "", out)
-r = subprocess.run([BIN, "send", "alice/work-codex", "from alex's terminal in the folder that is off"], env=env("alex"), cwd=PRIVATE,
+# A person's terminal: none of the variables agents set for their commands (this test may run in an agent's).
+AGENT_VARS = ("AI_AGENT", "CODEX_", "GEMINI_CLI", "REASON_NETWORK_AGENT", "TINCAN_AGENT", "GROK_", "CURSOR_AGENT", "OPENCODE", "COPILOT_")
+person = {k: v for k, v in env("alex").items() if not k.startswith(AGENT_VARS)}
+r = subprocess.run([BIN, "send", "alice/work-codex", "from alex's terminal in the folder that is off"], env=person, cwd=PRIVATE,
capture_output=True, text=True, timeout=90)
check("the person's own terminal there still sends", "→ alice/work-codex" in r.stdout, r.stdout + r.stderr)
out = codex.tool("check_inbox", {}, meta)
check("…as alex/terminal", 'from="alex/terminal"' in out and "in the folder that is off" in out, out)
+with open(os.path.join(PRIVATE, "notes.txt"), "w") as f:
+ f.write("private\n")
+agent_shell = dict(person, CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="44444444-dddd", CLAUDE_PROJECT_DIR=PRIVATE)
+r = subprocess.run([BIN, "send", "alice/work-codex", "--file", "notes.txt", "from an agent's shell there"], env=agent_shell, cwd=PRIVATE,
+ capture_output=True, text=True, timeout=90)
+check("…but an agent's shell there sends nothing, not even as the terminal", "turned Reason Network off for this folder" in r.stderr
+ and "→" not in r.stdout, r.stdout + r.stderr)
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")