Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

install-hooks: support cursor + gemini-cli + open-code + openclaw

AkitaOnRails6744ce33f7ad
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index a4673fd9..787038f1 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -278,8 +278,18 @@ pub enum AgentChoice {
ClaudeCode,
/// OpenAI Codex CLI.
Codex,
- /// OpenCode (open-source coding agent).
+ /// Cursor IDE agent — JSON-config hooks in `~/.cursor/hooks.json`.
+ Cursor,
+ /// Google Gemini CLI — JSON-config hooks in `~/.gemini/settings.json`.
+ GeminiCli,
+ /// OpenCode (open-source coding agent) — TypeScript plugin hooks
+ /// under `~/.config/opencode/plugins/`. Print-only for now; the
+ /// plugin generator lands in a follow-up commit.
OpenCode,
+ /// OpenClaw personal AI gateway — **no lifecycle hooks**;
+ /// `install-hooks --apply --agent openclaw` prints an
+ /// explanation and exits without mutating anything.
+ Openclaw,
}
/// MCP client to render configuration for. Includes both the
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index d8d93ad2..5bcafb73 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -9,11 +9,14 @@
use std::path::{Path, PathBuf};
-use anyhow::{Context, Result, bail};
+use anyhow::{Context, Result};
use crate::cli::{AgentChoice, InstallHooksArgs};
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};
-use crate::commands::render_shared::{build_claude_code_payload, build_codex_payload};
+use crate::commands::render_shared::{
+ CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_codex_payload,
+ build_profile_payload,
+};
use crate::config::Config;
/// Run the `install-hooks` subcommand.
@@ -31,16 +34,42 @@ pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {
AgentChoice::Codex => {
apply_to_codex_settings(&hooks_dir, &args.server_url, auth, &args)
}
- AgentChoice::OpenCode => bail!(
- "--apply does not yet support --agent open-code (no stable upstream \
- hook schema documented). Run without --apply to print the snippet."
- ),
+ AgentChoice::Cursor => {
+ apply_to_cursor_settings(&hooks_dir, &args.server_url, auth, &args)
+ }
+ AgentChoice::GeminiCli => {
+ apply_to_gemini_settings(&hooks_dir, &args.server_url, auth, &args)
+ }
+ AgentChoice::OpenCode => {
+ apply_to_opencode_plugin(&hooks_dir, &args.server_url, auth, &args)
+ }
+ AgentChoice::Openclaw => {
+ println!(
+ "OpenClaw does not support lifecycle hooks (only HTTP webhooks for \
+ request ingress; no session/tool/prompt callbacks). ai-memory's \
+ hook surface relies on per-event POSTs, which OpenClaw cannot fire."
+ );
+ println!();
+ println!("Workarounds if you want some capture against OpenClaw:");
+ println!(" - Manually call `memory_handoff_begin` from your OpenClaw");
+ println!(" session before wrapping up (it's still in the MCP surface).");
+ println!(" - Or run a sidecar that observes OpenClaw's webhooks and");
+ println!(" forwards them to ai-memory.");
+ Ok(())
+ }
};
}
match args.agent {
AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url, auth),
AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url, auth),
+ AgentChoice::Cursor => render_agent("cursor", &hooks_dir, &args.server_url, auth),
+ AgentChoice::GeminiCli => render_agent("gemini-cli", &hooks_dir, &args.server_url, auth),
AgentChoice::OpenCode => render_agent("opencode", &hooks_dir, &args.server_url, auth),
+ AgentChoice::Openclaw => {
+ println!("OpenClaw does not expose lifecycle hooks — only HTTP webhooks.");
+ println!("ai-memory cannot wire automatic capture against OpenClaw today.");
+ Ok(())
+ }
}
}
@@ -184,6 +213,277 @@ fn apply_to_codex_settings(
Ok(())
}
+/// Mutate `~/.cursor/hooks.json` (creating it if absent) so Cursor's
+/// agent fires the ai-memory scripts on lifecycle events.
+///
+/// Cursor's hook schema (per <https://cursor.com/docs/agent/hooks>) is
+/// *flatter* than Claude Code's / Codex's:
+///
+/// { "version": 1,
+/// "hooks": {
+/// "sessionStart": [
+/// { "type": "command", "command": "...", "matcher": "" }
+/// ]
+/// }
+/// }
+///
+/// — no inner `hooks: [...]` array, camelCase event names, plus a
+/// required top-level `version: 1` key. We use `CURSOR_PROFILE`
+/// (HookShape::Flat) to produce the right payload, then merge into
+/// the existing file (preserving any non-overlapping events the
+/// user has wired up to other tools).
+fn apply_to_cursor_settings(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(p) => p.clone(),
+ None => dirs::home_dir()
+ .context("could not locate $HOME for ~/.cursor/hooks.json")?
+ .join(".cursor")
+ .join("hooks.json"),
+ };
+ let payload = build_profile_payload(&CURSOR_PROFILE, hooks_dir, server_url, auth_token);
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(|v| v.as_object())
+ .context("internal: payload builder didn't return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ // Cursor requires "version": 1 at the top level.
+ // Overwrite unconditionally — the schema is versioned
+ // so future Cursor releases can bump this; we'll bump
+ // here too when that happens.
+ root.insert("version".into(), serde_json::json!(1));
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in hooks.json but not an object")?;
+ for (event, value) in &our_hooks {
+ hooks.insert(event.clone(), value.clone());
+ }
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ Ok(())
+}
+
+/// Mutate `~/.gemini/settings.json` so Gemini CLI fires the ai-memory
+/// scripts on its (Gemini-specific) lifecycle events.
+///
+/// Gemini's schema (per <https://geminicli.com/docs/hooks/reference>)
+/// is the same nested shape as Claude Code's (`matcher` +
+/// `hooks: [{type, command}]`), but the event vocabulary differs:
+///
+/// - `BeforeTool` / `AfterTool` (ai-memory: `pre-tool-use` / `post-tool-use`)
+/// - `PreCompress` (ai-memory: `pre-compact`)
+/// - `SessionStart` / `SessionEnd` line up with Claude Code's
+/// - No `UserPromptSubmit` / `Stop` equivalents — skipped
+///
+/// Like Claude Code, Gemini doesn't honour an `env` field at the
+/// inner-hook level, so the env vars get inlined into the command
+/// string by the shared payload builder.
+fn apply_to_gemini_settings(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(p) => p.clone(),
+ None => dirs::home_dir()
+ .context("could not locate $HOME for ~/.gemini/settings.json")?
+ .join(".gemini")
+ .join("settings.json"),
+ };
+ let payload = build_profile_payload(&GEMINI_PROFILE, hooks_dir, server_url, auth_token);
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(|v| v.as_object())
+ .context("internal: payload builder didn't return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ // Gemini's settings.json mixes MCP servers, hooks, and
+ // other config under one document. Get-or-create the
+ // `hooks` table; overlay our events; preserve siblings.
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in settings.json but not an object")?;
+ for (event, value) in &our_hooks {
+ hooks.insert(event.clone(), value.clone());
+ }
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ Ok(())
+}
+
+/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.
+///
+/// Unlike Claude Code / Codex / Cursor / Gemini, OpenCode's lifecycle
+/// hooks aren't JSON config — they're TypeScript modules under
+/// `~/.config/opencode/plugins/` (per
+/// <https://opencode.ai/docs/plugins/>). A plugin exports an
+/// async function returning a hooks object; the keys are
+/// dot-separated event names (`session.created`, `tool.execute.before`,
+/// etc.) and the values are async handlers.
+///
+/// Event mapping (OpenCode → ai-memory):
+/// session.created → session-start.sh
+/// session.idle → stop.sh
+/// session.compacted → pre-compact.sh
+/// tool.execute.before → pre-tool-use.sh
+/// tool.execute.after → post-tool-use.sh
+///
+/// OpenCode doesn't expose a `prompt-submit` equivalent or a
+/// `session.ended` event (idle is the closest). We forward what
+/// we can.
+fn apply_to_opencode_plugin(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(p) => p.clone(),
+ None => dirs::home_dir()
+ .context("could not locate $HOME for ~/.config/opencode/plugins")?
+ .join(".config")
+ .join("opencode")
+ .join("plugins")
+ .join("ai-memory.ts"),
+ };
+ let script = |name: &str| {
+ hooks_dir
+ .join(name)
+ .to_string_lossy()
+ .into_owned()
+ };
+ let token_line = auth_token
+ .map(|t| format!("const TOKEN = {};\n", ts_string_literal(t)))
+ .unwrap_or_else(|| "const TOKEN = null;\n".to_string());
+ let body = format!(
+ r#"// Auto-generated by `ai-memory install-hooks --agent open-code --apply`.
+// Edit by re-running the command, not by hand — install-hooks
+// will overwrite this file (with a `.bak-<ts>` backup) on each
+// re-run.
+
+import type {{ Plugin }} from "@opencode-ai/plugin";
+
+const SERVER = {server_literal};
+{token_line}
+async function fire(
+ $: any,
+ script: string,
+ event: string,
+ payload: unknown,
+): Promise<void> {{
+ // The hook scripts read JSON from stdin + AI_MEMORY_HOOK_URL/
+ // AI_MEMORY_AUTH_TOKEN from env. Inline the env into the shell
+ // command via POSIX `VAR=val cmd` syntax so we don't depend on
+ // the runtime's env-passing semantics.
+ const body = JSON.stringify({{
+ hook_event_name: event,
+ agent: "open-code",
+ payload,
+ }});
+ try {{
+ const authPrefix = TOKEN ? `AI_MEMORY_AUTH_TOKEN=${{TOKEN}} ` : "";
+ await $`echo ${{body}} | env AI_MEMORY_HOOK_URL=${{SERVER}} ${{authPrefix}}${{script}}`
+ .nothrow()
+ .quiet();
+ }} catch (_e) {{
+ // Fire-and-forget. Hooks must never block the agent.
+ }}
+}}
+
+export const AiMemoryHooks: Plugin = async ({{ $ }}) => {{
+ return {{
+ "session.created": async (input) => fire($, {session_start}, "session-start", input),
+ "session.idle": async (input) => fire($, {stop}, "stop", input),
+ "session.compacted": async (input) => fire($, {pre_compact}, "pre-compact", input),
+ "tool.execute.before": async (input) => fire($, {pre_tool}, "pre-tool-use", input),
+ "tool.execute.after": async (input) => fire($, {post_tool}, "post-tool-use", input),
+ }};
+}};
+"#,
+ server_literal = ts_string_literal(server_url),
+ token_line = token_line,
+ session_start = ts_string_literal(&script("session-start.sh")),
+ stop = ts_string_literal(&script("stop.sh")),
+ pre_compact = ts_string_literal(&script("pre-compact.sh")),
+ pre_tool = ts_string_literal(&script("pre-tool-use.sh")),
+ post_tool = ts_string_literal(&script("post-tool-use.sh")),
+ );
+
+ let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new plugin file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ if !matches!(outcome, ApplyOutcome::NoOp) {
+ println!();
+ println!("OpenCode auto-loads plugins from ~/.config/opencode/plugins/ on next start.");
+ println!("If you're already inside an `opencode` session, restart it for the");
+ println!("new plugin to take effect.");
+ }
+ Ok(())
+}
+
+/// Emit a TypeScript string literal containing `s`. Escapes
+/// backslashes, double quotes, and newlines. Sufficient for the
+/// URL + auth-token + path strings we embed; the generated file is
+/// not user-edited.
+fn ts_string_literal(s: &str) -> String {
+ let mut out = String::with_capacity(s.len() + 2);
+ out.push('"');
+ for ch in s.chars() {
+ match ch {
+ '\\' => out.push_str("\\\\"),
+ '"' => out.push_str("\\\""),
+ '\n' => out.push_str("\\n"),
+ '\r' => out.push_str("\\r"),
+ '\t' => out.push_str("\\t"),
+ c => out.push(c),
+ }
+ }
+ out.push('"');
+ out
+}
+
fn render_agent(
label: &str,
hooks_dir: &Path,
@@ -218,7 +518,13 @@ fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<Path
let sub = match agent {
AgentChoice::ClaudeCode => "claude-code",
AgentChoice::Codex => "codex",
+ AgentChoice::Cursor => "cursor",
+ AgentChoice::GeminiCli => "gemini-cli",
AgentChoice::OpenCode => "opencode",
+ // OpenClaw has no hooks → no script dir needed. Return a
+ // sentinel that's never touched; the caller's apply path
+ // short-circuits before any filesystem use.
+ AgentChoice::Openclaw => return Ok(PathBuf::from("/dev/null")),
};
if let Some(p) = explicit {
let path = p.join(sub);
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index ce33203b..15f87447 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -77,11 +77,42 @@ pub(crate) fn build_claude_code_payload(
build_hook_payload(&CLAUDE_CODE_EVENTS, emit_root, server_url, auth_token)
}
+/// Different agents nest hook entries differently. Two shapes
+/// cover everyone we support:
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum HookShape {
+ /// Claude Code / Codex / Gemini CLI:
+ /// `"E": [ { "matcher":"", "hooks":[ {"type":"command",
+ /// "command":"..."} ] } ]`
+ /// Gemini CLI tolerates (but doesn't require) a sibling
+ /// `sequential` key at the outer level — we don't set it.
+ Nested,
+ /// Cursor: `"e": [ { "type":"command", "command":"...",
+ /// "matcher":"" } ]` (no inner `hooks` array). Cursor's
+ /// `hooks.json` also requires a sibling `version: 1` key at
+ /// the top level — handled by the caller's apply path.
+ Flat,
+}
+
+/// One hook profile = (event vocabulary, JSON shape). Each agent
+/// gets its own constant so the install path is purely data-
+/// driven: pick the profile, build the payload, write the file.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct HookProfile {
+ /// `(EventName, script_basename)` tuples in the order the
+ /// agent surfaces them. Event names are case-sensitive and
+ /// agent-specific — Claude Code uses `SessionStart` while
+ /// Cursor uses `sessionStart`. The script basename resolves
+ /// against `hooks/<agent-dir>/`.
+ pub events: &'static [(&'static str, &'static str)],
+ /// JSON shape the file uses.
+ pub shape: HookShape,
+}
+
/// Codex's hook-event vocabulary (per the openai/codex source —
/// see `codex-rs/config/src/hooks_tests.rs`). Same shape as Claude
-/// Code's seven events, EXCEPT: Codex has no `SessionEnd` (it uses
-/// `Stop` for both turn-end and session-end signalling). The other
-/// six events line up 1:1.
+/// Code's six common events, EXCEPT: Codex has no `SessionEnd` (it
+/// uses `Stop` for both turn-end and session-end signalling).
pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
("SessionStart", "session-start.sh"),
("UserPromptSubmit", "user-prompt-submit.sh"),
@@ -91,24 +122,100 @@ pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
("Stop", "stop.sh"),
];
-/// Build a Codex-flavoured hook payload. Same JSON shape as Claude
-/// Code's (verified against `openai/codex/codex-rs/config/src/hooks_tests.rs`)
-/// minus `SessionEnd`, which Codex doesn't have.
+/// Cursor's hook-event vocabulary (per
+/// <https://cursor.com/docs/agent/hooks>). camelCase event names
+/// and a FLAT JSON shape (no inner `hooks: [...]` wrapper).
+/// `beforeSubmitPrompt` maps to ai-memory's `user-prompt-submit`
+/// concept. Cursor has no `userPromptSubmit` event.
+pub(crate) const CURSOR_EVENTS: [(&str, &str); 7] = [
+ ("sessionStart", "session-start.sh"),
+ ("sessionEnd", "session-end.sh"),
+ ("beforeSubmitPrompt", "user-prompt-submit.sh"),
+ ("preToolUse", "pre-tool-use.sh"),
+ ("postToolUse", "post-tool-use.sh"),
+ ("preCompact", "pre-compact.sh"),
+ ("stop", "stop.sh"),
+];
+
+/// Gemini CLI's hook-event vocabulary (per
+/// <https://geminicli.com/docs/hooks/reference>). Event names use
+/// PascalCase. The vocab DIFFERS from Claude Code's:
+/// - `BeforeTool` / `AfterTool` instead of `PreToolUse` / `PostToolUse`
+/// - `PreCompress` instead of `PreCompact`
+/// - No `UserPromptSubmit` equivalent (skipped)
+/// - No `Stop` event (SessionEnd covers it)
+pub(crate) const GEMINI_EVENTS: [(&str, &str); 5] = [
+ ("SessionStart", "session-start.sh"),
+ ("SessionEnd", "session-end.sh"),
+ ("BeforeTool", "pre-tool-use.sh"),
+ ("AfterTool", "post-tool-use.sh"),
+ ("PreCompress", "pre-compact.sh"),
+];
+
+/// Per-agent profile constants. Add a new agent by adding one of
+/// these + a script-dir name + a config-file path resolver — the
+/// payload-build path picks up the rest from `shape`.
+// Defined for completeness alongside the other profiles; the Claude
+// Code apply path still goes through `build_claude_code_payload`
+// (kept stable for the existing setup-agent emitter). Marked
+// `allow(dead_code)` so cargo doesn't complain — anyone adding a
+// new caller can switch to `build_profile_payload(&CLAUDE_CODE_PROFILE, …)`.
+#[allow(dead_code)]
+pub(crate) const CLAUDE_CODE_PROFILE: HookProfile = HookProfile {
+ events: &CLAUDE_CODE_EVENTS,
+ shape: HookShape::Nested,
+};
+pub(crate) const CODEX_PROFILE: HookProfile = HookProfile {
+ events: &CODEX_EVENTS,
+ shape: HookShape::Nested,
+};
+pub(crate) const CURSOR_PROFILE: HookProfile = HookProfile {
+ events: &CURSOR_EVENTS,
+ shape: HookShape::Flat,
+};
+pub(crate) const GEMINI_PROFILE: HookProfile = HookProfile {
+ events: &GEMINI_EVENTS,
+ shape: HookShape::Nested,
+};
+
+/// Build a Codex-flavoured hook payload. Thin alias for back-compat;
+/// new code should call `build_profile_payload(&CODEX_PROFILE, …)`.
pub(crate) fn build_codex_payload(
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
) -> serde_json::Value {
- build_hook_payload(&CODEX_EVENTS, emit_root, server_url, auth_token)
+ build_profile_payload(&CODEX_PROFILE, emit_root, server_url, auth_token)
+}
+
+/// Build a hook payload for `profile`. The output is always
+/// `{ "hooks": { "<EventName>": <profile-specific-array> } }`; the
+/// caller is responsible for any sibling top-level keys (e.g.
+/// Cursor's `"version": 1`).
+pub(crate) fn build_profile_payload(
+ profile: &HookProfile,
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+) -> serde_json::Value {
+ build_hook_payload_inner(profile.events, profile.shape, emit_root, server_url, auth_token)
}
-/// Shared helper. Given a list of `(event_name, script_basename)`,
-/// emit `{ "hooks": { "EventName": [matcher+inner-hooks] } }`.
fn build_hook_payload(
events: &[(&str, &str)],
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
+) -> serde_json::Value {
+ build_hook_payload_inner(events, HookShape::Nested, emit_root, server_url, auth_token)
+}
+
+fn build_hook_payload_inner(
+ events: &[(&str, &str)],
+ shape: HookShape,
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
) -> serde_json::Value {
let mut hooks_block = serde_json::Map::new();
for (event, script) in events {
@@ -145,16 +252,21 @@ fn build_hook_payload(
// Empty matcher = fire on every event of this kind. Right
// for ai-memory's capture hooks (every prompt, every tool
// call, every session boundary).
- hooks_block.insert(
- (*event).to_string(),
- json!([{
+ let entry = match shape {
+ HookShape::Nested => json!([{
"matcher": "",
"hooks": [{
"type": "command",
"command": command,
}],
}]),
- );
+ HookShape::Flat => json!([{
+ "type": "command",
+ "command": command,
+ "matcher": "",
+ }]),
+ };
+ hooks_block.insert((*event).to_string(), entry);
}
json!({ "hooks": hooks_block })
}
@@ -227,6 +339,90 @@ mod tests {
/// outer level — which made Claude Code refuse to load
/// settings.json with "hooks: Expected array, but received
/// undefined" on every event.
+ #[test]
+ fn cursor_payload_uses_flat_shape() {
+ // Flat shape: no inner `hooks: [...]` array; each event
+ // maps to an array of {type, command, matcher} entries.
+ let root = PathBuf::from("/host/hooks/cursor");
+ let v =
+ build_profile_payload(&CURSOR_PROFILE, &root, "http://localhost:49374", Some("tok"));
+ let session_start = v
+ .pointer("/hooks/sessionStart/0")
+ .and_then(|e| e.as_object())
+ .expect("missing /hooks/sessionStart/0");
+ assert_eq!(
+ session_start.get("type").and_then(|t| t.as_str()),
+ Some("command"),
+ "Cursor flat entries put `type` at the outer level"
+ );
+ assert!(
+ session_start.contains_key("command"),
+ "Cursor flat entries put `command` at the outer level"
+ );
+ // No nested hooks array.
+ assert!(
+ !session_start.contains_key("hooks"),
+ "Cursor must NOT use the nested hooks shape — found one: {session_start:?}"
+ );
+ // Auth token still inlined into command.
+ let cmd = session_start
+ .get("command")
+ .and_then(|c| c.as_str())
+ .unwrap();
+ assert!(cmd.contains("AI_MEMORY_AUTH_TOKEN=tok"));
+ // Events are camelCase, not PascalCase.
+ let events: Vec<&str> = v
+ .pointer("/hooks")
+ .and_then(|h| h.as_object())
+ .map(|o| o.keys().map(String::as_str).collect())
+ .unwrap_or_default();
+ assert!(events.contains(&"sessionStart"));
+ assert!(events.contains(&"preToolUse"));
+ assert!(
+ !events.contains(&"SessionStart"),
+ "Cursor uses camelCase, not PascalCase"
+ );
+ }
+
+ #[test]
+ fn gemini_payload_uses_nested_shape_with_gemini_event_names() {
+ // Same nested shape as Claude Code, but DIFFERENT event
+ // names (BeforeTool / AfterTool / PreCompress; no
+ // UserPromptSubmit, no Stop).
+ let root = PathBuf::from("/host/hooks/gemini-cli");
+ let v =
+ build_profile_payload(&GEMINI_PROFILE, &root, "http://localhost:49374", Some("tok"));
+ let session_start = v
+ .pointer("/hooks/SessionStart/0")
+ .and_then(|e| e.as_object())
+ .expect("missing /hooks/SessionStart/0");
+ // Outer level has matcher + hooks (nested shape).
+ assert!(session_start.contains_key("matcher"));
+ let inner = session_start
+ .get("hooks")
+ .and_then(|h| h.as_array())
+ .unwrap();
+ assert_eq!(inner.len(), 1);
+ let entry = inner[0].as_object().unwrap();
+ assert_eq!(entry.get("type").and_then(|t| t.as_str()), Some("command"));
+ // Event vocab: Gemini-specific names present, Claude Code-
+ // only names absent.
+ let events: Vec<&str> = v
+ .pointer("/hooks")
+ .and_then(|h| h.as_object())
+ .map(|o| o.keys().map(String::as_str).collect())
+ .unwrap_or_default();
+ for expected in ["SessionStart", "SessionEnd", "BeforeTool", "AfterTool", "PreCompress"] {
+ assert!(events.contains(&expected), "missing Gemini event {expected}");
+ }
+ for unexpected in ["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop", "PreCompact"] {
+ assert!(
+ !events.contains(&unexpected),
+ "Gemini should NOT have CC-only event {unexpected}; got {events:?}"
+ );
+ }
+ }
+
#[test]
fn claude_code_payload_uses_matcher_plus_inner_hooks_shape() {
let root = PathBuf::from("/host/hooks/claude-code");
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 45a50eaa..5140db0c 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -48,7 +48,17 @@ pub fn run(_config: &Config, args: SetupAgentArgs) -> Result<()> {
let agent_sub = match args.agent {
AgentChoice::ClaudeCode => "claude-code",
AgentChoice::Codex => "codex",
+ AgentChoice::Cursor => "cursor",
+ AgentChoice::GeminiCli => "gemini-cli",
AgentChoice::OpenCode => "opencode",
+ AgentChoice::Openclaw => {
+ anyhow::bail!(
+ "OpenClaw has no lifecycle hooks (only HTTP webhooks); \
+ `setup-agent --agent openclaw` is not applicable. Use \
+ `install-mcp --client openclaw --apply` for the MCP config \
+ only."
+ );
+ }
};
let source = resolve_source(args.source.as_deref(), agent_sub)?;
@@ -101,7 +111,16 @@ pub fn run(_config: &Config, args: SetupAgentArgs) -> Result<()> {
match args.agent {
AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,
- AgentChoice::Codex | AgentChoice::OpenCode => emit_other(&emit_root, agent_sub, &args),
+ AgentChoice::Codex | AgentChoice::Cursor | AgentChoice::GeminiCli | AgentChoice::OpenCode => {
+ emit_other(&emit_root, agent_sub, &args);
+ }
+ AgentChoice::Openclaw => {
+ // Unreachable — the early bail at the top of run()
+ // catches openclaw before we get here. Defensive
+ // arm so the match stays exhaustive if the bail is
+ // ever removed.
+ unreachable!("openclaw handled by the early bail above");
+ }
}
Ok(())
}
diff --git a/hooks/cursor/post-tool-use.sh b/hooks/cursor/post-tool-use.sh
new file mode 100755
index 00000000..410f5b77
--- /dev/null
+++ b/hooks/cursor/post-tool-use.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor post-tool-use hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=post-tool-use&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/cursor/pre-compact.sh b/hooks/cursor/pre-compact.sh
new file mode 100755
index 00000000..6e626f14
--- /dev/null
+++ b/hooks/cursor/pre-compact.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor pre-compact hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=pre-compact&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/cursor/pre-tool-use.sh b/hooks/cursor/pre-tool-use.sh
new file mode 100755
index 00000000..c9a4891c
--- /dev/null
+++ b/hooks/cursor/pre-tool-use.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor pre-tool-use hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=pre-tool-use&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/cursor/session-end.sh b/hooks/cursor/session-end.sh
new file mode 100755
index 00000000..24876086
--- /dev/null
+++ b/hooks/cursor/session-end.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor session-end hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=session-end&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/cursor/session-start.sh b/hooks/cursor/session-start.sh
new file mode 100755
index 00000000..48eb0dab
--- /dev/null
+++ b/hooks/cursor/session-start.sh
@@ -0,0 +1,39 @@
+#!/bin/sh
+# cursor SessionStart hook.
+#
+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).
+# 2. Synchronously fetches any pending cross-agent handoff and prints
+# it to stdout — agent CLIs prepend session-start hook stdout to
+# the next session, so the resuming agent sees prior context with
+# no human in the loop.
+#
+# Both calls carry an Authorization: Bearer header when
+# AI_MEMORY_AUTH_TOKEN is set in this hook's environment.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+
+get_handoff() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 1.0 "$1" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"
+ else
+ curl -s --max-time 1.0 "$1"
+ fi
+}
+
+echo "$PAYLOAD" | post_hook "$SERVER/hook?event=session-start&agent=cursor" >/dev/null 2>&1 || true
+get_handoff "$SERVER/handoff?agent=cursor" 2>/dev/null || true
+exit 0
diff --git a/hooks/cursor/stop.sh b/hooks/cursor/stop.sh
new file mode 100755
index 00000000..57179739
--- /dev/null
+++ b/hooks/cursor/stop.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor stop hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=stop&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/cursor/user-prompt-submit.sh b/hooks/cursor/user-prompt-submit.sh
new file mode 100755
index 00000000..20441702
--- /dev/null
+++ b/hooks/cursor/user-prompt-submit.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# cursor user-prompt hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=user-prompt&agent=cursor" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/post-tool-use.sh b/hooks/gemini-cli/post-tool-use.sh
new file mode 100755
index 00000000..0bbffcde
--- /dev/null
+++ b/hooks/gemini-cli/post-tool-use.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli post-tool-use hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=post-tool-use&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/pre-compact.sh b/hooks/gemini-cli/pre-compact.sh
new file mode 100755
index 00000000..13c50878
--- /dev/null
+++ b/hooks/gemini-cli/pre-compact.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli pre-compact hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=pre-compact&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/pre-tool-use.sh b/hooks/gemini-cli/pre-tool-use.sh
new file mode 100755
index 00000000..71e0fa3c
--- /dev/null
+++ b/hooks/gemini-cli/pre-tool-use.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli pre-tool-use hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=pre-tool-use&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/session-end.sh b/hooks/gemini-cli/session-end.sh
new file mode 100755
index 00000000..574ab5cc
--- /dev/null
+++ b/hooks/gemini-cli/session-end.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli session-end hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=session-end&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/session-start.sh b/hooks/gemini-cli/session-start.sh
new file mode 100755
index 00000000..2384c0e7
--- /dev/null
+++ b/hooks/gemini-cli/session-start.sh
@@ -0,0 +1,39 @@
+#!/bin/sh
+# gemini-cli SessionStart hook.
+#
+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).
+# 2. Synchronously fetches any pending cross-agent handoff and prints
+# it to stdout — agent CLIs prepend session-start hook stdout to
+# the next session, so the resuming agent sees prior context with
+# no human in the loop.
+#
+# Both calls carry an Authorization: Bearer header when
+# AI_MEMORY_AUTH_TOKEN is set in this hook's environment.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+
+get_handoff() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 1.0 "$1" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"
+ else
+ curl -s --max-time 1.0 "$1"
+ fi
+}
+
+echo "$PAYLOAD" | post_hook "$SERVER/hook?event=session-start&agent=gemini-cli" >/dev/null 2>&1 || true
+get_handoff "$SERVER/handoff?agent=gemini-cli" 2>/dev/null || true
+exit 0
diff --git a/hooks/gemini-cli/stop.sh b/hooks/gemini-cli/stop.sh
new file mode 100755
index 00000000..1a7e1e0c
--- /dev/null
+++ b/hooks/gemini-cli/stop.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli stop hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=stop&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/gemini-cli/user-prompt-submit.sh b/hooks/gemini-cli/user-prompt-submit.sh
new file mode 100755
index 00000000..2a292e72
--- /dev/null
+++ b/hooks/gemini-cli/user-prompt-submit.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# gemini-cli user-prompt hook.
+# Forwards the event JSON to the ai-memory server. Adds an
+# Authorization: Bearer header when AI_MEMORY_AUTH_TOKEN is set in
+# this hook's environment (set it via install-hooks --auth-token).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+post_hook() {
+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
+ --data-binary @-
+ else
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ --data-binary @-
+ fi
+}
+post_hook "$SERVER/hook?event=user-prompt&agent=gemini-cli" >/dev/null 2>&1 || true
+exit 0