Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

A3c: raea hook hands an agent what the person sent from the raea app, after any tool and as its turn ends

shinyobjectz76a11076ead8
diff --git a/Cargo.lock b/Cargo.lock
index 0ae9c5ce..5e619cf8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13732,6 +13732,7 @@ name = "raea-app-check"
version = "0.1.0"
dependencies = [
"raea-app-check-flash",
+ "raea-app-check-inbox",
"raea-core-brief",
"raea-core-facts",
"raea-io-ffmpeg",
@@ -13744,6 +13745,14 @@ dependencies = [
name = "raea-app-check-flash"
version = "0.1.0"
+[[package]]
+name = "raea-app-check-inbox"
+version = "0.1.0"
+dependencies = [
+ "raea-io-home",
+ "serde_json",
+]
+
[[package]]
name = "raea-app-ci"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 8b2034b2..5d66b0bf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -172,6 +172,7 @@ members = [
"runtime/shared",
"apps/check",
"apps/check/flash",
+ "apps/check/inbox",
"apps/direction",
"apps/notes",
"apps/fingerprint",
diff --git a/apps/check/Cargo.toml b/apps/check/Cargo.toml
index 17340a20..a8cca0b5 100644
--- a/apps/check/Cargo.toml
+++ b/apps/check/Cargo.toml
@@ -19,4 +19,6 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
raea-sys-measure = { path = "../../systems/measure" }
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
raea-app-check-flash = { path = "flash" }
+# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
+raea-app-check-inbox = { path = "inbox" }
serde_json = "1"
diff --git a/apps/check/inbox/Cargo.toml b/apps/check/inbox/Cargo.toml
new file mode 100644
index 00000000..54aaf2e6
--- /dev/null
+++ b/apps/check/inbox/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "raea-app-check-inbox"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "`raea hook`'s hand-over: what the person sent from the raea app, read from the session's inbox once and handed to the agent at its next step"
+
+[dependencies]
+serde_json = "1"
+# the inbox folder, under the home folder
+raea-io-home = { path = "../../../io/home" }
diff --git a/apps/check/inbox/src/lib.rs b/apps/check/inbox/src/lib.rs
new file mode 100644
index 00000000..a462b979
--- /dev/null
+++ b/apps/check/inbox/src/lib.rs
@@ -0,0 +1,105 @@
+//! What the person sent from the raea app, handed to the session it's for at its next step (docs/agents.feature A3c;
+//! Shane 11-14: a reply in the feed "doesn't confirm, doesn't interrupt the agent", and the app forked a copy of the
+//! session so two agents ran). A session that posted with `raea show` has an inbox, ~/.raea/inbox/<inbox>.jsonl, and
+//! the app writes there what the person sends on its items or to it in the feed, even while its terminal is busy. This
+//! hook reads what was added since it last looked, after any tool call and when a turn is about to end, and hands it
+//! over: as the tool's context, or as the reason the turn goes on. How far it has read is kept beside the inbox
+//! (<inbox>.read, a byte offset), which the app reads to say the message was read.
+use serde_json::Value;
+use std::path::{Path, PathBuf};
+
+/// The session's inbox, named as `raea show` names it (engine/cli/src/show.ts posterOf): the harness's name and the
+/// first eight of its session id.
+pub fn name(agent: &str, v: &Value) -> Option<String> {
+ let session = v["session_id"].as_str().map(String::from).or_else(|| std::env::var("CLAUDE_CODE_SESSION_ID").ok()).filter(|s| !s.is_empty())?;
+ let slug = match agent {
+ "claude" => "claude-code",
+ "codex" => "codex",
+ "gemini" => "gemini",
+ _ => return None,
+ };
+ // the id's word characters, dots and dashes, as posterOf's /[^\w.-]/ leaves them
+ let id: String = session.chars().filter(|c| c.is_ascii_alphanumeric() || "_.-".contains(*c)).take(8).collect();
+ Some(format!("{slug}-{id}"))
+}
+
+/// $RAEA_INBOX_DIR, else ~/.raea/inbox
+pub fn dir() -> PathBuf {
+ raea_io_home::env_path("RAEA_INBOX_DIR", ".raea/inbox")
+}
+
+/// The lines added to the inbox since the last look, each read once: the cursor moves past them.
+pub fn unread(dir: &Path, inbox: &str) -> Vec<Value> {
+ let file = dir.join(format!("{inbox}.jsonl"));
+ let mark = dir.join(format!("{inbox}.read"));
+ let Ok(all) = std::fs::read(&file) else { return vec![] };
+ let from = std::fs::read_to_string(&mark).ok().and_then(|s| s.trim().parse::<usize>().ok()).unwrap_or(0).min(all.len());
+ // only whole lines: one being written stays for the next look
+ let Some(end) = all[from..].iter().rposition(|&b| b == b'\n').map(|i| from + i + 1) else { return vec![] };
+ let lines = String::from_utf8_lossy(&all[from..end]).lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
+ let _ = std::fs::write(&mark, end.to_string());
+ lines
+}
+
+/// One line as the agent reads it: who it's on, what kind, the words.
+fn said(l: &Value) -> String {
+ let s = |k: &str| l[k].as_str().unwrap_or("").trim().to_string();
+ let on = if s("item").is_empty() { String::new() } else { format!(" on item {} \"{}\"", s("item"), s("title")) };
+ let kind = s("kind");
+ let text = s("text");
+ let what = match kind.as_str() {
+ "message" => format!("a message{}: {text}", if s("project").is_empty() { String::new() } else { format!(" (project {})", s("project")) }),
+ "edits" => format!("edits{on}:\n{text}{}", if s("tasks").is_empty() { String::new() } else { format!("\n({})", s("tasks")) }),
+ "note" => format!("a note{on}: {text}"),
+ "answer" => format!("answers{on}: {text}"),
+ "result" => format!("a result{on}: {text}"),
+ "correction" => format!("a correction{on}: {text}"),
+ "sign" => format!("a sign-off{on} (ask {})", l["ask"]),
+ k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
+ };
+ format!("- {what}")
+}
+
+/// What the agent is told, or None when nothing's new.
+pub fn told(agent: &str, v: &Value) -> Option<String> {
+ let inbox = name(agent, v)?;
+ let lines = unread(&dir(), &inbox);
+ if lines.is_empty() {
+ return None;
+ }
+ let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
+ Some(format!(
+ "raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
+ let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ let f = d.join("claude-code-abcd1234.jsonl");
+ std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
+ let first = unread(&d, "claude-code-abcd1234");
+ assert_eq!(first.len(), 1);
+ assert_eq!(said(&first[0]), "- a message: more epic");
+ assert!(unread(&d, "claude-code-abcd1234").is_empty());
+ std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"note\",\"item\":\"i-1\",\"title\":\"Board\",\"text\":\"hills taller\"}\n").unwrap();
+ let next = unread(&d, "claude-code-abcd1234");
+ assert_eq!(next.len(), 1);
+ assert_eq!(said(&next[0]), "- a note on item i-1 \"Board\": hills taller");
+ assert_eq!(std::fs::read_to_string(d.join("claude-code-abcd1234.read")).unwrap(), std::fs::metadata(&f).unwrap().len().to_string());
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[test]
+ fn the_inbox_is_named_as_raea_show_names_it() {
+ assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
+ assert_eq!(name("kimi", &json!({"session_id": "x"})), None);
+ }
+}
diff --git a/apps/check/src/hook.rs b/apps/check/src/hook.rs
index d5a83d4a..8260086d 100644
--- a/apps/check/src/hook.rs
+++ b/apps/check/src/hook.rs
@@ -3,7 +3,8 @@
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
-//! file is saved: the quick check on a composition. A stop is exit 2 with the reason on stderr, which every harness
+//! file is saved: the quick check on a composition. After any tool, and as a turn ends: what the person sent from the raea
+//! app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness
//! hands its agent; the quick check's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -144,7 +145,15 @@ pub fn hook(args: &[String]) -> R<String> {
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: Value = serde_json::from_str(&input).unwrap_or_default();
let agent = named.unwrap_or_else(|| agent_of(&v));
- if let Some(cmd) = shell_command(&v) {
+ let event = v["hook_event_name"].as_str().unwrap_or("");
+ // what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
+ // to end goes on to take it up
+ let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
+ if event == "Stop" {
+ return Ok(sent.map(|s| json!({"decision": "block", "reason": s}).to_string()).unwrap_or_default());
+ }
+ let after_tool = matches!(event, "PostToolUse" | "AfterTool");
+ if let Some(cmd) = shell_command(&v).filter(|_| !after_tool) {
let home = std::env::var("HOME").unwrap_or_default();
let files = opened_media(cmd);
let key = format!("{}\n{}\n{cmd}", v["session_id"].as_str().unwrap_or(""), v["cwd"].as_str().unwrap_or(""));
@@ -159,7 +168,9 @@ pub fn hook(args: &[String]) -> R<String> {
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
}
- Ok(if found.is_empty() { String::new() } else { after(agent, &format!("raea check --quick after this save:\n{}", found.join("\n"))) })
+ let quick = (!found.is_empty()).then(|| format!("raea check --quick after this save:\n{}", found.join("\n")));
+ let text = [sent, quick].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
+ Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
}
#[cfg(test)]
diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs
index 36a9dce2..2e6acb2e 100644
--- a/apps/check/src/lib.rs
+++ b/apps/check/src/lib.rs
@@ -26,6 +26,7 @@ mod text;
use text::*;
pub mod quick;
pub mod hook;
+pub use raea_app_check_inbox as inbox;
#[cfg(test)]
mod tests;
diff --git a/apps/tools/src/agent_hooks.rs b/apps/tools/src/agent_hooks.rs
index 36be2ef9..4d4ba09f 100644
--- a/apps/tools/src/agent_hooks.rs
+++ b/apps/tools/src/agent_hooks.rs
@@ -1,7 +1,9 @@
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
-//! composition. An event that already has a `raea hook` entry is left as it is.
+//! composition. Claude Code's run after every tool and as a turn ends too, to hand the session what the person sent from
+//! the raea app (apps/check/src/inbox.rs). An event that already has a `raea hook` entry keeps it, its matcher widened
+//! to this raea's when an older raea wrote a narrower one.
use crate::agent_mcp::user_home;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -15,14 +17,14 @@ struct Hook {
secs: u64,
}
-/// Each harness's two hooks, by its own event and tool names.
-fn hooks(agent: &str) -> R<[Hook; 2]> {
+/// Each harness's hooks, by its own event and tool names.
+fn hooks(agent: &str) -> R<Vec<Hook>> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
- "claude" => [h("PreToolUse", "Bash", 30), h("PostToolUse", "Write|Edit|MultiEdit", 60)],
- "codex" => [h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
- "gemini" => [h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
- "kimi" => [h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
+ "claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 10)],
+ "codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
+ "gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
+ "kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
})
}
@@ -54,7 +56,14 @@ fn add_json(path: &Path, agent: &str, h: &Hook) -> R<bool> {
let hooks = doc.as_object_mut().ok_or(format!("{at} isn't a JSON object"))?.entry("hooks").or_insert_with(|| json!({}));
let list = hooks.as_object_mut().ok_or(format!("{at}: hooks isn't an object"))?.entry(h.event).or_insert_with(|| json!([]));
let list = list.as_array_mut().ok_or(format!("{at}: hooks.{} isn't a list", h.event))?;
- if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(|x| x["command"].as_str().unwrap_or("").starts_with("raea hook"))) {
+ let ours = |m: &Value| m["hooks"].as_array().into_iter().flatten().any(|x| x["command"].as_str().unwrap_or("").starts_with("raea hook"));
+ if let Some(m) = list.iter_mut().find(|m| ours(m)) {
+ // an older raea's narrower matcher (Claude's after-save hook, now after every tool) is widened, the rest kept
+ if h.matcher == "*" && m["matcher"].as_str() != Some("*") {
+ m["matcher"] = h.matcher.into();
+ write(path, &(serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n"))?;
+ return Ok(true);
+ }
return Ok(false);
}
// Gemini CLI counts milliseconds and names each hook
@@ -115,21 +124,24 @@ mod tests {
let c = d.join("claude/settings.json");
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
- let [pre, post] = hooks("claude").unwrap();
+ let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
- assert!(!add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook stands");
+ assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
+ assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&c).unwrap()).unwrap();
assert_eq!((v["model"].as_str(), v["hooks"]["PostToolUse"].as_array().unwrap().len()), (Some("x"), 2));
+ assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
+ assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
let g = d.join("gemini/settings.json");
- let [before, _] = hooks("gemini").unwrap();
+ let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&g).unwrap()).unwrap();
assert_eq!(v["hooks"]["BeforeTool"][0], json!({"matcher": "run_shell_command", "hooks": [{"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": 30000}]}));
let k = d.join("kimi/config.toml");
std::fs::create_dir_all(k.parent().unwrap()).unwrap();
std::fs::write(&k, "default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n").unwrap();
- let [pre, post] = hooks("kimi").unwrap();
+ let [pre, post] = <[Hook; 2]>::try_from(hooks("kimi").unwrap()).ok().unwrap();
assert!(add_toml(&k, &pre).unwrap() && !add_toml(&k, &pre).unwrap() && add_toml(&k, &post).unwrap() && !add_toml(&k, &post).unwrap());
let t = std::fs::read_to_string(&k).unwrap();
assert!(t.starts_with("default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash|Shell\"\ncommand = \"raea hook kimi\"\ntimeout = 30\n"), "{t}");
diff --git a/tools/layers.toml b/tools/layers.toml
index cd216222..a2665217 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -161,6 +161,7 @@ raea-runtime-shared = "runtime"
raea-page = "runtime"
raea-app-check = "apps"
raea-app-check-flash = "apps"
+raea-app-check-inbox = "apps"
raea-app-direction = "apps"
raea-app-notes = "apps"
# `raea fingerprint`: its verbs and the resident service that keeps the encoders loaded