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.

raea hook for every agent: media opened in Preview goes to raea show (a second try goes through), and every harness gets the hooks (Shane 11-09)

shinyobjectze9e0fba83e50
diff --git a/apps/check/src/hook.rs b/apps/check/src/hook.rs
new file mode 100644
index 00000000..7a3da0d3
--- /dev/null
+++ b/apps/check/src/hook.rs
@@ -0,0 +1,194 @@
+//! `raea hook [AGENT]` (docs/agents.feature A5d, A5e; docs/skills.feature SK10): one runner for every agent harness's
+//! tool hooks, whichever harness runs the agent (Claude Code, Codex, Gemini CLI, Kimi Code; `raea skills install
+//! --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
+//! 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};
+
+type R<T> = Result<T, String>;
+
+/// What a still, a video or a sound ends with: what the raea app shows as an item.
+const MEDIA: [&str; 25] = ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "avif", "exr", "mp4", "mov", "m4v", "webm", "mkv", "avi", "wav", "mp3", "m4a", "aac", "flac", "aif", "aiff"];
+/// A stopped command tried again within this many seconds goes through.
+const AGAIN: u64 = 600;
+
+/// The harness that sent this input, when the hook's command doesn't name it: Gemini CLI names its events BeforeTool and
+/// AfterTool, Kimi Code says its client; Claude Code and Codex share one shape.
+fn agent_of(v: &Value) -> &'static str {
+ match (v["hook_event_name"].as_str().unwrap_or(""), v["client_type"].as_str().unwrap_or("")) {
+ ("BeforeTool" | "AfterTool", _) => "gemini",
+ (_, c) if c.contains("kimi") => "kimi",
+ _ => "claude",
+ }
+}
+
+/// The shell command a tool call runs, if it's a shell tool's (Bash, shell, shell_command, exec_command,
+/// run_shell_command): Codex's apply_patch carries its patch in `command` too, and isn't one.
+fn shell_command(v: &Value) -> Option<&str> {
+ let cmd = v["tool_input"]["command"].as_str()?;
+ (v["tool_name"].as_str() != Some("apply_patch") && !cmd.trim_start().starts_with("*** Begin Patch")).then_some(cmd)
+}
+
+/// A shell segment's words, quotes taken off (enough for `open "a b.png"`, not a shell).
+fn words(seg: &str) -> Vec<String> {
+ let (mut out, mut cur, mut quote, mut any) = (Vec::new(), String::new(), None, false);
+ for c in seg.chars() {
+ match (quote, c) {
+ (Some(q), c) if c == q => quote = None,
+ (Some(_), c) => cur.push(c),
+ (None, '\'' | '"') => (quote, any) = (Some(c), true),
+ (None, c) if c.is_whitespace() => {
+ if any || !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ any = false;
+ }
+ (None, c) => cur.push(c),
+ }
+ }
+ if any || !cur.is_empty() {
+ out.push(cur);
+ }
+ out
+}
+
+/// The media files a command opens in the Mac's viewer or a browser (`open`, `open -a Preview`, `xdg-open`,
+/// `qlmanage -p`); `open -a raea`, `open -R` (Finder), links and other files aren't.
+pub fn opened_media(cmd: &str) -> Vec<String> {
+ let mut found = Vec::new();
+ for seg in cmd.split(['\n', ';', '|', '&']) {
+ let w = words(seg);
+ let mut it = w.iter().skip_while(|t| t.contains('=') && !t.starts_with('-') || ["command", "exec", "nohup", "env"].contains(&t.as_str()));
+ let Some(tool) = it.next().map(|t| t.rsplit('/').next().unwrap_or(t).to_string()) else { continue };
+ if !["open", "xdg-open", "qlmanage"].contains(&tool.as_str()) {
+ continue;
+ }
+ let rest: Vec<&String> = it.collect();
+ let app = rest.windows(2).find(|p| p[0] == "-a" || p[0] == "-b").map(|p| p[1].to_lowercase());
+ if app.is_some_and(|a| a.contains("raea")) || rest.iter().any(|t| *t == "-R") {
+ continue;
+ }
+ let args = rest.iter().enumerate().filter(|(i, t)| !t.starts_with('-') && !(*i > 0 && ["-a", "-b"].contains(&rest[i - 1].as_str())));
+ found.extend(args.map(|(_, t)| t.to_string()).filter(|t| !t.contains("://") && t.rsplit_once('.').is_some_and(|(_, e)| MEDIA.contains(&e.to_lowercase().as_str()))));
+ }
+ found
+}
+
+/// The raea app on this Mac (RAEA_APP, /Applications or ~/Applications).
+fn app_installed(home: &str) -> bool {
+ [std::env::var("RAEA_APP").unwrap_or_default(), "/Applications/raea.app".into(), format!("{home}/Applications/raea.app")].iter().any(|p| !p.is_empty() && std::path::Path::new(p).exists())
+}
+
+/// True when this command was stopped for this session within AGAIN seconds (the agent's second yes, which clears it);
+/// else it's noted and false.
+fn tried_before(dir: &Path, key: &str) -> bool {
+ let h = key.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3));
+ let at = dir.join(format!("{h:016x}"));
+ let fresh = std::fs::metadata(&at).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|e| e.as_secs() < AGAIN);
+ if fresh {
+ let _ = std::fs::remove_file(&at);
+ return true;
+ }
+ let _ = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&at, key));
+ false
+}
+
+/// Why the command stops, for the agent: what to run instead, and that the same command again goes through.
+pub fn steer(files: &[String]) -> String {
+ let list = files.iter().map(|f| if f.contains(' ') { format!("{f:?}") } else { f.clone() }).collect::<Vec<_>>().join(" ");
+ format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
+}
+
+/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
+/// adds or updates (Codex).
+fn saved(v: &Value) -> Vec<String> {
+ let i = &v["tool_input"];
+ if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
+ return vec![p.to_string()];
+ }
+ let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
+ patch.lines().filter_map(|l| l.strip_prefix("*** Add File: ").or(l.strip_prefix("*** Update File: "))).map(|p| p.trim().to_string()).collect()
+}
+
+/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
+/// plain stdout, Claude Code's and Codex's PostToolUse context.
+fn after(agent: &str, text: &str) -> String {
+ match agent {
+ "kimi" => text.to_string(),
+ "gemini" => json!({"hookSpecificOutput": {"hookEventName": "AfterTool", "additionalContext": text}}).to_string(),
+ _ => json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": text}}).to_string(),
+ }
+}
+
+/// `raea hook [claude|codex|gemini|kimi]`: the harness's hook input on stdin. Prints what goes back to the agent, or
+/// stops the call (exit 2, the reason on stderr).
+pub fn hook(args: &[String]) -> R<String> {
+ let named = args.first().map(String::as_str);
+ if named.is_some_and(|a| !["claude", "codex", "gemini", "kimi"].contains(&a)) {
+ return Err("usage: raea hook [claude|codex|gemini|kimi] (an agent's tool hooks; raea skills install --agent A adds them)".into());
+ }
+ let mut input = String::new();
+ 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 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(""));
+ if !files.is_empty() && app_installed(&home) && !tried_before(&PathBuf::from(&home).join(".raea/hooks/again"), &key) {
+ eprintln!("{}", steer(&files));
+ std::process::exit(2);
+ }
+ return Ok(String::new());
+ }
+ let mut found = Vec::new();
+ for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
+ 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"))) })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn media_opened_in_a_viewer_is_found_and_the_rest_isnt() {
+ assert_eq!(opened_media("open out/a.png out/b.PNG"), ["out/a.png", "out/b.PNG"]);
+ assert_eq!(opened_media("cd /tmp && open -a Preview \"sheet 1.jpg\""), ["sheet 1.jpg"]);
+ assert_eq!(opened_media("FOO=1 /usr/bin/open cut.mp4; echo done"), ["cut.mp4"]);
+ assert_eq!(opened_media("qlmanage -p still.webp >/dev/null 2>&1"), ["still.webp"]);
+ assert_eq!(opened_media("xdg-open take.mov"), ["take.mov"]);
+ for none in ["open -a raea", "open -a raea out/a.png", "open -R out/a.png", "open https://x.io/a.png", "open notes.pdf", "open .", "cat a.png", "git open a.png", "echo open a.png > x"] {
+ assert!(opened_media(none).is_empty(), "{none}: {:?}", opened_media(none));
+ }
+ }
+
+ #[test]
+ fn each_harness_is_told_apart_and_answered_in_its_shape() {
+ assert_eq!(agent_of(&json!({"hook_event_name": "BeforeTool", "tool_name": "run_shell_command"})), "gemini");
+ assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "client_type": "kimi_code_cli"})), "kimi");
+ assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
+ assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
+ assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
+ assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
+ assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
+ assert_eq!(after("kimi", "x"), "x");
+ assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
+ assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
+ }
+
+ #[test]
+ fn the_same_command_again_goes_through_once() {
+ let d = std::env::temp_dir().join(format!("raea-hook-again-{}", std::process::id()));
+ assert!(!tried_before(&d, "s\n/x\nopen a.png"));
+ assert!(tried_before(&d, "s\n/x\nopen a.png"));
+ assert!(!tried_before(&d, "s\n/x\nopen a.png"), "a third try is a new first");
+ assert!(!tried_before(&d, "other\n/x\nopen a.png"));
+ let _ = std::fs::remove_dir_all(&d);
+ }
+}
diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs
index 553023e6..6dabdbc8 100644
--- a/apps/check/src/lib.rs
+++ b/apps/check/src/lib.rs
@@ -23,6 +23,7 @@ use flash::*;
mod text;
use text::*;
pub mod quick;
+pub mod hook;
#[cfg(test)]
mod tests;
diff --git a/apps/check/src/quick.rs b/apps/check/src/quick.rs
index 2d163812..2fef5bf1 100644
--- a/apps/check/src/quick.rs
+++ b/apps/check/src/quick.rs
@@ -1,8 +1,8 @@
-//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills
-//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full
-//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is
-//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root
-//! is written, the quick check's findings go back to the agent; a clean check says nothing.
+//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
+//! quarter in, the middle, the last frame) with their manifest, about a second, and runs the full check's text rules
+//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
+//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
+//! nothing.
use super::*;
use std::path::Path;
@@ -41,28 +41,6 @@ pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String,
result
}
-/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as
-/// the hook's additionalContext. Anything else, or a clean check, prints nothing.
-pub fn hook(args: &[String]) -> R<String> {
- if args.first().map(String::as_str) != Some("claude") {
- return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());
- }
- let mut input = String::new();
- std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
- let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
- let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();
- let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);
- if !composition {
- return Ok(String::new());
- }
- let (report, _) = quick(&[path.to_string()], Vec::new())?;
- if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {
- return Ok(String::new());
- }
- let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();
- Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())
-}
-
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
diff --git a/apps/tools/src/agent_hooks.rs b/apps/tools/src/agent_hooks.rs
new file mode 100644
index 00000000..1cfb42ef
--- /dev/null
+++ b/apps/tools/src/agent_hooks.rs
@@ -0,0 +1,136 @@
+//! 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.
+use crate::agent_mcp::user_home;
+use serde_json::{Value, json};
+use std::path::{Path, PathBuf};
+
+type R<T> = Result<T, String>;
+
+/// One hook: the harness's event, the tools it matches, and the seconds it may take.
+struct Hook {
+ event: &'static str,
+ matcher: &'static str,
+ secs: u64,
+}
+
+/// Each harness's two hooks, by its own event and tool names.
+fn hooks(agent: &str) -> R<[Hook; 2]> {
+ 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)],
+ a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
+ })
+}
+
+/// Where the harness keeps its hooks.
+fn file(agent: &str) -> R<PathBuf> {
+ let home = user_home()?;
+ let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
+ Ok(match agent {
+ "claude" => home.join(".claude/settings.json"),
+ "codex" => env("CODEX_HOME").unwrap_or_else(|| home.join(".codex")).join("hooks.json"),
+ "gemini" => home.join(".gemini/settings.json"),
+ _ => env("KIMI_CODE_HOME").unwrap_or_else(|| home.join(".kimi-code")).join("config.toml"),
+ })
+}
+
+/// Adds a hook to a JSON file of `{"hooks": {EVENT: [{matcher, hooks: [...]}]}}` (Claude Code, Codex, Gemini CLI)
+/// unless the event has a `raea hook` entry; true when it added.
+fn add_json(path: &Path, agent: &str, h: &Hook) -> R<bool> {
+ let at = path.display();
+ let mut doc: Value = match std::fs::read_to_string(path) {
+ Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{at}: {e}"))?,
+ _ => json!({}),
+ };
+ 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"))) {
+ return Ok(false);
+ }
+ // Gemini CLI counts milliseconds and names each hook
+ let one = if agent == "gemini" { json!({"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": h.secs * 1000}) } else { json!({"type": "command", "command": format!("raea hook {agent}"), "timeout": h.secs}) };
+ list.push(json!({"matcher": h.matcher, "hooks": [one]}));
+ write(path, &(serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n"))?;
+ Ok(true)
+}
+
+/// Adds a `[[hooks]]` table to Kimi Code's config.toml (only event, matcher, command and timeout: it refuses other
+/// keys) unless one runs `raea hook` on that event; true when it added.
+fn add_toml(path: &Path, h: &Hook) -> R<bool> {
+ let text = std::fs::read_to_string(path).unwrap_or_default();
+ let ours = text.split("[[hooks]]").skip(1).any(|t| {
+ let t = t.split("\n[").next().unwrap_or(t);
+ t.contains("command = \"raea hook") && t.contains(&format!("event = \"{}\"", h.event))
+ });
+ if ours {
+ return Ok(false);
+ }
+ let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
+ write(path, &format!("{text}{sep}[[hooks]]\nevent = \"{}\"\nmatcher = \"{}\"\ncommand = \"raea hook kimi\"\ntimeout = {}\n", h.event, h.matcher, h.secs))?;
+ Ok(true)
+}
+
+/// Writes a config file whole, through a temporary file beside it.
+fn write(path: &Path, text: &str) -> R<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ }
+ let tmp = path.with_extension("raea-tmp");
+ std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
+ std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Adds raea's hooks for an agent; the line says what happened.
+pub fn install(agent: &str) -> R<String> {
+ let (path, mut added) = (file(agent)?, Vec::new());
+ for h in hooks(agent)? {
+ if if agent == "kimi" { add_toml(&path, &h)? } else { add_json(&path, agent, &h)? } {
+ added.push(h.event);
+ }
+ }
+ let what = if added.is_empty() { "already there".to_string() } else { format!("added ({})", added.join(", ")) };
+ // Codex runs a new or changed hook only once the person trusts it
+ let trust = if agent == "codex" && !added.is_empty() { "; trust them in Codex's /hooks" } else { "" };
+ Ok(format!("{}: hooks `raea hook {agent}` {what}{trust}\n", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn each_harness_gets_both_hooks_once_and_keeps_its_own() {
+ let d = std::env::temp_dir().join(format!("raea-agent-hooks-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ 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();
+ 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");
+ 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"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
+ let g = d.join("gemini/settings.json");
+ let [before, _] = hooks("gemini").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();
+ 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}");
+ assert_eq!(t.matches("[[hooks]]").count(), 3);
+ assert!(hooks("cursor").is_err());
+ let _ = std::fs::remove_dir_all(&d);
+ }
+}
diff --git a/apps/tools/src/agent_mcp.rs b/apps/tools/src/agent_mcp.rs
index a4758091..da771f6a 100644
--- a/apps/tools/src/agent_mcp.rs
+++ b/apps/tools/src/agent_mcp.rs
@@ -90,30 +90,6 @@ pub fn offer(agent: &str) -> R<String> {
Ok(line(add_json(&p)?, &p))
}
-/// A hook entry raea added (its command is `raea hook ...`).
-fn ours(hook: &Value) -> bool {
- hook["command"].as_str().unwrap_or("").starts_with("raea hook")
-}
-
-/// Claude Code's PostToolUse hook running `raea hook claude` after a file is written, in its settings.json, unless one
-/// is there; true when it added. Its findings reach the agent as the hook's additionalContext.
-pub fn claude_hook(settings: &Path) -> R<bool> {
- let mut doc: Value = match std::fs::read_to_string(settings) {
- Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", settings.display()))?,
- _ => json!({}),
- };
- let post = doc.as_object_mut().ok_or("settings.json isn't an object")?.entry("hooks").or_insert_with(|| json!({})).as_object_mut().ok_or("settings.json: hooks isn't an object")?.entry("PostToolUse").or_insert_with(|| json!([]));
- let list = post.as_array_mut().ok_or("settings.json: hooks.PostToolUse isn't a list")?;
- if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(ours)) {
- return Ok(false);
- }
- list.push(json!({"matcher": "Write|Edit|MultiEdit", "hooks": [{"type": "command", "command": "raea hook claude", "timeout": 60}]}));
- let tmp = settings.with_extension("raea-tmp");
- std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;
- std::fs::rename(&tmp, settings).map_err(|e| format!("{}: {e}", settings.display()))?;
- Ok(true)
-}
-
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
pub fn pin(to: &Path, mv: &str, v: &str) -> R<String> {
let guide = raea_io_home::home().join("sdk/guides/craft/verbs").join(format!("{mv}.md"));
@@ -151,14 +127,6 @@ mod tests {
assert!(add_toml(&t).unwrap());
assert!(!add_toml(&t).unwrap());
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
- let h = d.join("claude/settings.json");
- std::fs::create_dir_all(h.parent().unwrap()).unwrap();
- std::fs::write(&h, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]}]}}"#).unwrap();
- assert!(claude_hook(&h).unwrap());
- assert!(!claude_hook(&h).unwrap());
- let v: Value = serde_json::from_str(&std::fs::read_to_string(&h).unwrap()).unwrap();
- assert_eq!(v["hooks"]["PostToolUse"].as_array().unwrap().len(), 2);
- assert_eq!(v["model"], "x");
let _ = std::fs::remove_dir_all(&d);
}
diff --git a/apps/tools/src/lib.rs b/apps/tools/src/lib.rs
index f6341669..537142d0 100644
--- a/apps/tools/src/lib.rs
+++ b/apps/tools/src/lib.rs
@@ -10,5 +10,6 @@ pub mod splat;
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
pub mod agent_mcp;
+pub mod agent_hooks;
/// `raea setup blender` and `raea blender run`
pub mod blender;
diff --git a/docs/agents.feature b/docs/agents.feature
index bf224ca0..abb7ba2c 100644
--- a/docs/agents.feature
+++ b/docs/agents.feature
@@ -102,6 +102,7 @@ Feature: Agents in the raea app: chats run on a provider, agents are optional te
# and recording them after making an answer."
# Status 11-09: built. App side raea-feed 077e77f (host/show.ts, host-file.ts, raea:// links in src/App.tsx,
# answers and results to the inbox); CLI engine/cli/src/show.ts; the skill's section 5 says it (raea-skills).
+ # A5d/A5e 11-09: apps/check/src/hook.rs (raea hook AGENT), apps/tools/src/agent_hooks.rs (each harness's config).
Scenario: A5a. raea show from any session
Given a session outside raea (a terminal agent) with the raea app installed
When it runs `raea show FILE...` (stills, a video, a sound, a NAME.script.ts or .md, a .tsx) or
@@ -119,3 +120,22 @@ Feature: Agents in the raea app: chats run on a provider, agents are optional te
Scenario: A5c. Agents show, they don't open
Then the raea skill tells every agent to show work with `raea show` (or feed_post inside the app), never to open
a render, a sheet or a question in Preview or a browser while the app is installed
+
+ Scenario: A5d. A hook stops the open once, and a second try goes through
+ # Shane 11-09: "yes lets do that or at least make it double confirm"
+ Given raea's hooks are installed for the agent (`raea skills install --agent A`) and the raea app is on this Mac
+ When the agent runs a shell command that opens a still, a video or a sound in the Mac's viewer or a browser
+ (`open`, `open -a Preview`, `xdg-open`, `qlmanage -p`)
+ Then `raea hook A` stops it, and the agent reads why: `raea show` with those files instead
+ And the same command run again in that session within ten minutes goes through: the agent's second yes, for when
+ the person asked for the viewer or raea show can't
+ But `open -a raea`, Finder (`open -R`), links and files the app doesn't show (a PDF) are never stopped
+
+ Scenario: A5e. Every harness, not only Claude Code
+ # Shane 11-09: "make sure all hooks and usages are acp agnostic not just claude"
+ Then `raea skills install` adds the same hooks for Claude Code (settings.json), Codex (hooks.json), Gemini CLI
+ (settings.json, BeforeTool and AfterTool) and Kimi Code (config.toml [[hooks]]), and `raea hook` answers each
+ in the shape it reads (a stop is exit 2 with the reason on stderr, which they all take)
+ And the hooks hold inside the raea app too, which runs each ACP agent with its own shell and config
+ And `raea show` names its poster from the harness that started it, found up its parent processes when the
+ harness doesn't mark its shell, so Kimi, OpenCode and the rest post as themselves with an inbox per session
diff --git a/docs/manual/reference/cli/hook.md b/docs/manual/reference/cli/hook.md
index eee263ec..7b86b6b9 100644
--- a/docs/manual/reference/cli/hook.md
+++ b/docs/manual/reference/cli/hook.md
@@ -1,16 +1,27 @@
---
title: "raea hook"
-summary: "Claude Code's PostToolUse hook: the quick text check after an agent saves a composition."
+summary: "Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved."
order: 48
-sources: ["apps/check/src/quick.rs"]
+sources: ["apps/check/src/hook.rs", "apps/tools/src/agent_hooks.rs"]
---
-`raea hook claude` is meant to be run by Claude Code, not by hand. Installed as a PostToolUse hook (`raea skills
-install` sets it up), it runs `raea check --quick` on a composition each time the agent saves one, and hands the
-findings back to the agent, so clipped or cramped text is caught on the edit that caused it.
+`raea hook` is run by an agent's harness, not by hand: Claude Code, Codex, Gemini CLI and Kimi Code each call it from
+their own hook settings, which `raea skills install --agent A` adds (and leaves alone when an entry is already there).
+Inside the raea app the same hooks hold, since the app runs each agent with its own shell and config.
+
+Before a shell command, it looks for a still, a video or a sound being opened in the Mac's viewer or a browser
+(`open`, `open -a Preview`, `xdg-open`, `qlmanage -p`). While the raea app is installed it stops that command once and
+tells the agent to use [`raea show`](show.md) instead, so the work comes up in the app as something the person can
+answer. The same command run again in that session within ten minutes goes through, for when the person asked for the
+viewer. `open -a raea`, Finder (`open -R`), links and PDFs are never stopped.
+
+After a file is saved, it runs `raea check --quick` on a composition and hands the findings back to the agent, so
+clipped or cramped text is caught on the edit that caused it. A stop is exit 2 with the reason on stderr, which every
+harness hands its agent; findings go back in the shape each harness reads.
```sh
-raea skills install --agent claude # installs the skill and this hook
+raea skills install --agent claude # the skill and its hooks, for Claude Code
+raea skills install --agent kimi # the same for Kimi Code (codex and gemini too)
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
diff --git a/docs/manual/reference/cli/skills.md b/docs/manual/reference/cli/skills.md
index 841c3d0e..6e1d5e09 100644
--- a/docs/manual/reference/cli/skills.md
+++ b/docs/manual/reference/cli/skills.md
@@ -7,8 +7,9 @@ sources: ["engine/cli/src/skill.rs"]
`raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this
version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and
-`~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and for Claude Code the hook that
-runs the quick check after each saved composition ([`raea hook`](hook.md)).
+`~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and raea's hooks to every agent
+([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each
+saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is.
The skill raea ships matches the version it ships with. An agent can hold a copy from an older or newer install;
its front matter names the version it came with, and when that differs from `raea --version` the agent reads
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 66b600ac..a9c0cfff 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -129,7 +129,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] | raea show --question Q --choice A --choice B [STILL...] (shown in the raea app as an item the person can use and answer, the window brought up on it: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or a question; what they send comes to ~/.raea/inbox/INBOX.jsonl; never open media in Preview while the app is installed)");
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
- let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook claude (Claude Code's PostToolUse hook: the quick check after a composition is saved)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}", skill::USAGE, tools::blender::USAGE);
+ let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}", skill::USAGE, tools::blender::USAGE);
let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
let apps = format!(" {}\n {}\n {}\n", raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
@@ -195,9 +195,9 @@ pub fn run(args: &[String]) -> R<String> {
println!("{report}");
std::process::exit(i32::from(bad));
}
- // `hook claude`: Claude Code's PostToolUse hook, the quick check after a composition is saved (SK10)
+ // `hook [AGENT]`: every agent harness's tool hooks (A5d): raea show over Preview, the quick check after a save (SK10)
if args[0] == "hook" {
- return raea_app_check::quick::hook(&args[1..]);
+ return raea_app_check::hook::hook(&args[1..]);
}
if args[0] == "check" {
std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));
diff --git a/engine/cli/src/native.ts b/engine/cli/src/native.ts
index 60915e2d..4fac89bd 100644
--- a/engine/cli/src/native.ts
+++ b/engine/cli/src/native.ts
@@ -10,6 +10,7 @@ import { basename, delimiter, dirname, extname } from "node:path";
import { brandKit } from "./brand";
import { readSite, stylesOf } from "./scrape";
import { wordsOf } from "./heard";
+import { HARNESSES } from "./show";
import { raeaHandler, type Engine, type Host } from "./index";
const [raea, ...args] = process.argv.slice(2);
@@ -422,6 +423,22 @@ function show(a: Record<string, unknown>): unknown {
return shown;
}
+/** The agent harness that started this command (show.ts HARNESSES), found up its parent processes: a program's own
+ * name, or the script a runtime runs (`node .../gemini`). Nothing when no harness is up there. */
+function harness(): { name: string; pid: number } | undefined {
+ let pid = process.ppid;
+ for (let i = 0; i < 16 && pid > 1; i++) {
+ const m = /^\s*(\d+)\s+(.*)$/.exec(spawnSync("ps", ["-o", "ppid=,args=", "-p", String(pid)], { encoding: "utf8" }).stdout ?? "");
+ if (!m) return undefined;
+ for (const w of m[2].split(/\s+/).slice(0, 2).map((w) => basename(w).toLowerCase())) {
+ const hit = HARNESSES.find(([re]) => re.test(w));
+ if (hit) return { name: hit[1], pid };
+ }
+ pid = Number(m[1]);
+ }
+ return undefined;
+}
+
/** An op of the feed host's libraries (apps/app host/library/service.ts): POST <the app's host>/host/library. */
function library(a: Record<string, unknown>): unknown {
const at = appHost();
@@ -443,6 +460,8 @@ const host: Host = (op, a) => {
return library(a);
case "show":
return show(a);
+ case "harness":
+ return harness();
default:
throw new Error(`raea: this step (${op}) isn't in the native raea yet`);
}
diff --git a/engine/cli/src/show.ts b/engine/cli/src/show.ts
index f6f0e336..1a63ef97 100644
--- a/engine/cli/src/show.ts
+++ b/engine/cli/src/show.ts
@@ -18,10 +18,19 @@ raea show --question "Which look?" (--choice A --choice B ... | STILL.png STILL.
const WITH_VALUE = new Set(["--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice"]);
-/** The session's name and inbox, from its harness when it doesn't say: one inbox per session, so its answers find it. */
-export function posterOf(env: Record<string, string | undefined>, as?: string, role?: string, inbox?: string, cwd = "") {
- const name = as?.trim() || (env.CLAUDECODE ? "Claude Code" : env.CODEX_SANDBOX || env.CODEX_HOME ? "Codex" : env.GEMINI_CLI ? "Gemini" : env.RAEA_AGENT || "An agent");
- const session = env.CLAUDE_CODE_SESSION_ID || env.CODEX_SESSION_ID || env.RAEA_SESSION || hash(cwd);
+/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
+ * walks up its parents): any harness, not only the ones that mark their shells. */
+export const HARNESSES: [RegExp, string][] = [
+ [/^claude$/, "Claude Code"], [/^codex/, "Codex"], [/^gemini$/, "Gemini"], [/^kimi$/, "Kimi"], [/^opencode$/, "OpenCode"],
+ [/^goose$/, "Goose"], [/^cursor-agent$/, "Cursor"], [/^amp$/, "Amp"], [/^qwen$/, "Qwen Code"], [/^crush$/, "Crush"], [/^aider$/, "Aider"],
+];
+
+/** The session's name and inbox, from its harness when it doesn't say: its shell's marks, else the harness that started
+ * this command (`parent`, any harness), one inbox per session so its answers find it. */
+export function posterOf(env: Record<string, string | undefined>, as?: string, role?: string, inbox?: string, cwd = "", parent?: { name: string; pid: number }) {
+ const marked = env.CLAUDECODE ? "Claude Code" : env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_THREAD_ID ? "Codex" : env.GEMINI_CLI ? "Gemini" : env.OPENCODE ? "OpenCode" : undefined;
+ const name = as?.trim() || marked || parent?.name || env.RAEA_AGENT || "An agent";
+ const session = env.CLAUDE_CODE_SESSION_ID || env.CODEX_THREAD_ID || env.CODEX_SESSION_ID || env.RAEA_SESSION || (parent ? `p${parent.pid}` : hash(cwd));
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "agent";
return { name, ...(role?.trim() ? { role: role.trim() } : {}), inbox: inbox?.trim() || `${slug}-${session.replace(/[^\w.-]/g, "").slice(0, 8)}` };
}
@@ -47,7 +56,14 @@ export function parseShow(args: string[], cwd: string) {
export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<string, string | undefined>): string {
if (!args.length || args[0] === "--help") return SHOW_USAGE;
const a = parseShow(args, cwd);
- const by = posterOf(env, a.as, a.role, a.inbox, cwd);
+ const parent = (): { name: string; pid: number } | undefined => {
+ try {
+ return ask("harness", {});
+ } catch {
+ return undefined; // a shell without the native raea: the show below says so
+ }
+ };
+ const by = posterOf(env, a.as, a.role, a.inbox, cwd, a.as && a.inbox ? undefined : parent());
const r = ask("show", { files: a.files, title: a.title, ask: a.ask, question: a.question, choices: a.choices, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string };
diff --git a/engine/cli/src/skill.rs b/engine/cli/src/skill.rs
index 336151b9..c245f965 100644
--- a/engine/cli/src/skill.rs
+++ b/engine/cli/src/skill.rs
@@ -4,7 +4,7 @@
//! `raea --version` the agent reads `raea skill` instead.
use super::*;
-pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and for claude adds the quick-check hook unless --no-hooks)";
+pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is)";
/// Where each agent reads a person's skills, one folder per skill holding SKILL.md. Checked by hand on 11-05:
/// claude: ~/.claude/skills (Claude Code's docs); codex: ~/.agents/skills (developers.openai.com/codex/skills, the user
@@ -103,7 +103,7 @@ fn copy(from: &Path, to: &Path) -> R<()> {
}
/// `raea skills install --agent claude|codex|kimi|gemini`: raea's skills, stamped with this version, where that agent
-/// reads them; each replaces the copy that was there.
+/// reads them; each replaces the copy that was there, but a link (a checkout of raea-skills) is the person's to keep.
pub fn install(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("install") {
return Err(format!("usage: {USAGE}"));
@@ -114,6 +114,7 @@ pub fn install(args: &[String]) -> R<String> {
let mut out = String::new();
for name in installed_names()? {
let dst = to.join(&name);
+ if dst.is_symlink() { out += &format!("{}: a link, left as it is\n", dst.display()); continue; }
if dst.exists() {
std::fs::remove_dir_all(&dst).map_err(|e| format!("{}: {e}", dst.display()))?;
}
@@ -132,11 +133,8 @@ pub fn install(args: &[String]) -> R<String> {
out += &tools::agent_mcp::pin(&to, m, &v)?;
}
}
- // Claude Code's hook: the quick check after a composition is saved (SK10); --no-hooks leaves its settings alone
- if agent == "claude" && !args.iter().any(|a| a == "--no-hooks") {
- let settings = target("claude")?.with_file_name("settings.json");
- out += &format!("{}: hook `raea hook claude` {}\n", settings.display(), if tools::agent_mcp::claude_hook(&settings)? { "added" } else { "already there" });
- }
+ // every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone
+ if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; }
// the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
if !args.iter().any(|a| a == "--no-mcp") {
out += &tools::agent_mcp::offer(agent)?;