Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hermes): run the session lifecycle through native hooks
4nrryeb37ecbed9a9
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex effab784..93d8b2d7 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2457,13 +2457,16 @@ pub enum AgentChoice {/// block of `~/.hermes/config.yaml`. Hermes runs each `command` through/// `shlex.split` with the event JSON on stdin and **no shell**, so/// ai-memory's native `hook` subcommand is invoked directly (exec form,- /// like Zero and ZCode). ai-memory wires the two events that give Hermes- /// tool observations — `pre_tool_call` / `post_tool_call`, whose payload- /// carries `tool_name` / `tool_input`, the envelope the router already- /// recognises for `agent=hermes`. `~/.hermes/config.yaml` is NOT written:- /// it is YAML the installer would have to splice, and Hermes gates user- /// hooks behind its own acceptance prompt (`hooks_auto_accept`), so- /// `install-hooks --agent hermes` prints the ready-to-paste block.+ /// like Zero and ZCode). ai-memory wires the tool events and the session+ /// lifecycle (`on_session_start`, `pre_llm_call`, `on_session_end` as a+ /// turn boundary, `on_session_finalize`); the first turn's `pre_llm_call`+ /// brings the pending handoff in as context. When the community+ /// memory-provider plugin is installed under `$HERMES_HOME/plugins`, only+ /// the tool events are wired, since the plugin owns the rest.+ /// `~/.hermes/config.yaml` is NOT written: it is YAML the installer would+ /// have to splice, and Hermes gates user hooks behind its own acceptance+ /// prompt (`hooks_auto_accept`), so `install-hooks --agent hermes` prints+ /// the ready-to-paste block.#[value(alias = "hermes-agent")]Hermes,/// GitHub Copilot CLI — JSON-config lifecycle hooks indiff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 7c7ab5a0..7c46584b 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -989,6 +989,29 @@ fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_js}}+/// Hermes adds a hook's stdout to the turn only as a JSON object whose+/// `context` is a non-blank string (`_parse_context` in+/// `agent/shell_hooks.py`); plain text and every other key are dropped.+fn first_prompt_context_envelope(handoff: String) -> serde_json::Value {+ serde_json::json!({ "context": handoff })+}++/// The variable Hermes exports `terminal.cwd` through, to its tools and to+/// every hook process (`hermes_cli/cli_config_load.py`, `gateway/run.py`).+const HERMES_TERMINAL_CWD_ENV: &str = "TERMINAL_CWD";++/// The Hermes session's working directory, when the hook process carries one+/// that exists here. A container backend can export a path that exists only+/// inside the sandbox, and a relative value names nothing, so either falls+/// back to the payload cwd.+fn hermes_terminal_cwd(runtime_env: &RuntimeEnv) -> Option<String> {+ let path = PathBuf::from(runtime_env.var_os(HERMES_TERMINAL_CWD_ENV)?);+ if !path.is_absolute() || !path.is_dir() {+ return None;+ }+ path.to_str().map(str::to_owned)+}+/// Run a single hook end-to-end. Always returns Ok and always writes a JSON/// object to stdout — a hook must never fail the agent.///@@ -1035,12 +1058,14 @@ wherestdout,spawn_background_drainer,home_dir(),+ RuntimeEnv::from_process(),).await}/// [`run_with_payload`] with the home directory given, the root that the-/// Antigravity step output and transcript reads are confined to.+/// Antigravity step output and transcript reads are confined to, and the+/// process environment captured by the caller.async fn run_with_payload_in_home<W, S>(data_dir: Option<PathBuf>,args: HookArgs,@@ -1048,12 +1073,12 @@ async fn run_with_payload_in_home<W, S>(stdout: &mut W,spawn_background_drainer: S,home: Option<PathBuf>,+ runtime_env: RuntimeEnv,) -> anyhow::Result<()>whereW: std::io::Write,S: FnOnce(&Path, Option<&str>) -> std::io::Result<()>,{- let runtime_env = RuntimeEnv::from_process();let dd = resolve_data_dir_with(data_dir.as_deref(), &runtime_env);let spool_policy =Config::load_with_runtime_env(Some(&dd.join("config.toml")), Some(dd), runtime_env.clone())@@ -1073,6 +1098,10 @@ wherelet delivers_context = (hook_event == HookEvent::SessionStart&& agent_kind.session_start_injects_handoff())|| (hook_event == HookEvent::UserPrompt && agent_kind.user_prompt_injects_handoff())+ // Hermes takes the handoff on a session's first prompt; which prompt+ // that is shows only in the payload, read below.+ || (hook_event == HookEvent::UserPrompt+ && agent_kind.first_user_prompt_injects_handoff())// Grok delivers the handoff on the first PostToolUse (its SessionStart /// UserPromptSubmit stdout is discarded); that path is context delivery// too, so external capture must not suppress it.@@ -1103,6 +1132,15 @@ wherereturn Ok(());}};+ // Read before the Hermes shaping below drops `extra`, where it lives.+ let first_prompt_of_session = hook_event == HookEvent::UserPrompt+ && agent_kind.first_user_prompt_injects_handoff()+ && ai_memory_hooks::hermes_is_first_turn(&json);+ if agent_kind == AgentKind::Hermes+ && ai_memory_hooks::shape_hermes_lifecycle_body(&mut json, hook_event)+ {+ payload = serde_json::to_string(&json)?;+ }// Read before any capture rewrite can drop the prompt text.let reload_requested = hook_event == HookEvent::UserPrompt&& ai_memory_hooks::user_prompt_text(&json)@@ -1183,6 +1221,24 @@ wherepayload = serde_json::to_string(&json)?;}let (payload_cwd, canonical_session_id) = hook_context(&args.agent, &json);+ // Hermes reports its own process cwd on every event, which for a gateway+ // is wherever the gateway started. The session's working directory is+ // `terminal.cwd`, which Hermes exports to hooks as `TERMINAL_CWD`, so that+ // replaces the reported cwd. A tool event can still move to another+ // checkout its own absolute locations prove (below).+ let payload_cwd = match (agent_kind == AgentKind::Hermes)+ .then(|| hermes_terminal_cwd(&runtime_env))+ .flatten()+ {+ Some(cwd) => {+ if let Some(object) = json.as_object_mut() {+ object.insert("cwd".into(), cwd.clone().into());+ payload = serde_json::to_string(&json)?;+ }+ Some(cwd)+ }+ None => payload_cwd,+ };let tool_event = is_tool_event(&args.event);// Some harnesses report a cwd other than where the tool ran: a subagent's// parent session (#932), or Hermes' own process cwd while its tools take@@ -1694,6 +1750,30 @@ wherereturn Ok(());}+ // user-prompt: Hermes ignores `on_session_start` stdout, so the handoff+ // rides the session's first `pre_llm_call` instead, the only turn that+ // claims one. Later turns print `{}` without a fetch, so the turn is never+ // held for it, and a handoff written mid-session stays for the next one.+ if first_prompt_of_session && handoff_scoped {+ let client = build_client();+ let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;+ let native_session_qs = canonical_session_id+ .as_deref()+ .map_or_else(String::new, |session_id| {+ format!("&session_id={}", url_encode(session_id))+ });+ let handoff_url = format!(+ "{base}/handoff?agent={}{qs}{managed_qs}{native_session_qs}",+ args.agent+ );+ if let Some(handoff) =+ get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await+ {+ writeln!(stdout, "{}", first_prompt_context_envelope(handoff))?;+ return Ok(());+ }+ }+// post-tool-use: Grok shows hookSpecificOutput.additionalContext to the// model after the tool result. SessionStart and UserPromptSubmit stdout// are discarded, so this is the event that can carry a handoff without@@ -6665,6 +6745,7 @@ mod tests {&mut stdout,|_, _| Ok(()),Some(home.to_path_buf()),+ RuntimeEnv::from_process(),).await.unwrap();@@ -6908,6 +6989,7 @@ mod tests {&mut stdout,|_, _| Ok(()),Some(home),+ RuntimeEnv::from_process(),).await.unwrap();@@ -8047,6 +8129,420 @@ mod tests {}}+ fn hermes_args(event: &str, server_url: &str) -> HookArgs {+ let mut args = kimi_hook_args(event, server_url);+ args.agent = "hermes".into();+ args+ }++ /// The stdin envelope Hermes gives every shell hook+ /// (`_payload_fields` in `agent/shell_hooks.py`, v0.22.2).+ fn hermes_payload(hook_event_name: &str, cwd: &Path, extra: serde_json::Value) -> String {+ serde_json::json!({+ "hook_event_name": hook_event_name,+ "tool_name": null,+ "tool_input": null,+ "session_id": "hermes-session",+ "cwd": cwd,+ "profile": "default",+ "extra": extra,+ })+ .to_string()+ }++ fn pre_llm_call_extra(is_first_turn: bool) -> serde_json::Value {+ serde_json::json!({+ "task_id": "task-1",+ "turn_id": "turn-1",+ "user_message": "refactor the parser",+ "conversation_history": [+ {"role": "user", "content": "HISTORY_SENTINEL"}+ ],+ "is_first_turn": is_first_turn,+ "model": "hermes-4",+ "platform": "cli",+ "parent_session_id": "",+ "sender_id": ""+ })+ }++ /// Run one Hermes hook with an injected environment, so a test never+ /// inherits a `TERMINAL_CWD` from the shell running the suite.+ async fn run_hermes(+ data_dir: &Path,+ args: HookArgs,+ payload: String,+ runtime_env: RuntimeEnv,+ ) -> Vec<u8> {+ let mut stdout = Vec::new();+ run_with_payload_in_home(+ Some(data_dir.to_path_buf()),+ args,+ payload,+ &mut stdout,+ |_, _| Ok(()),+ None,+ runtime_env,+ )+ .await+ .unwrap();+ stdout+ }++ fn spooled_entries(data_dir: &Path) -> Vec<hook_spool::SpoolEntry> {+ let spool = hook_spool::spool_dir(data_dir);+ if spool.exists() {+ read_spooled_entries(&spool)+ } else {+ Vec::new()+ }+ }++ /// The first `pre_llm_call` of a session claims the handoff and prints the+ /// one shape Hermes adds to the turn: `{"context": "..."}`.+ #[tokio::test]+ async fn hermes_first_prompt_prints_the_handoff_as_context() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (base, mut requests) = serve_requests("200 OK", "HERMES-HANDOFF").await;+ let stdout = run_hermes(+ &data_dir,+ hermes_args("user-prompt-submit", &base),+ hermes_payload("pre_llm_call", tmp.path(), pre_llm_call_extra(true)),+ RuntimeEnv::default(),+ )+ .await;++ assert_eq!(+ String::from_utf8(stdout).unwrap(),+ "{\"context\":\"HERMES-HANDOFF\"}\n"+ );+ let request = first_request(&mut requests).await.unwrap();+ assert!(request.starts_with("GET /handoff?"), "{request}");+ assert!(request.contains("agent=hermes"), "{request}");+ assert!(request.contains("session_id=hermes-session"), "{request}");++ // The prompt was captured too, without the conversation history.+ let entries = spooled_entries(&data_dir);+ assert_eq!(entries.len(), 1);+ assert!(+ entries[0]+ .url+ .contains("event=user-prompt-submit&agent=hermes")+ );+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();+ assert_eq!(body["prompt"], "refactor the parser");+ assert_eq!(body["session_id"], "hermes-session");+ assert!(+ !entries[0].body.contains("HISTORY_SENTINEL"),+ "{}",+ entries[0].body+ );+ assert!(!entries[0].body.contains("conversation_history"));+ }++ /// No pending handoff on the first prompt: `{}`, which Hermes reads as+ /// "no context", never a bare body or an empty `context`.+ #[tokio::test]+ async fn hermes_first_prompt_without_a_handoff_prints_an_empty_object() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("404 Not Found", "").await;+ let stdout = run_hermes(+ &tmp.path().join("data"),+ hermes_args("user-prompt-submit", &base),+ hermes_payload("pre_llm_call", tmp.path(), pre_llm_call_extra(true)),+ RuntimeEnv::default(),+ )+ .await;+ assert_eq!(stdout, b"{}\n");+ let request = first_request(&mut requests).await.unwrap();+ assert!(request.starts_with("GET /handoff?"), "{request}");+ }++ /// `GET /handoff` claims the baton. A later turn, `on_session_start`+ /// (whose stdout Hermes ignores) and the turn and session ends must never+ /// send it, or the handoff would be consumed where nobody sees it.+ #[tokio::test]+ async fn hermes_never_claims_the_handoff_outside_the_first_prompt() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (base, mut requests) = serve_requests("200 OK", "HERMES-HANDOFF").await;+ for (event, payload) in [+ (+ "user-prompt-submit",+ hermes_payload("pre_llm_call", tmp.path(), pre_llm_call_extra(false)),+ ),+ (+ "session-start",+ hermes_payload(+ "on_session_start",+ tmp.path(),+ serde_json::json!({"model": "hermes-4", "platform": "cli"}),+ ),+ ),+ (+ "stop",+ hermes_payload(+ "on_session_end",+ tmp.path(),+ serde_json::json!({"completed": true, "turn_exit_reason": "done"}),+ ),+ ),+ (+ "session-end",+ hermes_payload(+ "on_session_finalize",+ tmp.path(),+ serde_json::json!({"platform": "cli", "reason": "shutdown"}),+ ),+ ),+ ] {+ let stdout = run_hermes(+ &data_dir,+ hermes_args(event, &base),+ payload,+ RuntimeEnv::default(),+ )+ .await;+ assert_eq!(stdout, b"{}\n", "{event}");+ }+ // The session-start backlog drain may POST spooled events; none of+ // the requests may touch /handoff.+ while let Some(request) = first_request(&mut requests).await {+ assert!(!request.starts_with("GET /handoff"), "{request}");+ }+ }++ /// `on_session_finalize` after a gateway `/new` names both sessions; only+ /// the ending one may be closed.+ #[tokio::test]+ async fn hermes_finalize_spools_the_ending_session_only() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let payload = serde_json::json!({+ "hook_event_name": "on_session_finalize",+ "tool_name": null,+ "tool_input": null,+ "session_id": "old-session",+ "cwd": tmp.path(),+ "profile": "default",+ "extra": {+ "platform": "telegram",+ "reason": "new_session",+ "old_session_id": "old-session",+ "new_session_id": "new-session"+ }+ })+ .to_string();+ let stdout = run_hermes(+ &data_dir,+ hermes_args("session-end", &dead_server_url()),+ payload,+ RuntimeEnv::default(),+ )+ .await;+ assert_eq!(stdout, b"{}\n");+ let entries = spooled_entries(&data_dir);+ assert_eq!(entries.len(), 1);+ assert!(entries[0].url.contains("event=session-end&agent=hermes"));+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();+ assert_eq!(body["session_id"], "old-session");+ assert_eq!(body["reason"], "new_session");+ assert!(+ !entries[0].body.contains("new-session"),+ "{}",+ entries[0].body+ );+ }++ #[test]+ fn hermes_terminal_cwd_takes_only_an_existing_absolute_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let file = tmp.path().join("file.txt");+ std::fs::write(&file, "x").unwrap();+ let dir = tmp.path().to_str().unwrap();+ let env = |value: &str| RuntimeEnv::with_process_env_for_tests(&[("TERMINAL_CWD", value)]);+ assert_eq!(hermes_terminal_cwd(&env(dir)).as_deref(), Some(dir));+ assert_eq!(hermes_terminal_cwd(&env("relative/dir")), None);+ assert_eq!(+ hermes_terminal_cwd(&env(&tmp.path().join("missing").to_string_lossy())),+ None+ );+ assert_eq!(hermes_terminal_cwd(&env(&file.to_string_lossy())), None);+ assert_eq!(hermes_terminal_cwd(&RuntimeEnv::default()), None);+ }++ /// A gateway reports its own process cwd (here an unmarked home); the+ /// session's project arrives as `TERMINAL_CWD`. Under allowlist mode the+ /// prompt is captured only because that variable selected the marked+ /// repository, and the body's cwd says so.+ #[tokio::test]+ async fn hermes_terminal_cwd_routes_lifecycle_events() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ std::fs::create_dir_all(&home).unwrap();+ let repo = repo_with_marker(+ tmp.path(),+ "some-repo",+ "workspace = \"w\"\nproject = \"some-repo\"\n",+ );+ let repo_str = repo.to_str().unwrap();+ let args = || {+ let mut args = hermes_args("user-prompt-submit", &dead_server_url());+ args.capture_mode = Some(crate::cli::CaptureModeArg::Allowlist);+ args+ };++ let data_dir = tmp.path().join("data-routed");+ run_hermes(+ &data_dir,+ args(),+ hermes_payload("pre_llm_call", &home, pre_llm_call_extra(false)),+ RuntimeEnv::with_process_env_for_tests(&[("TERMINAL_CWD", repo_str)]),+ )+ .await;+ let entries = spooled_entries(&data_dir);+ assert_eq!(entries.len(), 1);+ assert_eq!(query_param(&entries[0].url, "project"), Some("some-repo"));+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();+ assert_eq!(body["cwd"], repo_str);++ // Controls: no variable, or one that names nothing usable, leaves the+ // unmarked process cwd in charge, which allowlist mode drops.+ for (name, env) in [+ ("unset", RuntimeEnv::default()),+ (+ "relative",+ RuntimeEnv::with_process_env_for_tests(&[("TERMINAL_CWD", "some-repo")]),+ ),+ (+ "missing",+ RuntimeEnv::with_process_env_for_tests(&[(+ "TERMINAL_CWD",+ &tmp.path().join("gone").to_string_lossy(),+ )]),+ ),+ ] {+ let data_dir = tmp.path().join(format!("data-{name}"));+ run_hermes(+ &data_dir,+ args(),+ hermes_payload("pre_llm_call", &home, pre_llm_call_extra(false)),+ env,+ )+ .await;+ assert!(spooled_entries(&data_dir).is_empty(), "{name}");+ }+ }++ /// Adversarial: `TERMINAL_CWD` selects a checkout, so that checkout's+ /// exclusions and server profile apply to what lands there. A relative+ /// read of an excluded path is dropped before the spool, a public read is+ /// kept, and a marker naming an unregistered server profile drops the+ /// event instead of delivering it to the install default.+ #[tokio::test]+ async fn hermes_terminal_cwd_applies_the_selected_checkout_policy() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ std::fs::create_dir_all(&home).unwrap();+ let guarded = repo_with_marker(+ tmp.path(),+ "guarded",+ "project = \"guarded\"\n[capture]\nignore_paths = [\"secret/**\"]\n",+ );+ let routed_away = repo_with_marker(tmp.path(), "routed", "server = \"nobody\"\n");+ let read = |path: &str| {+ serde_json::json!({+ "hook_event_name": "post_tool_call",+ "tool_name": "read_file",+ "tool_input": {"path": path},+ "session_id": "hermes-session",+ "cwd": home,+ "extra": {"tool_call_id": "call-1", "status": "ok", "result": "SENTINEL_CONTENT"}+ })+ .to_string()+ };+ let env = |dir: &Path| {+ RuntimeEnv::with_process_env_for_tests(&[("TERMINAL_CWD", dir.to_str().unwrap())])+ };+ for (name, dir, path, spooled) in [+ ("excluded read", &guarded, "secret/token.txt", 0),+ ("public read", &guarded, "README.md", 1),+ ("refused profile", &routed_away, "README.md", 0),+ ] {+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));+ run_hermes(+ &data_dir,+ hermes_args("post-tool-use", &dead_server_url()),+ read(path),+ env(dir),+ )+ .await;+ let entries = spooled_entries(&data_dir);+ assert_eq!(entries.len(), spooled, "{name}");+ assert!(+ entries.iter().all(|e| !e.body.contains("secret/token")),+ "{name}"+ );+ }+ }++ /// Tool events fall back to `TERMINAL_CWD` when their own locations prove+ /// nothing, and an absolute location in another checkout still wins+ /// (#1199).+ #[tokio::test]+ async fn hermes_tool_events_prefer_their_locations_then_terminal_cwd() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ std::fs::create_dir_all(&home).unwrap();+ let session_repo =+ repo_with_marker(tmp.path(), "session-repo", "project = \"session-repo\"\n");+ let other_repo = repo_with_marker(tmp.path(), "other-repo", "project = \"other-repo\"\n");+ let env = RuntimeEnv::with_process_env_for_tests(&[(+ "TERMINAL_CWD",+ session_repo.to_str().unwrap(),+ )]);+ let tool = |input: serde_json::Value| {+ serde_json::json!({+ "hook_event_name": "post_tool_call",+ "tool_name": "terminal",+ "tool_input": input,+ "session_id": "hermes-session",+ "cwd": home,+ "extra": {"tool_call_id": "call-1", "status": "ok", "result": "ok"}+ })+ .to_string()+ };+ let args = || {+ let mut args = hermes_args("post-tool-use", &dead_server_url());+ args.capture_mode = Some(crate::cli::CaptureModeArg::Allowlist);+ args+ };++ for (name, input, project) in [+ (+ "no location",+ serde_json::json!({"command": "ls"}),+ "session-repo",+ ),+ (+ "other workdir",+ serde_json::json!({"command": "ls", "workdir": other_repo}),+ "other-repo",+ ),+ ] {+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));+ run_hermes(&data_dir, args(), tool(input), env.clone()).await;+ let entries = spooled_entries(&data_dir);+ assert_eq!(entries.len(), 1, "{name}");+ assert_eq!(+ query_param(&entries[0].url, "project"),+ Some(project),+ "{name}"+ );+ }+ }+fn write_briefing_marker(dir: &Path) {std::fs::write(dir.join(".ai-memory.toml"),diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 1a9e9f4f..f2559468 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -31,15 +31,15 @@ use crate::commands::openclaw_plugin;use crate::commands::path_util::{home_dir, strip_windows_verbatim_prefix};use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,- COPILOT_CLI_PROFILE, CURSOR_PROFILE, DSH_EVENTS, GEMINI_PROFILE, KIMI_CODE_EVENTS,- KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS, POOL_EVENTS, build_antigravity_payload_with_data_dir,- build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,- build_dsh_hooks_payload, build_grok_payload_with_data_dir, build_kiro_cli_v2_hooks_value,- build_kiro_cli_v3_hooks_value, build_pool_settings_yaml_with_data_dir,- build_profile_payload_for_agent, hook_embedded_exe_path, hook_script_for_claude_code,- hook_script_for_current_platform, kimi_code_hook_commands, local_hook_policy_v1_supported,- ts_auth_headers_fn, ts_capture_policy_v1, ts_string_literal, ts_timeout_signal,- yaml_single_quote,+ COPILOT_CLI_PROFILE, CURSOR_PROFILE, DSH_EVENTS, GEMINI_PROFILE, HermesHookSet,+ KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS, POOL_EVENTS,+ build_antigravity_payload_with_data_dir, build_claude_code_payload_with_data_dir,+ build_devin_payload_with_data_dir, build_dsh_hooks_payload, build_grok_payload_with_data_dir,+ build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,+ build_pool_settings_yaml_with_data_dir, build_profile_payload_for_agent,+ hook_embedded_exe_path, hook_script_for_claude_code, hook_script_for_current_platform,+ kimi_code_hook_commands, local_hook_policy_v1_supported, ts_auth_headers_fn,+ ts_capture_policy_v1, ts_string_literal, ts_timeout_signal, yaml_single_quote,};use crate::commands::uninstall::hook_command_is_ours;use crate::config::{Config, DEFAULT_SERVER_URL};@@ -941,14 +941,18 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(}AgentChoice::Zero => apply_to_zero_hooks(&server_url, auth, &config.data_dir, &args),AgentChoice::Zcode => apply_to_zcode_hooks(&server_url, auth, &config.data_dir, &args),- AgentChoice::Hermes => {- // Nothing to write or stage: the block invokes the native- // `hook` subcommand, and `~/.hermes/config.yaml` is a YAML file- // the operator also edits (and Hermes itself gates hooks behind- // an acceptance prompt). The render step below prints the- // ready-to-paste block.- Ok(())- }+ // Nothing to write or stage: the block invokes the native `hook`+ // subcommand, and `~/.hermes/config.yaml` is a YAML file the+ // operator also edits (and Hermes itself gates hooks behind an+ // acceptance prompt). `--apply` prints the same ready-to-paste+ // block a preview does.+ AgentChoice::Hermes => render_hermes(+ &server_url,+ auth,+ &config.data_dir,+ args.project_strategy.and_then(ProjectStrategyArg::baked),+ hermes_plugin_dir(&config.runtime_env).as_deref(),+ ),AgentChoice::Devin => {let hooks_dir =resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;@@ -1136,7 +1140,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(}AgentChoice::Zero => render_zero(&server_url, auth, &config.data_dir, strategy),AgentChoice::Zcode => render_zcode(&server_url, auth, &config.data_dir, strategy),- AgentChoice::Hermes => render_hermes(&server_url, auth, &config.data_dir, strategy),+ AgentChoice::Hermes => render_hermes(+ &server_url,+ auth,+ &config.data_dir,+ strategy,+ hermes_plugin_dir(&config.runtime_env).as_deref(),+ ),AgentChoice::Devin => {let hooks_dir =resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;@@ -7042,6 +7052,34 @@ fn render_zcode(Ok(())}+/// Where the community ai-memory memory-provider plugin for Hermes installs+/// itself: `$HERMES_HOME/plugins/ai-memory`, with `HERMES_HOME` defaulting to+/// `~/.hermes` as Hermes and the plugin's installer both resolve it. Both+/// variables come from the captured environment (invariant #1).+pub(crate) fn hermes_plugin_dir(env: &crate::config::RuntimeEnv) -> Option<PathBuf> {+ hermes_plugin_dir_in(env.var_os("HERMES_HOME"), env.home_dir().map(PathBuf::from))+}++fn hermes_plugin_dir_in(+ hermes_home: Option<std::ffi::OsString>,+ home: Option<PathBuf>,+) -> Option<PathBuf> {+ crate::commands::path_util::agent_config_home(hermes_home)+ .or_else(|| home.map(|home| home.join(".hermes")))+ .map(|hermes_home| hermes_home.join("plugins").join("ai-memory"))+}++/// The plugin posts prompts and session ends and claims the handoff itself,+/// so where it is installed the hooks wire the tool events alone. A plain+/// directory check, so the same machine always renders the same block.+pub(crate) fn hermes_hook_set(plugin_dir: Option<&Path>) -> HermesHookSet {+ if plugin_dir.is_some_and(Path::is_dir) {+ HermesHookSet::ToolsOnly+ } else {+ HermesHookSet::Full+ }+}+/// `install-hooks --agent hermes`: print the ready-to-paste `hooks:` block for/// `~/.hermes/config.yaml`.///@@ -7056,10 +7094,17 @@ fn render_hermes(auth_token: Option<&str>,data_dir: &Path,project_strategy: Option<&str>,+ plugin_dir: Option<&Path>,) -> Result<()> {print!("{}",- render_hermes_output(server_url, auth_token, data_dir, project_strategy)+ render_hermes_output(+ server_url,+ auth_token,+ data_dir,+ project_strategy,+ plugin_dir+ ));Ok(())}@@ -7069,28 +7114,28 @@ fn render_hermes_output(auth_token: Option<&str>,data_dir: &Path,project_strategy: Option<&str>,+ plugin_dir: Option<&Path>,) -> String {+ let hook_set = hermes_hook_set(plugin_dir);let block = super::render_shared::build_hermes_hooks_yaml(server_url,auth_token,Some(data_dir),project_strategy,+ hook_set,);let mut out = String::new();out.push_str("# Hermes Agent hooks config — merge the `hooks:` block below\n");out.push_str("# into ~/.hermes/config.yaml and let Hermes accept it when it\n");out.push_str("# prompts (or set `hooks_auto_accept: true`). ai-memory does not\n");out.push_str("# write that file: it is YAML you also edit, and it would have to\n");- out.push_str("# be spliced.\n");+ out.push_str("# be spliced. Restart Hermes (and its gateway) to load it.\n");out.push_str(&format!("# AI-memory server URL: {server_url}\n"));if auth_token.is_some() {out.push_str("# Auth: this snippet embeds the token in each hook command —\n");out.push_str("# treat ~/.hermes/config.yaml as sensitive (chmod 600).\n");}- out.push_str("# NOTE: only the two tool events are wired — that is what gives\n");- out.push_str("# Hermes tool observations. Session lifecycle (prompts,\n");- out.push_str("# session-end, the automatic handoff) is handled by the\n");- out.push_str("# ai-memory memory-provider plugin, so nothing is duplicated.\n");+ out.push_str(&hermes_hook_set_notes(hook_set, plugin_dir));out.push_str("# NOTE: each `command` is a bare argv line. Hermes splits it with\n");out.push_str("# shlex.split and runs it without a shell, so the generated\n");out.push_str("# command invokes the ai-memory binary directly.\n");@@ -7099,6 +7144,36 @@ fn render_hermes_output(out}+/// The comment lines that say which Hermes events the block wires and why.+/// Shared with `setup-agent`, which renders the same block.+pub(crate) fn hermes_hook_set_notes(hook_set: HermesHookSet, plugin_dir: Option<&Path>) -> String {+ let plugin = plugin_dir.map_or_else(+ || "$HERMES_HOME/plugins/ai-memory".to_owned(),+ |dir| dir.display().to_string(),+ );+ match hook_set {+ HermesHookSet::ToolsOnly => format!(+ "# NOTE: only the two tool events are wired. The ai-memory\n\+ # memory-provider plugin is installed at {plugin}\n\+ # and already captures prompts, ends sessions and claims\n\+ # the handoff; wiring those here too would capture every\n\+ # prompt twice and race the plugin for the handoff.\n"+ ),+ HermesHookSet::Full => format!(+ "# NOTE: tool events plus the session lifecycle. pre_llm_call\n\+ # captures each prompt and brings the pending handoff into\n\+ # the session's first turn; on_session_end marks a turn\n\+ # (Hermes fires it after every turn) and on_session_finalize\n\+ # ends the session.\n\+ # NOTE: a gateway session that expires idle is never finalized;\n\+ # close it with `ai-memory finalize-session --agent hermes`.\n\+ # NOTE: if you install the ai-memory memory-provider plugin\n\+ # ({plugin}), keep only pre_tool_call and\n\+ # post_tool_call: the plugin covers the rest.\n"+ ),+ }+}+/// Merge ai-memory's entries into Droid's `hooks.json` (#1240), keeping/// every other entry in it, idempotently.///@@ -10202,28 +10277,105 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/aassert_eq!(fs::read_to_string(target).unwrap(), "untouched");}- /// Hermes' output must state the manual paste step (ai-memory does not write- /// `~/.hermes/config.yaml`) and must not advertise a staged bundle or a- /// session-end hook — the memory-provider plugin owns session lifecycle.+ /// Without the community plugin, Hermes' output wires the whole lifecycle+ /// natively and still states the manual paste step (ai-memory does not+ /// write `~/.hermes/config.yaml`).#[test]- fn render_hermes_output_states_manual_paste_and_plugin_owned_lifecycle() {- let out = render_hermes_output("http://127.0.0.1:49374", None, Path::new("/data"), None);+ fn render_hermes_output_wires_the_lifecycle_without_the_plugin() {+ let tmp = tempfile::tempdir().unwrap();+ let plugin = tmp.path().join(".hermes").join("plugins").join("ai-memory");+ let out = render_hermes_output(+ "http://127.0.0.1:49374",+ None,+ Path::new("/data"),+ None,+ Some(&plugin),+ );assert!(out.contains("~/.hermes/config.yaml"));assert!(out.contains("ai-memory does not"));assert!(out.contains("hooks:\n"));- assert!(out.contains("pre_tool_call"));- assert!(out.contains("post_tool_call"));assert!(out.contains("--agent hermes"));assert!(out.contains("without a shell"));- assert!(out.contains("memory-provider plugin"));- // Tool events only: a hook-driven session-end would double-close a- // session the plugin already closes.- assert!(!out.contains("session_end"));- assert!(!out.contains("session-end:"));+ for event in [+ "pre_tool_call:",+ "post_tool_call:",+ "on_session_start:",+ "pre_llm_call:",+ "on_session_end:",+ "on_session_finalize:",+ ] {+ assert!(out.contains(event), "missing {event}");+ }+ assert!(out.contains("--event session-end "));+ assert!(out.contains("--event user-prompt-submit "));+ assert!(out.contains("finalize-session --agent hermes"));+ // The operator learns what to drop if the plugin arrives later.+ assert!(out.contains(&plugin.display().to_string()));// No token was passed, so the auth caution line stays out.assert!(!out.contains("chmod 600"));}+ /// With the community plugin installed, only the tool events are wired:+ /// the plugin already posts prompts and session ends and claims the+ /// handoff, so a second lifecycle path would double both.+ #[test]+ fn render_hermes_output_keeps_tool_events_only_beside_the_plugin() {+ let tmp = tempfile::tempdir().unwrap();+ let plugin = tmp.path().join(".hermes").join("plugins").join("ai-memory");+ fs::create_dir_all(&plugin).unwrap();+ let out = render_hermes_output(+ "http://127.0.0.1:49374",+ None,+ Path::new("/data"),+ None,+ Some(&plugin),+ );+ assert!(out.contains("pre_tool_call:"));+ assert!(out.contains("post_tool_call:"));+ for event in [+ "on_session_start:",+ "pre_llm_call:",+ "on_session_end:",+ "on_session_finalize:",+ ] {+ assert!(!out.contains(event), "{event} belongs to the plugin");+ }+ assert!(!out.contains("--event session-end"));+ assert!(!out.contains("--event user-prompt-submit"));+ assert!(out.contains("memory-provider plugin is installed at"));+ assert!(out.contains(&plugin.display().to_string()));+ }++ #[test]+ fn hermes_plugin_dir_follows_hermes_home_then_the_home_default() {+ let home = PathBuf::from("/home/alice");+ assert_eq!(+ hermes_plugin_dir_in(None, Some(home.clone())),+ Some(home.join(".hermes").join("plugins").join("ai-memory"))+ );+ assert_eq!(+ hermes_plugin_dir_in(Some("/srv/hermes".into()), Some(home.clone())),+ Some(+ PathBuf::from("/srv/hermes")+ .join("plugins")+ .join("ai-memory")+ )+ );+ // A blank HERMES_HOME is an unset expansion, not the filesystem root.+ assert_eq!(+ hermes_plugin_dir_in(Some(" ".into()), Some(home.clone())),+ Some(home.join(".hermes").join("plugins").join("ai-memory"))+ );+ assert_eq!(hermes_plugin_dir_in(None, None), None);+ // A file of that name is not an installed plugin.+ let tmp = tempfile::tempdir().unwrap();+ let file = tmp.path().join("ai-memory");+ fs::write(&file, "").unwrap();+ assert_eq!(hermes_hook_set(Some(&file)), HermesHookSet::Full);+ assert_eq!(hermes_hook_set(None), HermesHookSet::Full);+ assert_eq!(hermes_hook_set(Some(tmp.path())), HermesHookSet::ToolsOnly);+ }+// Issue #156: Zero hook install writes exec-form entries into Zero's// hooks.json shape and merges around third-party hooks by id prefix.#[test]diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 4d753513..80819071 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -1019,25 +1019,61 @@ pub(crate) const ZCODE_HOOK_TIMEOUT_MS: u64 = 10_000;/// (same reasoning as Kiro v2's `max_output_size`).pub(crate) const ZCODE_HOOK_MAX_OUTPUT_BYTES: usize = 64 * 1024;-/// Hermes Agent lifecycle events ai-memory hooks. Each pair is+/// Hermes Agent tool events ai-memory hooks. Each pair is/// `(event-name-in-~/.hermes/config.yaml, native `hook --event` value)`.///-/// Verified against Hermes v0.21.4 (`agent/shell_hooks.py`): a configured+/// Verified against Hermes v0.22.2 (`agent/shell_hooks.py`): a configured/// `command` is split into argv by `shlex.split` and executed **without a/// shell**, with the event JSON on stdin — so the generated block invokes the/// native `hook` subcommand, the same shape Zero and ZCode use, and no-/// `.sh`/`.ps1` bundle is staged. Only the two tool events are wired: their-/// payload carries `tool_name` / `tool_input`, the envelope the router already-/// maps for `agent=hermes`. Session lifecycle stays with the memory-provider-/// plugin (`on_session_end`), so a hook-driven `session-end` cannot-/// double-close a Hermes session.-pub(crate) const HERMES_EVENTS: [(&str, &str); 2] = [+/// `.sh`/`.ps1` bundle is staged. Hermes fires a shell hook for every event it+/// defines, with one stdin envelope (`hook_event_name`, `tool_name`,+/// `tool_input`, `session_id`, `cwd`, `extra`).+pub(crate) const HERMES_TOOL_EVENTS: [(&str, &str); 2] = [("pre_tool_call", "pre-tool-use"),("post_tool_call", "post-tool-use"),];+/// Hermes session lifecycle events, mapped by meaning rather than name:+///+/// - `on_session_start` fires on a new session's first turn. Hermes ignores+/// its stdout, so it only records the start; the handoff is never fetched+/// there, because that fetch claims it.+/// - `pre_llm_call` fires before every turn with the prompt in+/// `extra.user_message`. On the session's first turn its+/// `{"context": ...}` stdout carries the handoff into the turn.+/// - `on_session_end` fires at the end of **every turn**, not of the session,+/// so it is a turn boundary (`stop`).+/// - `on_session_finalize` is the real end: CLI exit, `/new`, gateway+/// shutdown. A gateway session that expires idle is never finalized, which+/// `ai-memory finalize-session --agent hermes` covers.+///+/// `post_llm_call` (assistant text) and `subagent_*` are not wired: assistant+/// capture is native-only, and a delegated child is not a session of its own.+pub(crate) const HERMES_LIFECYCLE_EVENTS: [(&str, &str); 4] = [+ ("on_session_start", "session-start"),+ ("pre_llm_call", "user-prompt-submit"),+ ("on_session_end", "stop"),+ ("on_session_finalize", "session-end"),+];++/// Which Hermes events the generated `hooks:` block wires.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum HermesHookSet {+ /// Tool and lifecycle events: ai-memory owns the whole Hermes session.+ Full,+ /// Tool events only. The community ai-memory memory-provider plugin+ /// already posts prompts and session ends and claims the handoff, so a+ /// second lifecycle path would capture each prompt twice and race it for+ /// the handoff.+ ToolsOnly,+}+/// Wall-clock bound written into each Hermes hook entry. Capture POSTs are-/// fire-and-forget, so this only bounds a hung `hook` invocation.+/// fire-and-forget and the first-turn handoff fetch has its own short+/// timeout, so this only bounds a hung `hook` invocation. Hermes bounds a+/// blocking hook's callback at 30 s by default, and `pre_llm_call` holds+/// the turn while it runs, so the entry stays well under that.pub(crate) const HERMES_HOOK_TIMEOUT_SECONDS: u64 = 20;/// The ready-to-paste `hooks:` block for `~/.hermes/config.yaml`.@@ -1055,6 +1091,7 @@ pub(crate) fn build_hermes_hooks_yaml(auth_token: Option<&str>,data_dir: Option<&Path>,project_strategy: Option<&str>,+ hook_set: HermesHookSet,) -> String {build_hermes_hooks_yaml_for_platform(server_url,@@ -1065,18 +1102,30 @@ pub(crate) fn build_hermes_hooks_yaml(data_dir,project_strategy,),+ hook_set,)}+/// The events [`build_hermes_hooks_yaml`] wires for `hook_set`, tool events+/// first.+pub(crate) fn hermes_events(hook_set: HermesHookSet) -> Vec<(&'static str, &'static str)> {+ let mut events = HERMES_TOOL_EVENTS.to_vec();+ if hook_set == HermesHookSet::Full {+ events.extend(HERMES_LIFECYCLE_EVENTS);+ }+ events+}+/// Platform-forced variant, so a test can pin POSIX/Windows instead of/// asserting whatever the machine running the suite happens to be.fn build_hermes_hooks_yaml_for_platform(server_url: &str,auth_token: Option<&str>,context: HookCommandContext<'_>,+ hook_set: HermesHookSet,) -> String {let mut out = String::from("hooks:\n");- for (hermes_event, our_event) in HERMES_EVENTS {+ for (hermes_event, our_event) in hermes_events(hook_set) {// The native platforms derive the event token from the script stem, so// the synthetic filename carries the ai-memory event name.let command = hook_command(@@ -4057,24 +4106,53 @@ if (inheritOnly) {assert!(args.iter().all(|arg| !arg.contains(r"\\?\")));}- /// The public entry point must emit a complete `hooks:` map with both tool- /// events, whatever platform it renders for (the suite runs on Windows too).+ /// The public entry point must emit a complete `hooks:` map, whatever+ /// platform it renders for (the suite runs on Windows too): every tool and+ /// lifecycle event in full, the tool events alone beside the plugin.#[test]- fn hermes_hooks_yaml_covers_both_tool_events() {- let yaml = build_hermes_hooks_yaml("http://127.0.0.1:49374", None, None, None);- assert!(yaml.starts_with("hooks:\n"));- for (event, _) in HERMES_EVENTS {- assert!(yaml.contains(&format!(" {event}:\n")), "missing {event}");- assert!(- yaml.contains(" - command: '"),- "command must be a single-quoted YAML scalar"+ fn hermes_hooks_yaml_wires_the_full_lifecycle_or_the_tool_events_only() {+ let full = build_hermes_hooks_yaml(+ "http://127.0.0.1:49374",+ None,+ None,+ None,+ HermesHookSet::Full,+ );+ let tools = build_hermes_hooks_yaml(+ "http://127.0.0.1:49374",+ None,+ None,+ None,+ HermesHookSet::ToolsOnly,+ );+ for (yaml, events) in [+ (&full, hermes_events(HermesHookSet::Full)),+ (&tools, hermes_events(HermesHookSet::ToolsOnly)),+ ] {+ assert!(yaml.starts_with("hooks:\n"));+ for (event, _) in &events {+ assert!(yaml.contains(&format!("\n {event}:\n")), "missing {event}");+ }+ assert_eq!(yaml.matches(" - command: '").count(), events.len());+ assert_eq!(+ yaml.matches(&format!("timeout: {HERMES_HOOK_TIMEOUT_SECONDS}"))+ .count(),+ events.len());}+ assert_eq!(hermes_events(HermesHookSet::Full).len(), 6);assert_eq!(- yaml.matches(&format!("timeout: {HERMES_HOOK_TIMEOUT_SECONDS}"))- .count(),- HERMES_EVENTS.len()+ hermes_events(HermesHookSet::ToolsOnly),+ HERMES_TOOL_EVENTS.to_vec());+ for (event, our_event) in HERMES_LIFECYCLE_EVENTS {+ assert!(!tools.contains(event), "{event} must stay with the plugin");+ assert!(!tools.contains(&format!("--event {our_event} ")));+ }+ // Assistant text is native-only, and subagents are not sessions.+ for unwired in ["post_llm_call", "subagent_start", "subagent_stop"] {+ assert!(!full.contains(unwired), "{unwired}");+ }}/// Hermes splits `command` with `shlex.split` and runs it with no shell, so@@ -4091,8 +4169,9 @@ if (inheritOnly) {Some(Path::new("/data")),Some("repo-root"),),+ HermesHookSet::Full,);- for (_, our_event) in HERMES_EVENTS {+ for (_, our_event) in hermes_events(HermesHookSet::Full) {assert!(yaml.contains(&format!("hook --event {our_event} --agent hermes")),"missing the native command for {our_event}"diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex e2560c82..08a163f8 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -111,7 +111,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {// Hermes also runs the native `hook` command directly (no shell), so there// are no scripts to stage — setup-agent prints the YAML block instead.if matches!(args.agent, AgentChoice::Hermes) {- emit_hermes(&args)?;+ let plugin_dir = install_hooks::hermes_plugin_dir(&config.runtime_env);+ print!("{}", hermes_setup_output(&args, plugin_dir.as_deref()));return Ok(());}// Droid has no script bundle either: its hooks.json runs the native@@ -317,27 +318,34 @@ fn emit_zcode(args: &SetupAgentArgs) -> Result<()> {/// runs the ai-memory binary directly with the JSON payload on stdin. The/// binary must be reachable on the host that runs Hermes — for docker-wrapper/// setups install the native binary or point `command` at the wrapper.-fn emit_hermes(args: &SetupAgentArgs) -> Result<()> {+///+/// The community memory-provider plugin is looked for where this command+/// runs. Inside a container that is not the host's Hermes home, which is why+/// the full block also says which entries to drop beside the plugin.+fn hermes_setup_output(args: &SetupAgentArgs, plugin_dir: Option<&Path>) -> String {+ let hook_set = install_hooks::hermes_hook_set(plugin_dir);let block = crate::commands::render_shared::build_hermes_hooks_yaml(&args.server_url,args.auth_token.as_deref(),None,None,+ hook_set,);- println!("# Hermes Agent — merge the `hooks:` block into ~/.hermes/config.yaml");- println!("# The `command` must be an ai-memory binary reachable on the host that");- println!("# runs Hermes; prefer `ai-memory install-hooks --agent hermes` from");- println!("# that host so the path is resolved for you.");+ let mut out = String::new();+ out.push_str("# Hermes Agent — merge the `hooks:` block into ~/.hermes/config.yaml\n");+ out.push_str("# The `command` must be an ai-memory binary reachable on the host that\n");+ out.push_str("# runs Hermes; prefer `ai-memory install-hooks --agent hermes` from\n");+ out.push_str("# that host so the path is resolved for you.\n");if args.auth_token.is_some() {- println!("# Treat the config as sensitive (chmod 600).");+ out.push_str("# Treat the config as sensitive (chmod 600).\n");}- println!("# NOTE: Hermes splits each `command` with shlex.split and runs it with");- println!("# no shell, so the generated line is argv, not a shell command.");- println!("# NOTE: tool observations only — session lifecycle stays with the");- println!("# ai-memory memory-provider plugin.");- println!();- println!("{block}");- Ok(())+ out.push_str("# NOTE: Hermes splits each `command` with shlex.split and runs it with\n");+ out.push_str("# no shell, so the generated line is argv, not a shell command.\n");+ out.push_str(&install_hooks::hermes_hook_set_notes(hook_set, plugin_dir));+ out.push('\n');+ out.push_str(&block);+ out.push('\n');+ out}/// Print the event map for `~/.factory/hooks.json` (#1240). No scripts are@@ -854,6 +862,49 @@ fn source_candidates(explicit: Option<&Path>, sub: &str, exe: Option<PathBuf>) -mod tests {use super::*;+ fn hermes_setup_args() -> SetupAgentArgs {+ use clap::Parser as _;+ let cli = crate::cli::Cli::try_parse_from([+ "ai-memory",+ "setup-agent",+ "--agent",+ "hermes",+ "--to",+ "/host/hooks",+ ])+ .unwrap();+ let crate::cli::Command::SetupAgent(args) = cli.command else {+ panic!("expected setup-agent");+ };+ args+ }++ /// `setup-agent --agent hermes` renders the same two blocks as+ /// `install-hooks`: the whole lifecycle, or the tool events alone when the+ /// community plugin is installed.+ #[test]+ fn hermes_setup_output_follows_the_plugin_check() {+ let tmp = tempfile::tempdir().unwrap();+ let plugin = tmp.path().join("plugins").join("ai-memory");+ let full = hermes_setup_output(&hermes_setup_args(), Some(&plugin));+ assert!(full.contains("pre_llm_call:") && full.contains("on_session_finalize:"));+ assert!(full.contains("pre_tool_call:") && full.contains("post_tool_call:"));+ assert!(full.contains("keep only pre_tool_call"));++ std::fs::create_dir_all(&plugin).unwrap();+ let tools = hermes_setup_output(&hermes_setup_args(), Some(&plugin));+ assert!(tools.contains("pre_tool_call:") && tools.contains("post_tool_call:"));+ for event in [+ "on_session_start:",+ "pre_llm_call:",+ "on_session_end:",+ "on_session_finalize:",+ ] {+ assert!(!tools.contains(event), "{event}");+ }+ assert!(tools.contains("memory-provider plugin is installed at"));+ }+#[test]fn source_candidates_include_binary_sibling_for_flat_tarball() {// Flat release tarball: the binary and its `hooks/` bundle arediff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 78f0727d..299a786b 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -518,6 +518,21 @@ impl AgentKind {matches!(self, Self::KimiCode)}+ /// Whether this agent adds the native `user-prompt` hook's stdout to the+ /// turn only on the first prompt of a session, which the payload itself+ /// marks.+ ///+ /// Hermes Agent ignores `on_session_start` stdout but adds a+ /// `pre_llm_call` hook's `{"context": "..."}` to the user message, and+ /// flags the session's first turn with `extra.is_first_turn`+ /// (`agent/turn_context.py`, `agent/shell_hooks.py`, v0.22.2). The+ /// handoff is claimed on that turn alone: `pre_llm_call` holds every turn+ /// while it runs, so later turns skip the round-trip.+ #[must_use]+ pub fn first_user_prompt_injects_handoff(self) -> bool {+ matches!(self, Self::Hermes)+ }+/// Whether this agent adds a `UserPromptSubmit` hook's/// `hookSpecificOutput.additionalContext` to the turn it belongs to.///@@ -684,7 +699,7 @@ mod tests {}#[test]- fn agent_kind_hermes_round_trips_without_claiming_handoff_delivery() {+ fn agent_kind_hermes_round_trips_and_claims_the_handoff_on_the_first_prompt_only() {assert_eq!(AgentKind::Hermes.as_str(), "hermes");assert_eq!(AgentKind::from_wire("hermes"), AgentKind::Hermes);assert_eq!(AgentKind::from_wire("hermes-agent"), AgentKind::Hermes);@@ -696,8 +711,16 @@ mod tests {serde_json::to_string(&AgentKind::Hermes).unwrap(),"\"hermes\"");+ // `on_session_start` stdout is ignored, so the destructive fetch must+ // not run there; the first `pre_llm_call` carries it instead.assert!(!AgentKind::Hermes.session_start_injects_handoff());assert!(!AgentKind::Hermes.user_prompt_injects_handoff());+ assert!(AgentKind::Hermes.first_user_prompt_injects_handoff());+ for other in AgentKind::ALL {+ if other != AgentKind::Hermes {+ assert!(!other.first_user_prompt_injects_handoff(), "{other:?}");+ }+ }}#[test]diff --git a/crates/ai-memory-hooks/src/hermes.rs b/crates/ai-memory-hooks/src/hermes.rsnew file mode 100644index 00000000..b3030f18--- /dev/null+++ b/crates/ai-memory-hooks/src/hermes.rs@@ -0,0 +1,332 @@+//! Hermes Agent lifecycle payloads, shaped before the native hook spools them.+//!+//! Hermes runs every configured shell hook with one stdin envelope+//! (`agent/shell_hooks.py`, v0.22.2): `hook_event_name`, `tool_name`,+//! `tool_input`, `session_id`, `cwd`, `profile`, and an `extra` object holding+//! every other keyword argument of the event. The tool events already parse as+//! sent. The lifecycle events do not, and two of them carry more than+//! ai-memory may keep:+//!+//! - `pre_llm_call` puts the prompt in `extra.user_message`, a string or a list+//! of content parts, next to `extra.conversation_history`, the whole+//! conversation so far. Only the prompt's text is kept.+//! - `on_session_finalize` names the ending session in `session_id`. A gateway+//! `/new` also sends `extra.old_session_id` and `extra.new_session_id`+//! (`gateway/slash_commands_session.py`). Only the ending id is kept, so the+//! session that has just begun cannot be closed by it.+//! - `on_session_start` and `on_session_end`, which Hermes fires at the end of+//! every turn rather than at session end, carry nothing stored beyond the+//! session id.+//!+//! Hook reference: <https://hermes-agent.nousresearch.com/docs/user-guide/features/hooks>.++use serde_json::{Map, Value};++use crate::payload::HookEvent;++/// Part types Hermes itself drops when it flattens message content+/// (`agent/message_content.py`).+const NON_TEXT_PART_TYPES: [&str; 5] =+ ["image", "image_url", "input_image", "audio", "input_audio"];++/// Keys Hermes reads a text part's text from, in its order.+const TEXT_PART_KEYS: [&str; 5] = [+ "text",+ "content",+ "input_text",+ "output_text",+ "summary_text",+];++/// Whether a Hermes `pre_llm_call` payload is the first turn of its session.+/// Hermes sets `extra.is_first_turn` when the turn starts with no prior+/// history (`agent/turn_context.py`); a resumed session never sets it.+#[must_use]+pub fn hermes_is_first_turn(raw: &Value) -> bool {+ raw.pointer("/extra/is_first_turn").and_then(Value::as_bool) == Some(true)+}++/// Replace a Hermes lifecycle payload with the fields ai-memory stores, in the+/// shape the router reads. Returns whether the payload changed; tool events and+/// non-object payloads are left alone.+pub fn shape_hermes_lifecycle_body(raw: &mut Value, event: HookEvent) -> bool {+ if !matches!(+ event,+ HookEvent::SessionStart | HookEvent::UserPrompt | HookEvent::Stop | HookEvent::SessionEnd+ ) || !raw.is_object()+ {+ return false;+ }+ let extra = raw.get("extra").and_then(Value::as_object);+ let extra_string = |key: &str| {+ extra+ .and_then(|extra| extra.get(key))+ .and_then(Value::as_str)+ .filter(|value| !value.trim().is_empty())+ };+ let mut shaped = Map::new();+ for key in ["hook_event_name", "cwd"] {+ if let Some(value) = raw.get(key).and_then(Value::as_str) {+ shaped.insert(key.into(), value.into());+ }+ }+ let session_id = match event {+ HookEvent::SessionEnd => extra_string("old_session_id"),+ _ => None,+ }+ .or_else(|| {+ raw.get("session_id")+ .and_then(Value::as_str)+ .filter(|value| !value.trim().is_empty())+ });+ if let Some(session_id) = session_id {+ shaped.insert("session_id".into(), session_id.into());+ }+ match event {+ HookEvent::SessionStart => {+ if let Some(model) = extra_string("model") {+ shaped.insert("model".into(), model.into());+ }+ }+ HookEvent::UserPrompt => {+ if let Some(prompt) = extra+ .and_then(|extra| extra.get("user_message"))+ .and_then(prompt_text)+ {+ shaped.insert("prompt".into(), prompt.into());+ }+ }+ HookEvent::SessionEnd => {+ if let Some(reason) = extra_string("reason") {+ shaped.insert("reason".into(), reason.into());+ }+ }+ _ => {}+ }+ *raw = Value::Object(shaped);+ true+}++/// The visible text of `extra.user_message`, flattened the way Hermes does+/// it: a string as is, a list joined by line, and image or audio parts+/// dropped.+fn prompt_text(message: &Value) -> Option<String> {+ let text = match message {+ Value::Array(parts) => parts+ .iter()+ .filter_map(part_text)+ .filter(|text| !text.is_empty())+ .collect::<Vec<_>>()+ .join("\n"),+ other => part_text(other)?.to_owned(),+ };+ (!text.trim().is_empty()).then_some(text)+}++fn part_text(part: &Value) -> Option<&str> {+ match part {+ Value::String(text) => Some(text),+ Value::Object(fields) => {+ let kind = fields+ .get("type")+ .and_then(Value::as_str)+ .map(|kind| kind.trim().to_ascii_lowercase());+ if kind.is_some_and(|kind| NON_TEXT_PART_TYPES.contains(&kind.as_str())) {+ return None;+ }+ TEXT_PART_KEYS+ .iter()+ .find_map(|key| fields.get(*key).and_then(Value::as_str))+ }+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn pre_llm_call(user_message: Value) -> Value {+ json!({+ "hook_event_name": "pre_llm_call",+ "tool_name": null,+ "tool_input": null,+ "session_id": "hermes-session",+ "cwd": "/home/alice",+ "profile": "default",+ "extra": {+ "task_id": "task-1",+ "turn_id": "turn-1",+ "user_message": user_message,+ "conversation_history": [+ {"role": "user", "content": "HISTORY_SENTINEL earlier prompt"},+ {"role": "assistant", "content": "HISTORY_SENTINEL earlier answer"}+ ],+ "is_first_turn": false,+ "model": "hermes-4",+ "platform": "cli",+ "sender_id": ""+ }+ })+ }++ #[test]+ fn prompt_keeps_the_user_message_and_never_the_history() {+ let mut raw = pre_llm_call(json!("fix the flaky test"));+ assert!(shape_hermes_lifecycle_body(&mut raw, HookEvent::UserPrompt));+ assert_eq!(+ raw,+ json!({+ "hook_event_name": "pre_llm_call",+ "cwd": "/home/alice",+ "session_id": "hermes-session",+ "prompt": "fix the flaky test"+ })+ );+ assert!(!raw.to_string().contains("HISTORY_SENTINEL"));+ assert_eq!(+ crate::payload::user_prompt_text(&raw).as_deref(),+ Some("fix the flaky test")+ );+ }++ #[test]+ fn prompt_content_parts_keep_only_their_text() {+ let mut raw = pre_llm_call(json!([+ {"type": "text", "text": "describe this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,SECRETPIXELS"}},+ {"type": "input_audio", "input_audio": {"data": "AUDIOBYTES"}},+ "and this",+ {"type": "input_text", "input_text": "plus that"}+ ]));+ assert!(shape_hermes_lifecycle_body(&mut raw, HookEvent::UserPrompt));+ assert_eq!(raw["prompt"], "describe this\nand this\nplus that");+ let text = raw.to_string();+ assert!(!text.contains("SECRETPIXELS") && !text.contains("AUDIOBYTES"));+ }++ #[test]+ fn a_prompt_without_text_stores_no_prompt_field() {+ for message in [+ json!([{"type": "image_url", "image_url": {"url": "https://x/y.png"}}]),+ json!(" "),+ json!(null),+ json!(42),+ ] {+ let mut raw = pre_llm_call(message.clone());+ assert!(shape_hermes_lifecycle_body(&mut raw, HookEvent::UserPrompt));+ assert!(raw.get("prompt").is_none(), "{message}");+ assert!(raw.get("extra").is_none(), "{message}");+ }+ }++ #[test]+ fn first_turn_comes_only_from_a_true_flag() {+ let mut raw = pre_llm_call(json!("hi"));+ assert!(!hermes_is_first_turn(&raw));+ raw["extra"]["is_first_turn"] = json!(true);+ assert!(hermes_is_first_turn(&raw));+ raw["extra"]["is_first_turn"] = json!("true");+ assert!(!hermes_is_first_turn(&raw), "only a JSON boolean counts");+ assert!(!hermes_is_first_turn(&json!({"is_first_turn": true})));+ }++ #[test]+ fn finalize_closes_the_ending_session_never_the_new_one() {+ let mut raw = json!({+ "hook_event_name": "on_session_finalize",+ "session_id": "old-session",+ "cwd": "/srv/gateway",+ "extra": {+ "platform": "telegram",+ "reason": "new_session",+ "old_session_id": "old-session",+ "new_session_id": "new-session"+ }+ });+ assert!(shape_hermes_lifecycle_body(&mut raw, HookEvent::SessionEnd));+ assert_eq!(+ raw,+ json!({+ "hook_event_name": "on_session_finalize",+ "cwd": "/srv/gateway",+ "session_id": "old-session",+ "reason": "new_session"+ })+ );+ assert!(!raw.to_string().contains("new-session"));++ // A top-level id that disagrees still loses to the ending id.+ let mut raw = json!({+ "session_id": "new-session",+ "extra": {"old_session_id": "old-session", "new_session_id": "new-session"}+ });+ shape_hermes_lifecycle_body(&mut raw, HookEvent::SessionEnd);+ assert_eq!(raw["session_id"], "old-session");++ // The CLI's shutdown finalize carries only `session_id`.+ let mut raw = json!({+ "session_id": "cli-session",+ "extra": {"platform": "cli", "reason": "shutdown"}+ });+ shape_hermes_lifecycle_body(&mut raw, HookEvent::SessionEnd);+ assert_eq!(+ raw,+ json!({"session_id": "cli-session", "reason": "shutdown"})+ );+ }++ #[test]+ fn session_start_and_turn_end_keep_only_identity() {+ let mut start = json!({+ "hook_event_name": "on_session_start",+ "session_id": "s",+ "cwd": "/w",+ "profile": "default",+ "extra": {"model": "hermes-4", "platform": "cli", "telemetry_schema_version": 1}+ });+ assert!(shape_hermes_lifecycle_body(+ &mut start,+ HookEvent::SessionStart+ ));+ assert_eq!(+ start,+ json!({"hook_event_name": "on_session_start", "cwd": "/w", "session_id": "s", "model": "hermes-4"})+ );++ let mut turn_end = json!({+ "hook_event_name": "on_session_end",+ "session_id": "s",+ "cwd": "/w",+ "extra": {"completed": true, "turn_exit_reason": "done", "task_id": "t"}+ });+ assert!(shape_hermes_lifecycle_body(&mut turn_end, HookEvent::Stop));+ assert_eq!(+ turn_end,+ json!({"hook_event_name": "on_session_end", "cwd": "/w", "session_id": "s"})+ );+ }++ #[test]+ fn tool_events_are_left_as_sent() {+ let original = json!({+ "hook_event_name": "post_tool_call",+ "tool_name": "terminal",+ "tool_input": {"command": "ls"},+ "session_id": "s",+ "cwd": "/w",+ "extra": {"result": "ok", "status": "ok"}+ });+ for event in [HookEvent::PreToolUse, HookEvent::PostToolUse] {+ let mut raw = original.clone();+ assert!(!shape_hermes_lifecycle_body(&mut raw, event));+ assert_eq!(raw, original);+ }+ let mut not_object = json!(["x"]);+ assert!(!shape_hermes_lifecycle_body(+ &mut not_object,+ HookEvent::UserPrompt+ ));+ }+}diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 5e3d594a..bffdb8ff 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -27,6 +27,7 @@ mod brief_tiers;pub mod capture_policy;pub mod drop_list;mod grants;+pub mod hermes;pub mod idle_end;pub mod log;pub mod payload;@@ -57,6 +58,7 @@ pub use capture_policy::{glob_segment_matches, glob_walk, repository_admits_capture, tool_call_payload, valid_call_id,};pub use drop_list::IngestDropList;+pub use hermes::{hermes_is_first_turn, shape_hermes_lifecycle_body};pub use idle_end::{IDLE_END_BATCH, IDLE_END_INTERVAL_SECS, IdleEndTickInput, IdleEndTickOutcome, run_idle_end_tick,};