Skip to content

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

Address review: keep grok from losing mail

watarus7fefb86d97ac
diff --git a/DESIGN.md b/DESIGN.md
index 135614b..270554b 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -139,12 +139,12 @@ session connection also receives pushed `deliver` events for its sessions.
**Session registration**, by priority:
1. Per-call `_meta`: Codex `sessionId` (the root thread, same id its hooks see), opencode V2 `ai.opencode/sessionID`.
-2. Env: `CLAUDE_CODE_SESSION_ID` (Claude), `COPILOT_AGENT_SESSION_ID` (Copilot).
+2. Env: `CLAUDE_CODE_SESSION_ID` (Claude), `COPILOT_AGENT_SESSION_ID` (Copilot), `GROK_SESSION_ID` (Grok).
3. Hook stdin `session_id` (`SessionStart`), correlated to the MCP process by agent PID ancestry.
4. Fallback: one session per MCP process.
Agent kind comes from MCP `clientInfo.name` plus env (`CLAUDECODE`, `CODEX_*`, `GEMINI_CLI`,
-`CURSOR_AGENT`, `OPENCODE`, `COPILOT_CLI`).
+`CURSOR_AGENT`, `OPENCODE`, `COPILOT_CLI`, `GROK_SESSION_ID`).
**Passive discovery.** Claude Code writes every live session to `~/.claude/sessions/<pid>.json` (name, cwd,
busy/idle). The daemon reads these, so Claude sessions show up with live busy/idle status even without our
@@ -169,7 +169,7 @@ The hard part. Each session advertises a **delivery tier** so senders know when
| Cursor | turn | `postToolUse` `additional_context`; `stop` `followup_message`. Idle: background `reason-network wait`. |
| Gemini CLI | turn | `AfterTool` `additionalContext`; `AfterAgent` block. Idle: experimental background-shell inject. |
| Copilot CLI | turn | `postToolUse` `additionalContext`; `agentStop` block; `notification` hook. |
-| Grok CLI | turn | `PostToolUse` `additionalContext`; `Stop` block. Prompt-submit output is dropped. |
+| Grok CLI | turn | `PostToolUse` `additionalContext`; `Stop` (`end_turn`) block. SessionStart and prompt-submit output are dropped; subagents' hooks are ignored. |
| any MCP client | pull | Tools + unread notice on every tool result + `check_inbox(wait_secs)` long-poll. |
MCP notifications are not a delivery path: no client passes them to the model (checked Oct 2026).
@@ -244,7 +244,7 @@ With Reason, `reason network` does all of it: the workspace is the team.
`join`/`init` run `setup`, which detects installed agents and wires each one (backing up every file it
edits): Claude Code plugin or `claude mcp add --scope user` + hooks, `~/.codex/config.toml` + `hooks.json`,
`~/.cursor/mcp.json` + `hooks.json`, `~/.gemini/settings.json`, opencode plugin + MCP, Copilot
-`mcp-config.json` + hooks. Or paste one line into any agent: "install Reason Network and join cm1…".
+`mcp-config.json` + hooks, `~/.grok/config.toml` + `hooks/reason-network.json`. Or paste one line into any agent: "install Reason Network and join cm1…".
## Milestones
diff --git a/README.md b/README.md
index 2ec2c26..c633f1a 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,7 @@ trust the new hooks.
messages can't be pushed, under the MCP server `reason-network`. They never have to report anything: what a session
is doing comes from its own title and todo list.
- **Messages land right away.** Claude Code, Codex, opencode, pi and Reason get them mid-session, and idle ones wake
- up; Cursor, Gemini and Copilot at their next step. Claude sessions you already had open join without a restart.
+ up; Cursor, Gemini, Copilot and Grok at their next step. Claude sessions you already had open join without a restart.
- **A tap on the shoulder when it matters.** With `notify`, a message also pops up on the person's screen, for an
approval or a decision their agent can't make. Agents can reach their own user that way too. (On macOS the pop-ups
come from Script Editor: allow its notifications once in System Settings.)
diff --git a/src/agent.rs b/src/agent.rs
index f0a94a1..17d720b 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -168,6 +168,7 @@ pub fn short(agent: &str) -> &str {
pub fn label(agent: &str) -> &str {
match agent {
"codex" => "Codex",
+ "grok" => "Grok",
"reason" => "Reason",
a => a,
}
diff --git a/src/hook.rs b/src/hook.rs
index de8794c..31b2b58 100644
--- a/src/hook.rs
+++ b/src/hook.rs
@@ -50,6 +50,9 @@ async fn handle(
let v: Value = serde_json::from_str(input.trim_start_matches('\u{feff}')).unwrap_or(Value::Null);
let agent = agent::from_client_name(agent_name).unwrap_or(agent_name);
let str_at = |k: &str| v.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string);
+ if agent == "grok" && grok_ignores(event, &v) {
+ return None;
+ }
let session_id = session
.or_else(|| str_at("session_id"))
@@ -72,9 +75,7 @@ async fn handle(
("doing", _) => "doing",
_ => return None,
};
- // Prompt-submit hooks in Cursor, Copilot and grok can't add context, and opencode's status call shows nothing.
- let mail =
- !matches!((agent, event), ("cursor" | "copilot" | "grok", "user-prompt-submit") | (_, "status" | "doing"));
+ let mail = takes_mail(agent, event);
let key = format!("{agent}:{session_id}");
let req = Request::Hook(HookCall {
@@ -103,6 +104,21 @@ async fn handle(
Some((format_for(agent, event, ev, &text), key, ids))
}
+/// Prompt-submit hooks in Cursor, Copilot and grok can't add context, grok drops what SessionStart prints, and
+/// opencode's status call shows nothing.
+fn takes_mail(agent: &str, event: &str) -> bool {
+ !matches!(
+ (agent, event),
+ ("cursor" | "copilot" | "grok", "user-prompt-submit") | ("grok", "session-start") | (_, "status" | "doing")
+ )
+}
+
+/// grok runs a subagent's hooks under the subagent's own session id, and after SessionEnd fires one more Stop
+/// (reason "shutdown" or "channel_closed") whose block it ignores.
+fn grok_ignores(event: &str, v: &Value) -> bool {
+ !v["subagentType"].is_null() || (event == "stop" && v["reason"] != "end_turn")
+}
+
/// The JSON (or text) each agent expects from this hook to put `text` in front of the model.
fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {
let specific = |name: &str| json!({ "hookSpecificOutput": { "hookEventName": name, "additionalContext": text } });
@@ -112,7 +128,6 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {
("codex", "start") => specific("SessionStart"),
("codex", "prompt") => specific("UserPromptSubmit"),
("codex", "tool") => specific("PostToolUse"),
- ("grok", "start") => specific("SessionStart"),
("grok", "tool") => specific("PostToolUse"),
("gemini", "start") => specific("SessionStart"),
("gemini", "prompt") => specific("BeforeAgent"),
@@ -142,7 +157,8 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {
#[cfg(test)]
mod tests {
- use super::format_for;
+ use super::{format_for, grok_ignores, takes_mail};
+ use serde_json::json;
#[test]
fn formats() {
@@ -153,8 +169,22 @@ mod tests {
assert_eq!(format_for("copilot", "session-start", "start", "hi"), r#"{"additionalContext":"hi"}"#);
assert!(format_for("gemini", "user-prompt-submit", "prompt", "hi").contains("BeforeAgent"));
assert!(format_for("grok", "post-tool-use", "tool", "hi").contains("\"PostToolUse\""));
- assert!(format_for("grok", "session-start", "start", "hi").contains("\"SessionStart\""));
assert_eq!(format_for("grok", "stop", "stop", "hi"), r#"{"decision":"block","reason":"hi"}"#);
assert_eq!(format_for("opencode", "poll", "stop", "hi"), "hi");
}
+
+ #[test]
+ fn grok_payloads() {
+ assert!(!takes_mail("grok", "session-start"));
+ assert!(!takes_mail("grok", "user-prompt-submit"));
+ assert!(takes_mail("grok", "post-tool-use"));
+ assert!(takes_mail("grok", "stop"));
+ assert!(takes_mail("codex", "session-start"));
+ assert!(!grok_ignores("stop", &json!({ "reason": "end_turn" })));
+ assert!(grok_ignores("stop", &json!({ "reason": "shutdown" })));
+ assert!(grok_ignores("stop", &json!({ "reason": "channel_closed" })));
+ assert!(!grok_ignores("session-end", &json!({ "reason": "shutdown" })));
+ assert!(!grok_ignores("post-tool-use", &json!({ "subagentType": null })));
+ assert!(grok_ignores("post-tool-use", &json!({ "subagentType": "general-purpose" })));
+ }
}
diff --git a/src/setup.rs b/src/setup.rs
index 2eac1f2..8079cd1 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -354,7 +354,7 @@ fn codex(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
// ---- Grok CLI ----
fn grok_home() -> PathBuf {
- std::env::var_os("GROK_HOME").map(PathBuf::from).unwrap_or_else(|| home().join(".grok"))
+ std::env::var_os("GROK_HOME").filter(|h| !h.is_empty()).map(PathBuf::from).unwrap_or_else(|| home().join(".grok"))
}
/// grok reads the MCP server from `config.toml` and Claude-Code-style hook groups from `hooks/*.json` (global hook
@@ -392,6 +392,7 @@ fn grok(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
t["tool_timeout_sec"] = toml_edit::value(660);
servers[AGENT_NAME] = toml_edit::Item::Table(t);
}
+ grok_allow(&mut doc, remove);
r.lines.push(changed(&cfg_path, write_file(&cfg_path, &doc.to_string(), dry)?));
let hooks_path = dir.join(format!("hooks/{AGENT_NAME}.json"));
@@ -426,6 +427,32 @@ fn grok(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
Ok(Some(r))
}
+/// grok asks before every MCP tool call unless a rule allows it.
+fn grok_allow(doc: &mut toml_edit::DocumentMut, remove: bool) {
+ let rule = format!("MCPTool({AGENT_NAME}__*)");
+ if remove {
+ if let Some(permission) = doc.get_mut("permission").and_then(|p| p.as_table_like_mut()) {
+ if let Some(allow) = permission.get_mut("allow").and_then(|a| a.as_array_mut()) {
+ allow.retain(|v| v.as_str() != Some(rule.as_str()));
+ if allow.is_empty() {
+ permission.remove("allow");
+ }
+ }
+ if permission.is_empty() {
+ doc.remove("permission");
+ }
+ }
+ return;
+ }
+ let allow = doc.entry("permission").or_insert(toml_edit::table())["allow"]
+ .or_insert(toml_edit::value(toml_edit::Array::new()));
+ if let Some(allow) = allow.as_array_mut()
+ && !allow.iter().any(|v| v.as_str() == Some(rule.as_str()))
+ {
+ allow.push(rule);
+ }
+}
+
// ---- Cursor ----
fn cursor(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
@@ -1278,6 +1305,21 @@ pub async fn doctor() -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn grok_allow_rule() {
+ let mut doc: toml_edit::DocumentMut = "[permission]\nallow = [\"Bash(ls)\"]\n".parse().unwrap();
+ grok_allow(&mut doc, false);
+ grok_allow(&mut doc, false);
+ assert_eq!(doc.to_string(), "[permission]\nallow = [\"Bash(ls)\", \"MCPTool(reason-network__*)\"]\n");
+ grok_allow(&mut doc, true);
+ assert_eq!(doc.to_string(), "[permission]\nallow = [\"Bash(ls)\"]\n");
+ let mut doc = toml_edit::DocumentMut::new();
+ grok_allow(&mut doc, false);
+ assert!(doc.to_string().contains("MCPTool(reason-network__*)"));
+ grok_allow(&mut doc, true);
+ assert_eq!(doc.to_string(), "");
+ }
+
#[test]
fn hook_groups_merge_and_remove() {
let mut hooks = serde_json::from_value::<Map<String, Value>>(json!({