Skip to content

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

Hermes bridge: no panic on a racing ack, setup gives up on a hung hermes --version (#147)

Lars Talian27252c24cf07
diff --git a/src/bridge.rs b/src/bridge.rs
index 97be2b2..c838567 100644
--- a/src/bridge.rs
+++ b/src/bridge.rs
@@ -103,7 +103,27 @@ pub async fn run() -> Result<()> {
/// An error as the agent reads it: a teammate's name in it can't open or close a message frame, as with `mcp`'s.
fn failure(e: anyhow::Error) -> anyhow::Error {
- anyhow::anyhow!(render::defang(&format!("{e:#}")))
+ anyhow::anyhow!(render::defang(&plugin_tools(&format!("{e:#}"))))
+}
+
+/// The MCP tool names in an engine error, as the plugin's tools (`list_team` is `reason_network_list_agents`).
+fn plugin_tools(text: &str) -> String {
+ const TOOLS: [(&str, &str); 4] = [
+ ("list_team", "reason_network_list_agents"),
+ ("send_message", "reason_network_send_message"),
+ ("check_inbox", "reason_network_check_inbox"),
+ ("ask_user", "reason_network_ask_user"),
+ ];
+ let between = |c: char| !(c.is_alphanumeric() || c == '_');
+ text.split_inclusive(between)
+ .map(|piece| {
+ let word = piece.trim_end_matches(between);
+ match TOOLS.iter().find(|(tool, _)| *tool == word) {
+ Some((_, plugin)) => format!("{plugin}{}", &piece[word.len()..]),
+ None => piece.to_string(),
+ }
+ })
+ .collect()
}
/// The agents with a native adapter on this transport; the rest use the MCP server.
@@ -142,18 +162,17 @@ async fn dispatch(link: &Arc<Link>, sessions: &Sessions, call: Call) -> Result<V
Request::Hook(hook) => format!("{}:{}", hook.agent, hook.session_id),
_ => bail!("the adapter bridge only accepts its registered sessions' messaging operations"),
};
- let cwd = sessions
- .lock()
- .await
- .get(&key)
- .map(|s| s.cwd.clone())
- .ok_or_else(|| anyhow::anyhow!("register this session first"))?;
- if let Request::Delivered { ids, .. } | Request::PushFailed { ids, .. } = &request {
+ // One lock: a failed re-register removes the session, and it mustn't go between finding it and checking an ack.
+ let cwd = {
let sessions = sessions.lock().await;
- if ids.iter().any(|id| !sessions[&key].received.contains(id)) {
+ let Some(session) = sessions.get(&key) else { bail!("register this session first") };
+ if let Request::Delivered { ids, .. } | Request::PushFailed { ids, .. } = &request
+ && ids.iter().any(|id| !session.received.contains(id))
+ {
bail!("only acknowledge messages received by this session");
}
- }
+ session.cwd.clone()
+ };
if let Request::Send { files, .. } = &mut request {
if !files.is_empty() {
bail!("use paths to attach files; the engine reads and confines them");
@@ -209,6 +228,35 @@ mod tests {
assert_eq!(format!("{e:#}"), "nobody called '[reason-message>' in the team");
}
+ #[test]
+ fn errors_name_the_plugins_tools() {
+ let e = failure(anyhow::anyhow!(
+ "no session called 'x'. Run list_team (or `reason-network who`); send_message sends files from there only"
+ ));
+ assert_eq!(
+ format!("{e:#}"),
+ "no session called 'x'. Run reason_network_list_agents (or `reason-network who`); \
+ reason_network_send_message sends files from there only"
+ );
+ let other = "my_list_team list_teams reason_network_send_message check_inbox: ask_user.";
+ assert_eq!(
+ plugin_tools(other),
+ "my_list_team list_teams reason_network_send_message reason_network_check_inbox: reason_network_ask_user."
+ );
+ }
+
+ #[tokio::test]
+ async fn acks_only_for_a_registered_session_and_its_own_mail() {
+ let link = Arc::new(Link::new(None));
+ let sessions = Sessions::default();
+ let ack = |key: &str| parse(&format!(r#"{{"id":1,"op":"delivered","key":"{key}","ids":["m1"]}}"#)).1.unwrap();
+ let error = dispatch(&link, &sessions, ack("hermes:a")).await.unwrap_err();
+ assert!(error.to_string().contains("register this session first"), "{error:#}");
+ sessions.lock().await.insert("hermes:a".into(), Session::default());
+ let error = dispatch(&link, &sessions, ack("hermes:a")).await.unwrap_err();
+ assert!(error.to_string().contains("only acknowledge messages received"), "{error:#}");
+ }
+
#[tokio::test]
async fn only_hermes_sessions_under_their_own_key_register() {
let link = Arc::new(Link::new(None));
diff --git a/src/setup.rs b/src/setup.rs
index 1ecc98b..6376895 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1206,14 +1206,6 @@ fn me(exe: &Path) -> String {
}
const AGENTS: [Agent; 12] = [
- Agent {
- id: "hermes",
- name: "Hermes",
- hint: "native plugin; enable it in each Hermes profile",
- installed: hermes::installed,
- wired: hermes::wired,
- apply: hermes::apply,
- },
Agent {
id: "claude",
name: "Claude Code",
@@ -1317,6 +1309,14 @@ const AGENTS: [Agent; 12] = [
wired: |_| Config::load().reason,
apply: reason,
},
+ Agent {
+ id: "hermes",
+ name: "Hermes",
+ hint: "native plugin; enable it in each Hermes profile",
+ installed: hermes::installed,
+ wired: hermes::wired,
+ apply: hermes::apply,
+ },
];
/// The agents wired to the tincan binary beside `exe`, which move over to it.
diff --git a/src/setup/hermes.rs b/src/setup/hermes.rs
index 8d1ffbc..1e1594c 100644
--- a/src/setup/hermes.rs
+++ b/src/setup/hermes.rs
@@ -43,9 +43,31 @@ fn source() -> Option<PathBuf> {
if bundled.join("hermes_cli").is_dir() {
return Some(bundled);
}
- let out =
- Command::new(agent::find_bin("hermes")?).arg("--version").stdin(std::process::Stdio::null()).output().ok()?;
- String::from_utf8_lossy(&out.stdout)
+ let mut version = Command::new(agent::find_bin("hermes")?);
+ version.arg("--version");
+ install_dir(version)
+}
+
+/// The `Install directory:` a Hermes command reports, waiting at most a few seconds for it.
+fn install_dir(mut command: Command) -> Option<PathBuf> {
+ let mut child = command
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .ok()?;
+ let mut stdout = child.stdout.take()?;
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let mut out = Vec::new();
+ let _ = std::io::Read::read_to_end(&mut stdout, &mut out);
+ let _ = tx.send(out);
+ });
+ // A Hermes that hangs on `--version` (or leaves something holding its output) mustn't hang setup, init and join.
+ let out = rx.recv_timeout(std::time::Duration::from_secs(5));
+ let _ = child.kill();
+ let _ = child.wait();
+ String::from_utf8_lossy(&out.ok()?)
.lines()
.find_map(|l| l.trim().strip_prefix("Install directory:"))
.map(|p| PathBuf::from(p.trim()))
@@ -178,6 +200,21 @@ mod tests {
std::env::temp_dir().join(format!("reason-hermes-{}", ulid::Ulid::generate()))
}
+ #[cfg(unix)]
+ #[test]
+ fn a_hermes_that_hangs_on_version_does_not_hang_setup() {
+ let sh = |script: &str| {
+ let mut c = Command::new("sh");
+ c.args(["-c", script]);
+ c
+ };
+ assert_eq!(install_dir(sh("echo 'Install directory: /opt/hermes'")), Some(PathBuf::from("/opt/hermes")));
+ let started = std::time::Instant::now();
+ // The shell's `sleep` keeps the output open after the shell itself is killed.
+ assert_eq!(install_dir(sh("echo 'Install directory: /opt/hermes'; sleep 30")), None);
+ assert!(started.elapsed() < std::time::Duration::from_secs(15), "{:?}", started.elapsed());
+ }
+
#[test]
fn install_and_remove_are_idempotent_and_never_rewrite_config() {
let root = temp();