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
Claude Code's inbox only from its own conversation; no session named after its person (#108)
Lars Talianedd065da1c97
diff --git a/DESIGN.md b/DESIGN.mdindex 2cea9dd..0d470bc 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -284,12 +284,19 @@ busy/idle). The daemon reads these, so Claude sessions show up with live busy/idMCP server loaded. Our MCP server reads the conversation it serves from there too, from the entry of the Claude Codeprocess it runs under: the nearest of its ancestors, else `CLAUDE_PID`, whose entry names the conversation it wasstarted in (`CLAUDE_CODE_SESSION_ID`), followed from then on. After `/clear` the same process is in a new conversation,-which the server then serves, and the one before ends. With no such entry (a headless Claude run from an interactive-one's shell has none, and the entry above it is the other conversation's), it goes by `CLAUDE_CODE_SESSION_ID` and-registers no process, so nothing ends it but its own server. The daemon's scan ends it as soon as the registry names the new one, by the process the server registered-it under, so mail for it waits for it instead of going into the new conversation before the server's next call. Any MCP-server that serves one session at a time (not Codex's, opencode's or Cursor's) ends its session when it registers or-takes up another, also one the registry scan or its hooks already registered.+which the server then serves, and the one before ends: the daemon's scan ends it as soon as the registry names the new+one, by the process the server registered it under, so mail for it waits for it instead of going into the new+conversation before the server's next call. Any MCP server that serves one session at a time (not Codex's, opencode's+or Cursor's) ends its session when it registers or takes up another, also one the registry scan or its hooks already+registered. Claude Code gives each shell it starts the conversation it is in then, so a shell started before `/clear`+keeps acting as the cleared conversation. With no such entry (a headless Claude run from an interactive one's shell has+none, and the entry above it is the other conversation's), the server goes by `CLAUDE_CODE_SESSION_ID` and registers+no process, so nothing ends it but its own server. The server pushes into the inbox Claude Code gave it+(`CLAUDE_CODE_MESSAGING_SOCKET`: Claude Code drops an inherited one when it starts and sets its own once its inbox+listens), else the one its own process's entry names, never another's (an inherited `CLAUDE_PID` can be the parent's).+Claude Code may list its inbox after starting the server: the server registers as `push` once it knows the inbox, and+until then the daemon posts into the one the registry lists, or leaves the mail for `check_inbox` and says so. A server+asked to push with no inbox says so, and the mail is unread again: nobody is told it was delivered.## Getting messages into agentsdiff --git a/src/agent.rs b/src/agent.rsindex cc4216a..4ac44bc 100644--- a/src/agent.rs+++ b/src/agent.rs@@ -215,32 +215,40 @@ pub fn agent_pid() -> u32 {/// not have written its entry yet), not on every call: each look can run `ps` for each ancestor.pub fn claude_pid() -> Option<u32> {static PID: std::sync::OnceLock<u32> = std::sync::OnceLock::new();- static MISSED: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);if let Some(pid) = PID.get() {return Some(*pid);}- if MISSED.lock().unwrap().is_some_and(|t| t.elapsed() < LOOK_AGAIN) {- return None;- }+ // Our ancestors don't change: they are looked up once (each can take a `ps`), their entries each time.+ let chain = ancestors();let dir = paths::claude_sessions();let found = find_claude(- util::parent_pid(),+ chain.first().copied().unwrap_or_else(util::parent_pid),std::env::var("CLAUDE_CODE_SESSION_ID").ok().as_deref(),std::env::var("CLAUDE_PID").ok().and_then(|s| s.parse().ok()),|p| registry_session_id(&dir, p),- parent_of,+ |p| chain.iter().position(|a| *a == p).and_then(|i| chain.get(i + 1).copied()),);- match found {- Some(pid) => {- let _ = PID.set(pid);- }- None => *MISSED.lock().unwrap() = Some(std::time::Instant::now()),+ if let Some(pid) = found {+ let _ = PID.set(pid);}found}-/// How long `claude_pid` goes by not having found the Claude process before it looks again.-const LOOK_AGAIN: std::time::Duration = std::time::Duration::from_secs(30);+/// Our parent and its ancestors, a few levels up: found once.+fn ancestors() -> &'static [u32] {+ static CHAIN: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();+ CHAIN.get_or_init(|| {+ let mut chain = vec![util::parent_pid()];+ while chain.len() < 5 {+ let last = *chain.last().expect("never empty");+ match parent_of(last) {+ Some(p) if p > 1 && !chain.contains(&p) => chain.push(p),+ _ => break,+ }+ }+ chain+ })+}/// The Claude Code process in conversation `given`: the nearest of `start` and its ancestors, else `claude_pid`, whose/// registry entry (`entry`) names it. None without a conversation to match.@@ -303,17 +311,33 @@ pub struct ClaudeSocket {pub token: Option<String>,}+/// The inbox of the Claude Code session we serve: the one Claude Code gave us (`CLAUDE_CODE_MESSAGING_SOCKET`, which it+/// sets once its inbox listens, having dropped any it inherited), else the one named by the registry entry of the+/// process in our conversation (`claude_pid`). Never another's: a headless Claude run from another's shell has no entry,+/// and a `CLAUDE_PID` it inherited would be the other session's. Then nothing is pushed, and mail waits for+/// `check_inbox`.pub fn claude_socket() -> Option<ClaudeSocket> {let token = std::env::var("CLAUDE_CODE_MESSAGING_TOKEN").ok().filter(|s| !s.is_empty());- if let Some(path) = std::env::var_os("CLAUDE_CODE_MESSAGING_SOCKET") {+ if let Some(path) = std::env::var_os("CLAUDE_CODE_MESSAGING_SOCKET").filter(|p| !p.is_empty()) {return Some(ClaudeSocket { path: path.into(), token });}- // Not exported to this process: fall back to the session's registry entry.- let pid = claude_pid().unwrap_or_else(agent_pid);- let file = paths::claude_sessions().join(format!("{pid}.json"));- let s: Value = serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()?;- let path = s["messagingSocketPath"].as_str()?;- Some(ClaudeSocket { path: path.into(), token: token.or_else(|| crate::claude::peer_token(pid)) })+ let pid = claude_pid()?;+ socket_of(&paths::claude_sessions(), pid, None, token, crate::claude::peer_token)+}++/// The inbox Claude Code process `pid`'s registry entry names, with its token: the one we were given, when that is for+/// this very inbox, else what Claude Code keeps for its peers.+fn socket_of(+ dir: &Path,+ pid: u32,+ given: Option<PathBuf>,+ given_token: Option<String>,+ peer_token: impl Fn(u32) -> Option<String>,+) -> Option<ClaudeSocket> {+ let s: Value = serde_json::from_str(&std::fs::read_to_string(dir.join(format!("{pid}.json"))).ok()?).ok()?;+ let path = PathBuf::from(s["messagingSocketPath"].as_str().filter(|p| !p.is_empty())?);+ let token = given_token.filter(|_| given.as_deref() == Some(path.as_path())).or_else(|| peer_token(pid));+ Some(ClaudeSocket { path, token })}pub fn post_to_claude(sock: &ClaudeSocket, text: &str) -> std::io::Result<()> {@@ -411,6 +435,36 @@ mod tests {assert_eq!(find_claude(900, None, Some(700), entry, parent), None);}+ #[test]+ fn a_headless_claude_pushes_nothing_into_the_session_it_was_run_from() {+ let dir = std::env::temp_dir().join(format!("reason-network-claude-{}", ulid::Ulid::generate()));+ std::fs::create_dir_all(&dir).unwrap();+ // The interactive Claude (700, in `outer`) and its inbox, which a headless Claude it runs (no entry, in+ // `inner`) may have inherited, with CLAUDE_PID=700.+ std::fs::write(+ dir.join("700.json"),+ r#"{"pid":700,"sessionId":"outer","messagingSocketPath":"/run/outer.sock"}"#,+ )+ .unwrap();+ let entry = |p: u32| registry_session_id(&dir, p);+ let parent = |p: u32| match p {+ 900 => Some(800),+ 800 => Some(700),+ _ => None,+ };+ // The headless one's server finds no process of its own: no inbox, whatever it inherited.+ assert_eq!(find_claude(900, Some("inner"), Some(700), entry, parent), None);+ // The interactive one's server gets its own inbox, with the token it was given for it.+ let pid = find_claude(900, Some("outer"), None, entry, parent).unwrap();+ let none = |_| None;+ let s = socket_of(&dir, pid, Some("/run/outer.sock".into()), Some("t".into()), none).unwrap();+ assert_eq!((s.path, s.token.as_deref()), (PathBuf::from("/run/outer.sock"), Some("t")));+ // A token that came with another inbox isn't this one's.+ let s = socket_of(&dir, pid, Some("/run/other.sock".into()), Some("t".into()), none).unwrap();+ assert_eq!(s.token, None);+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn a_parent_is_read_from_proc_stat() {assert_eq!(stat_parent("4242 (claude) S 4100 4242 4100 0 -1 4194560"), Some(4100));diff --git a/src/client.rs b/src/client.rsindex 13a788a..76cada6 100644--- a/src/client.rs+++ b/src/client.rs@@ -64,8 +64,9 @@ impl Link {Ok(r)}- pub fn is_registered(&self, key: &str) -> bool {- self.regs.lock().unwrap().contains_key(key)+ /// How a registered session was said to be reached.+ pub fn registered_tier(&self, key: &str) -> Option<Tier> {+ self.regs.lock().unwrap().get(key).map(|r| r.tier)}async fn raw(&self, conn: &Conn, req: &Request) -> Result<Value> {diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex b09e07c..69886cb 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -183,9 +183,12 @@ impl Daemon {super::log(&format!("adding the Claude session of process {}: {e:#}", c.pid));}}- // Seen alive just now (it goes when its process does).+ // Seen alive just now (it goes when its process does), and its inbox listed: it can be pushed into.if let Some(l) = self.inner.lock().unwrap().live.get_mut(&key) {l.last_hook = Some(now);+ if c.messaging_socket_path.is_some() && !l.push_failed {+ l.reg.tier = Tier::Push;+ }}}diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex d57e47c..2e50f49 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -326,14 +326,17 @@ impl Daemon {}let has = |bin: &str| !l.push_failed && agent::find_bin(bin).is_some();let channel = match (l.reg.tier, l.conn, &l.reg.agent_session_id) {- (Tier::Push, Some(conn), _) if l.reg.agent == agent::CLAUDE_CODE => Channel::ClaudeSocket(conn),+ // Its MCP server knows its inbox; else (it may not yet) the daemon posts into the one Claude Code lists.+ (Tier::Push, Some(conn), _) if l.reg.agent == agent::CLAUDE_CODE && l.mcp_push => {+ Channel::ClaudeSocket(conn)+ }(Tier::Push, _, Some(id)) if l.reg.agent == "codex" && has("codex") => {Channel::Command("codex", vec!["queue".into(), "--thread".into(), id.clone(), "--message".into()])}(Tier::Push, _, Some(id)) if l.reg.agent == "reason" && has("reason") => {Channel::Command("reason", vec!["session".into(), "send".into(), id.clone(), "--message".into()])}- (Tier::Push, None, id) if l.reg.agent == agent::CLAUDE_CODE && !l.push_failed => {+ (Tier::Push, _, id) if l.reg.agent == agent::CLAUDE_CODE && !l.push_failed => {match claude::socket_for(id.as_deref(), l.reg.pid) {Some(sock) => Channel::ClaudeDirect(sock),None => Channel::Pull,@@ -395,6 +398,22 @@ impl Daemon {}}+ /// A session's MCP server had no inbox to push `ids` into: they are unread again, for the session to read when it+ /// checks, and nothing is pushed through it until it registers knowing one (or Claude Code lists one to post into).+ pub(super) fn push_failed(&self, key: &str, ids: &[String]) {+ let mut g = self.inner.lock().unwrap();+ for id in ids {+ g.in_flight.remove(id);+ }+ if let Some(l) = g.live.get_mut(key) {+ l.mcp_push = false;+ l.reg.tier = l.reg.tier.max(Tier::Pull);+ }+ log(&format!("pushing to {}: its MCP server knows no inbox; left unread", self.logged(&g, key)));+ drop(g);+ self.arrived.notify_waiters();+ }+/// Posts into a Claude Code session's messaging socket; read once it took it.fn post_direct(self: &Arc<Self>, key: String, sock: agent::ClaudeSocket, ids: Vec<String>, text: String) {let this = self.clone();@@ -926,6 +945,50 @@ mod tests {);}+ #[tokio::test]+ async fn a_claude_session_is_told_delivered_only_through_a_server_that_knows_its_inbox() {+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));+ d.register(Some(1), codex("codex:1"), crate::git::GitInfo::default()).unwrap();+ // Claude Code's MCP server, connected, before Claude Code has listed its inbox.+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ d.inner.lock().unwrap().conns.insert(7, tx);+ let claude = |tier| SessionReg {+ key: "claude-code:a".into(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/web".into(),+ agent_session_id: None,+ pid: None,+ tier,+ name: None,+ };+ let to = d.register(Some(7), claude(Tier::Pull), crate::git::GitInfo::default()).unwrap().address;+ let send = |body: &'static str| d.send("codex:1".into(), &to, body, None, true, false, None, Vec::new());+ let r = send("one").await.unwrap();+ assert_eq!((r.recipients[0].state.as_str(), rx.try_recv().is_err()), ("queued", true));+ // Its inbox has turned up: the server registers again, as push; what waited, and the next, go through it.+ d.register(Some(7), claude(Tier::Push), crate::git::GitInfo::default()).unwrap();+ let r = send("two").await.unwrap();+ assert_eq!(r.recipients[0].state, "pushed");+ let mut pushed = Vec::new();+ while let Ok(line) = rx.try_recv() {+ let Event::Deliver { ids, .. } = serde_json::from_str(&line).unwrap();+ pushed.extend(ids);+ }+ assert_eq!(pushed.len(), 2);+ // The server finds it can't after all: unread again, and not pushed through it any more.+ let key = "claude-code:a".to_string();+ d.push_failed(&key, &pushed);+ {+ let g = d.inner.lock().unwrap();+ assert!(g.in_flight.is_empty());+ assert!(!g.live[&key].mcp_push);+ }+ let unread: Vec<String> = d.inner.lock().unwrap().pending(&to).unwrap().into_iter().map(|m| m.body).collect();+ assert_eq!(unread, ["one", "two"]);+ let r = send("three").await.unwrap();+ assert_eq!((r.recipients[0].state.as_str(), rx.try_recv().is_err()), ("queued", true));+ }+#[test]fn a_peers_message_id_is_a_ulid_as_written() {let msg = |id: &str| Message {diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 41503f6..dfca248 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -165,6 +165,8 @@ struct Live {retry: Option<(Instant, Duration)>,/// Bumped to end this session's `check_inbox` wait (its client gave up on it).stop_gen: u64,+ /// Its MCP connection pushes into it (it registered as `push`, knowing the agent's inbox). Claude Code's only.+ mcp_push: bool,/// It could be reached beyond its own hooks: an MCP server connected for it or attached a call to it, a push channel/// delivers into it (Claude Code's inbox, `codex queue`, the opencode and pi plugins, Reason), or it is one of the/// person's own mailboxes. Only such a session keeps its name while offline: a run only its hooks ever saw (a@@ -325,6 +327,10 @@ impl Daemon {}Value::Null}+ Request::PushFailed { key, ids } => {+ self.push_failed(&key, &ids);+ Value::Null+ }Request::Hook(h) => json!(self.hook(h).await?),Request::Attach { agent, cwd } => json!(self.attach(&agent, &cwd)?),Request::CreateTeam { name, person, relay, proof } => {diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex b359951..e8b83d5 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -85,6 +85,7 @@ impl Daemon {if conn.is_some() {l.conn = conn;l.attached = true;+ l.mcp_push = reg.tier == Tier::Push;}l.reg.tier = if l.push_failed { l.reg.tier.max(Tier::Turn) } else { l.reg.tier.min(reg.tier) };l.attached |= l.reg.tier == Tier::Push;@@ -97,9 +98,10 @@ impl Daemon {if conn.is_none() {reg.tier = reg.tier.min(self.hook_tier(®.agent, false));}- let name = pick_name(g, ®, &git, &others, |r| self.holds(r, now))?;+ let name = pick_name(g, ®, &git, &others, &self.person, |r| self.holds(r, now))?;self.take_over(g, &name, &key)?;let attached = conn.is_some() || reg.tier == Tier::Push || reg.agent == "cli";+ let mcp_push = conn.is_some() && reg.tier == Tier::Push;g.live.insert(key.clone(),Live {@@ -116,6 +118,7 @@ impl Daemon {retry: None,stop_gen: 0,attached,+ mcp_push,},);self.presence_changed();@@ -141,6 +144,11 @@ impl Daemon {/// it registered now. (Checked as the terminal is used: each command from it comes through here.) A rename that/// fails (another session took the name meanwhile) is logged, and the command goes on: it is tried again next time.fn recheck_terminal(&self, others: &Elsewhere) {+ self.recheck_terminal_with(others, |name| self.set_status(TERMINAL, None, Some(name)).map(drop));+ }++ /// `recheck_terminal`, renaming with `rename`.+ fn recheck_terminal_with(&self, others: &Elsewhere, rename_to: impl FnOnce(String) -> Result<()>) {let now = util::now_ms();let rename = || -> Result<()> {let name = {@@ -149,14 +157,13 @@ impl Daemon {if others.terminals || !others.live.contains(&l.name) {return Ok(());}- pick_name(&g, &l.reg, &l.git, others, |r| self.holds(r, now))?+ pick_name(&g, &l.reg, &l.git, others, &self.person, |r| self.holds(r, now))?};log(&format!("{} is on another machine too, and an older engine is in the team: now {name}",self.addr("terminal")));- self.set_status(TERMINAL, None, Some(name))?;- Ok(())+ rename_to(name)};if let Err(e) = rename() {log(&format!("renaming {}: {e:#}", self.addr("terminal")));@@ -542,13 +549,16 @@ fn pick_name(reg: &SessionReg,git: &GitInfo,elsewhere: &Elsewhere,+ person: &str,holds: impl Fn(&Remembered) -> bool,) -> Result<String> {// A machine's own `terminal` is its own: another machine's never makes it take a suffix, once every engine in the// team shows which machine a terminal's message came from. (An older one couldn't tell two apart in a reply.)let none = Elsewhere::default();let elsewhere = if reg.key == TERMINAL && elsewhere.terminals { &none } else { elsewhere };- let live = |n: &str| g.live.iter().any(|(k, l)| l.name == n && *k != reg.key) || elsewhere.live.contains(n);+ // The person's own name is never a session's (`<person>/<person>` would read as the person), as for a rename.+ let live =+ |n: &str| n == person || g.live.iter().any(|(k, l)| l.name == n && *k != reg.key) || elsewhere.live.contains(n);let free = |n: &str| -> Result<bool> {let kept_here = g.store.session_by_name(n)?.is_some_and(|r| r.key != reg.key && holds(&r));Ok(!live(n) && !kept_here && !elsewhere.kept.contains(n))@@ -850,7 +860,7 @@ mod tests {Elsewhere { live: HashSet::from(["api-claude".to_string()]), kept: HashSet::new(), terminals: true };let mut g = d.inner.lock().unwrap();let g = &mut *g;- let name = pick_name(g, &claude("a"), &GitInfo::default(), &elsewhere, |_| true).unwrap();+ let name = pick_name(g, &claude("a"), &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap();assert_eq!(name, "api-claude-2");let r = Remembered {name: name.clone(),@@ -878,7 +888,10 @@ mod tests {terminals: true,};let g = d.inner.lock().unwrap();- assert_eq!(pick_name(&g, &claude("c"), &GitInfo::default(), &elsewhere, |_| true).unwrap(), "api-claude-3");+ assert_eq!(+ pick_name(&g, &claude("c"), &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap(),+ "api-claude-3"+ );}#[test]@@ -1167,13 +1180,12 @@ mod tests {#[tokio::test]async fn a_terminal_rename_that_fails_never_fails_the_command() {- // The name the terminal would move to can't be had (here: it is the person's own name).- let cfg = crate::config::Config { person: Some("terminal-2".into()), ..Default::default() };- let d = Arc::new(super::super::test_daemon(cfg));+ let d = Arc::new(super::super::test_daemon(Default::default()));assert_eq!(join(&d, named(TERMINAL, "cli", Some("terminal"))).name, "terminal");let others =Elsewhere { live: HashSet::from(["terminal".to_string()]), terminals: false, ..Default::default() };- d.recheck_terminal(&others);+ // The rename loses a race: another session took the name it picked meanwhile.+ d.recheck_terminal_with(&others, |name| bail!("'{name}' is taken by a live session"));assert_eq!(d.inner.lock().unwrap().live[TERMINAL].name, "terminal");// The terminal's commands go on as before.let call = HookCall {@@ -1191,6 +1203,29 @@ mod tests {assert_eq!(d.hook(call).await.unwrap().address, Some(d.addr("terminal")));}+ #[test]+ fn no_session_is_named_after_its_person() {+ let d = super::super::test_daemon(crate::config::Config { person: Some("lars".into()), ..Default::default() });+ // `listen --as lars`, and a Claude Code session someone named Lars.+ assert_eq!(join(&d, named("cli:lars", "cli", Some("lars"))).name, "lars-2");+ assert_eq!(join(&d, SessionReg { name: Some("Lars".into()), ..claude("a") }).name, "lars-3");+ // Nor a session coming back to such a name an older engine gave it.+ let r = Remembered {+ name: "lars".into(),+ key: "claude-code:old".into(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/api".into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Push,+ last_seen: util::now_ms(),+ attached: true,+ };+ d.inner.lock().unwrap().store.upsert_session(&r, &d.person).unwrap();+ assert_eq!(join(&d, claude("old")).name, "api-claude");+ }+#[test]fn each_machine_has_its_own_terminal() {let d = super::super::test_daemon(Default::default());@@ -1202,14 +1237,17 @@ mod tests {let g = d.inner.lock().unwrap();let terminal = named(TERMINAL, "cli", Some("terminal"));// While an older engine in the team couldn't tell two apart in a reply, the second one on is `terminal-2`.- assert_eq!(pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal-2");+ assert_eq!(+ pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap(),+ "terminal-2"+ );elsewhere.terminals = true;- assert_eq!(pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal");+ assert_eq!(pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap(), "terminal");// Any other session asking for it, or for a name kept elsewhere, still gets the next free one.let other = named("cli:t2", "cli", Some("terminal"));- assert_eq!(pick_name(&g, &other, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal-2");+ assert_eq!(pick_name(&g, &other, &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap(), "terminal-2");let review = named("cli:review", "cli", Some("review"));- assert_eq!(pick_name(&g, &review, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "review-2");+ assert_eq!(pick_name(&g, &review, &GitInfo::default(), &elsewhere, &d.person, |_| true).unwrap(), "review-2");}#[test]diff --git a/src/mcp.rs b/src/mcp.rsindex 7bd5cfc..77b3b22 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -87,7 +87,8 @@ pub struct InboxArgs {pub struct ReasonNetworkMcp {link: Arc<Link>,env_agent: Option<&'static str>,- claude: Option<Arc<ClaudeSocket>>,+ /// The inbox of the Claude Code session we serve, once known (see [`agent::claude_socket`]).+ claude: Arc<Mutex<Option<Arc<ClaudeSocket>>>>,/// The agent named by the client's `clientInfo`, once known.client_agent: Arc<Mutex<Option<&'static str>>>,tool_router: ToolRouter<Self>,@@ -98,7 +99,7 @@ pub async fn run() -> Result<()> {let server = ReasonNetworkMcp {link: Link::new(Some(tx)),env_agent: agent::detect_env(),- claude: agent::claude_socket().map(Arc::new),+ claude: Default::default(),client_agent: Default::default(),tool_router: ReasonNetworkMcp::tool_router(),};@@ -265,9 +266,19 @@ impl ServerHandler for ReasonNetworkMcp {}impl ReasonNetworkMcp {+ /// Our Claude Code session's inbox: looked for until found (Claude Code may write its registry entry after it starts+ /// us), then kept.+ fn claude(&self) -> Option<Arc<ClaudeSocket>> {+ let mut known = self.claude.lock().unwrap();+ if known.is_none() {+ *known = agent::claude_socket().map(Arc::new);+ }+ known.clone()+ }+/// Whether messages reach this session by being pushed into it: Claude Code, through its inbox.fn pushed(&self, agent: &str) -> bool {- agent == agent::CLAUDE_CODE && self.claude.is_some()+ agent == agent::CLAUDE_CODE && self.claude().is_some()}/// The agent we serve: the client's `clientInfo` (handshake, or the call's `_meta` on handshake-less@@ -311,10 +322,11 @@ impl ReasonNetworkMcp {Some(id) => format!("{agent}:{id}"),None => format!("proc:{}", std::process::id()),};- if self.link.is_registered(&key) {+ let tier = if self.pushed(agent) { Tier::Push } else { Tier::Pull };+ // Registered already, unless its inbox has turned up since (Claude Code may list it after starting us).+ if self.link.registered_tier(&key).is_some_and(|t| t == Tier::Push || tier != Tier::Push) {return Ok(key);}- let tier = if self.pushed(agent) { Tier::Push } else { Tier::Pull };let reg = SessionReg {key: key.clone(),agent: agent.to_string(),@@ -361,7 +373,11 @@ impl ReasonNetworkMcp {async fn on_event(&self, ev: Event) {let Event::Deliver { key, ids, text } = ev;- let Some(sock) = self.claude.clone() else { return };+ // No inbox to put it in: the daemon takes it back, and doesn't push here again until there is one.+ let Some(sock) = self.claude() else {+ let _ = self.link.call::<Value>(Request::PushFailed { key, ids }).await;+ return;+ };match tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await {Ok(Ok(())) => {let _ = self.link.call::<Value>(Request::Delivered { key, ids }).await;diff --git a/src/proto.rs b/src/proto.rsindex 37b1cb6..73521bd 100644--- a/src/proto.rs+++ b/src/proto.rs@@ -150,6 +150,12 @@ pub enum Request {key: String,ids: Vec<String>,},+ /// The client couldn't push these messages into its agent's conversation (it knows no inbox for it): they stay+ /// unread.+ PushFailed {+ key: String,+ ids: Vec<String>,+ },/// An agent hook fired (`reason network hook`): keeps hook-only sessions alive and returns mail to inject.Hook(HookCall),/// For agents whose MCP calls carry no session id (Cursor, opencode): the hook-known session of this agentdiff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.pyindex 53325c8..00eb053 100644--- a/tests/e2e/hooks.py+++ b/tests/e2e/hooks.py@@ -314,6 +314,73 @@ hc.kill()cc.kill()claude_proc.kill()+# Pushing through Claude Code's MCP server, whenever Claude Code lists its inbox in its registry: before the server+# starts, after its first tool call, or right after `tools/list` (the call at once, or 3 s later). Every message is+# either put into the inbox or left unread, and the sender is told which.+def push_case(name, when):+ proj = os.path.join(D, f"push-{name}")+ os.makedirs(proj)+ sock = os.path.join(D, f"p{name[:2]}.sock")+ frames = []+ srv = socket.socket(socket.AF_UNIX)+ srv.bind(sock)+ srv.listen(8)+ def serve_inbox():+ while True:+ c, _ = srv.accept()+ frames.append(c.makefile().read())+ threading.Thread(target=serve_inbox, daemon=True).start()+ proc = subprocess.Popen(["sleep", "300"])+ sid = f"push-{name}"+ def list_inbox():+ with open(os.path.join(CLAUDE, "sessions", f"{proc.pid}.json"), "w") as f:+ json.dump({"pid": proc.pid, "sessionId": sid, "cwd": proj, "kind": "interactive", "messagingSocketPath": sock}, f)+ if when == "before":+ list_inbox()+ p = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ env=dict(env, CLAUDE_PID=str(proc.pid), CLAUDE_CODE_SESSION_ID=sid), cwd=proj, text=True)+ rpc(p, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "claude-code", "version": "1"}}})+ reply(p, 1)+ rpc(p, {"jsonrpc": "2.0", "method": "notifications/initialized"})+ rpc(p, {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}})+ reply(p, 2)+ if when.startswith("after-list"):+ list_inbox()+ if when == "after-list-later":+ time.sleep(3)+ rpc(p, {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "list_team", "arguments": {}}})+ reply(p, 3)+ if when == "after-call":+ list_inbox()+ to = f"push-{name}-claude"+ sent = {}+ for i in range(2):+ body = f"push {name} {i}"+ sent[body] = run("send", to, body)+ time.sleep(3)+ time.sleep(2)+ got = "".join(frames)+ rpc(p, {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "check_inbox", "arguments": {}}})+ unread = json.dumps(reply(p, 4))+ for body, out in sent.items():+ # Told it was delivered, it is in the inbox. Told it was queued, it is unread, or went in once the inbox was+ # known: never lost, never claimed.+ told_delivered = "delivered into the session" in out+ check(f"push, inbox listed {when}: '{body}' reached the session as the sender was told ({'delivered' if told_delivered else 'queued'})",+ (body in got) if told_delivered else ("queued" in out and (body in unread) != (body in got)),+ f"send said: {out}\ninbox got: {got[-400:]}\nunread: {unread[-400:]}")+ # Once Claude Code has listed it, the inbox is used.+ body = f"push {name} last"+ out = run("send", to, body)+ time.sleep(2)+ check(f"push, inbox listed {when}: once listed, mail goes into it", "delivered into the session" in out and body in "".join(frames),+ out + "".join(frames)[-300:])+ p.kill()+ proc.kill()++for name, when in [("b", "before"), ("c", "after-call"), ("n", "after-list-now"), ("l", "after-list-later")]:+ push_case(name, when)+# An agent's MCP server outlives daemon restarts without collecting zombies or storming restarts.mcp = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)time.sleep(4)