Skip to content

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

Rust

feat: add OpenClaw lifecycle integration

AkitaOnRailsa8d27e5fe66d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0bb37b42..bd62ee70 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Clarified Gemini CLI support docs: MCP registration, lifecycle hooks,
SessionStart handoff injection, and SessionEnd capture are now called out
consistently across README and install guides.
+- Added OpenClaw lifecycle support via a generated native plugin package and
+ updated Cursor / Claude Desktop / OpenClaw support docs against current
+ upstream MCP and hook documentation.
- Docker images now bundle both POSIX and PowerShell hook scripts.
### Fixed
diff --git a/README.md b/README.md
index 277898cc..d78108c2 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,7 @@
| Gemini CLI | Supported | MCP config + lifecycle hooks. |
| Oh My Pi / OMP | Supported | `pi` / `omp` aliases for MCP config + TypeScript extension. |
| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |
-| OpenClaw | MCP-only | OpenClaw has MCP/webhook ingress but no lifecycle hook surface. |
+| OpenClaw | Supported | MCP config + native plugin lifecycle hooks. |
| LLM providers | Supported | Anthropic, OpenAI, Gemini, and OpenAI-compatible endpoints. |
| Embedding providers | Supported | OpenAI and Voyage. |
@@ -750,7 +750,7 @@ data-flow diagram + crate breakdown + cross-cutting invariants.
|---|---|
| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. |
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, native source builds, and current hook/MCP harness caveats. |
-| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP config snippets (Cursor, Claude Desktop, Gemini CLI, OpenClaw, OMP). |
+| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes (Cursor, Claude Desktop, Gemini CLI, OpenClaw, OMP). |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, TLS via cloudflared. |
| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset.** Safety matrix for the state-touching commands, per-project disk layout (how isolation actually works), and operator workflows for "fresh start", "snapshot before risky op", "drop one project". |
| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 81d4fcd2..d239737a 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -329,7 +329,7 @@ pub struct RestoreArgs {
}
/// Agent CLI to install hooks/extensions for. For MCP-only clients
-/// (Claude Desktop, OpenClaw), use `install-mcp --client <name>` instead.
+/// (Claude Desktop), use `install-mcp --client <name>` instead.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AgentChoice {
/// Anthropic Claude Code.
@@ -356,9 +356,8 @@ pub enum AgentChoice {
/// file directly; restart `omp` for it to load.
#[value(alias = "pi", alias = "oh-my-pi")]
Omp,
- /// OpenClaw personal AI gateway — **no lifecycle hooks**;
- /// `install-hooks --apply --agent openclaw` prints an
- /// explanation and exits without mutating anything.
+ /// OpenClaw personal AI gateway — native plugin package with
+ /// session/tool/compaction hooks.
Openclaw,
}
@@ -497,7 +496,7 @@ pub struct InstallHooksArgs {
pub agent: AgentChoice,
/// Filesystem root that contains the vendored hook scripts (defaults
/// to the repo's `hooks/` if known, else `/usr/local/share/ai-memory/hooks`).
- /// Ignored for OpenCode, whose integration is a generated TypeScript plugin.
+ /// Ignored for generated TypeScript integrations (OpenCode, OMP, OpenClaw).
#[arg(long)]
pub hooks_dir: Option<PathBuf>,
/// Server URL the hooks will POST to.
@@ -517,6 +516,7 @@ pub struct InstallHooksArgs {
#[arg(long)]
pub apply: bool,
/// Override the settings/plugin/extension file path for the selected agent.
+ /// For OpenClaw, this is the generated plugin package directory.
#[arg(long)]
pub config_file: Option<PathBuf>,
}
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index b3fba286..4173e86a 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -15,7 +15,9 @@
//! and produces no backup.
use std::fs;
+use std::io::ErrorKind;
use std::path::{Path, PathBuf};
+use std::process::Command;
use anyhow::{Context, Result};
@@ -57,20 +59,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_gemini_settings(&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(())
- }
+ AgentChoice::Openclaw => apply_to_openclaw_plugin(&args.server_url, auth, &args),
};
}
match args.agent {
@@ -92,11 +81,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
render_agent("gemini-cli", &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(())
- }
+ AgentChoice::Openclaw => render_openclaw_plugin(&args.server_url, auth),
}
}
@@ -901,6 +886,352 @@ export default function AiMemoryExtension(api: any): void {{
)
}
+const OPENCLAW_PLUGIN_ID: &str = "ai-memory";
+
+fn apply_to_openclaw_plugin(
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let plugin_dir = resolve_openclaw_plugin_dir(args)?;
+ let outcomes = write_openclaw_plugin_package(&plugin_dir, server_url, auth_token)?;
+ for (path, outcome) in &outcomes {
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ }
+
+ match install_openclaw_plugin(&plugin_dir)? {
+ OpenClawInstallStatus::Installed => {
+ println!();
+ println!("OpenClaw plugin installed from {}.", plugin_dir.display());
+ println!(
+ "If your OpenClaw gateway did not auto-restart, run `openclaw gateway restart`."
+ );
+ println!("Verify with `openclaw plugins inspect ai-memory --runtime --json`.");
+ }
+ OpenClawInstallStatus::CliMissing => {
+ println!();
+ println!("OpenClaw CLI not found on PATH; plugin package was written only.");
+ println!("Install it with:");
+ println!(
+ " openclaw plugins install --link {} --force",
+ plugin_dir.display()
+ );
+ println!(" openclaw gateway restart");
+ println!(" openclaw plugins inspect ai-memory --runtime --json");
+ }
+ }
+ Ok(())
+}
+
+fn render_openclaw_plugin(server_url: &str, auth_token: Option<&str>) -> Result<()> {
+ println!("# OpenClaw native plugin package");
+ println!("# Re-run with `--apply` to write the package and call:");
+ println!("# openclaw plugins install --link <package-dir> --force");
+ println!("# OpenClaw loads plugin code at gateway startup; restart if your");
+ println!("# managed gateway does not auto-restart after install.");
+ println!();
+ println!("## package.json");
+ println!("{}", openclaw_package_json());
+ println!("## openclaw.plugin.json");
+ println!("{}", openclaw_manifest_json());
+ println!("## index.ts");
+ println!("{}", build_openclaw_plugin(server_url, auth_token));
+ Ok(())
+}
+
+fn resolve_openclaw_plugin_dir(args: &InstallHooksArgs) -> Result<PathBuf> {
+ if let Some(path) = &args.config_file {
+ return Ok(path.clone());
+ }
+ Ok(dirs::data_local_dir()
+ .context("could not locate the user data-local directory")?
+ .join("ai-memory")
+ .join("openclaw-plugin"))
+}
+
+fn write_openclaw_plugin_package(
+ plugin_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+) -> Result<Vec<(PathBuf, ApplyOutcome)>> {
+ let files = [
+ ("package.json", openclaw_package_json()),
+ ("openclaw.plugin.json", openclaw_manifest_json()),
+ ("index.ts", build_openclaw_plugin(server_url, auth_token)),
+ ];
+ let mut outcomes = Vec::with_capacity(files.len());
+ for (name, body) in files {
+ let path = plugin_dir.join(name);
+ let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;
+ outcomes.push((path, outcome));
+ }
+ Ok(outcomes)
+}
+
+enum OpenClawInstallStatus {
+ Installed,
+ CliMissing,
+}
+
+fn install_openclaw_plugin(plugin_dir: &Path) -> Result<OpenClawInstallStatus> {
+ let output = match Command::new("openclaw")
+ .args(["plugins", "install", "--link"])
+ .arg(plugin_dir)
+ .arg("--force")
+ .output()
+ {
+ Ok(output) => output,
+ Err(e) if e.kind() == ErrorKind::NotFound => return Ok(OpenClawInstallStatus::CliMissing),
+ Err(e) => return Err(e).context("running openclaw plugins install"),
+ };
+ if !output.status.success() {
+ anyhow::bail!(
+ "openclaw plugins install failed with status {}\nstdout:\n{}\nstderr:\n{}",
+ output.status,
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ let enable = Command::new("openclaw")
+ .args(["plugins", "enable", OPENCLAW_PLUGIN_ID])
+ .output()
+ .context("running openclaw plugins enable")?;
+ if !enable.status.success() {
+ eprintln!(
+ "# warning: `openclaw plugins enable ai-memory` exited with {}\n# stdout:\n{}\n# stderr:\n{}",
+ enable.status,
+ String::from_utf8_lossy(&enable.stdout),
+ String::from_utf8_lossy(&enable.stderr)
+ );
+ }
+
+ Ok(OpenClawInstallStatus::Installed)
+}
+
+fn openclaw_package_json() -> String {
+ serde_json::to_string_pretty(&serde_json::json!({
+ "name": "@ai-memory/openclaw-plugin",
+ "version": env!("CARGO_PKG_VERSION"),
+ "private": true,
+ "type": "module",
+ "openclaw": {
+ "extensions": ["./index.ts"]
+ }
+ }))
+ .expect("OpenClaw package metadata serializes")
+ + "\n"
+}
+
+fn openclaw_manifest_json() -> String {
+ serde_json::to_string_pretty(&serde_json::json!({
+ "id": OPENCLAW_PLUGIN_ID,
+ "name": "ai-memory",
+ "description": "Capture OpenClaw session lifecycle, tool use, compaction, and handoffs into ai-memory.",
+ "activation": {
+ "onCapabilities": ["hook"]
+ },
+ "configSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {}
+ }
+ }))
+ .expect("OpenClaw manifest serializes")
+ + "\n"
+}
+
+fn build_openclaw_plugin(server_url: &str, auth_token: Option<&str>) -> String {
+ let token_line = auth_token
+ .map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))
+ .unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());
+ format!(
+ r#"// Auto-generated by `ai-memory install-hooks --agent openclaw --apply`.
+// Edit by re-running the command, not by hand. install-hooks owns
+// this local OpenClaw plugin package.
+
+import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";
+
+const SERVER = {server_literal}.replace(/\/+$/, "");
+const AGENT = "openclaw";
+{token_line}
+
+function timeoutSignal(ms: number): AbortSignal | undefined {{
+ if (typeof AbortSignal === "undefined") return undefined;
+ const factory = (AbortSignal as unknown as {{ timeout?: (ms: number) => AbortSignal }}).timeout;
+ return factory ? factory(ms) : undefined;
+}}
+
+function authHeaders(): Record<string, string> {{
+ return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
+}}
+
+function textFrom(value: unknown): string {{
+ if (value === null || value === undefined) return "";
+ if (typeof value === "string") return value;
+ if (Array.isArray(value)) return value.map(textFrom).filter(Boolean).join("\n\n").trim();
+ const obj = value as any;
+ if (typeof obj.text === "string") return obj.text;
+ if (typeof obj.content === "string") return obj.content;
+ if (typeof obj.prompt === "string") return obj.prompt;
+ try {{
+ return JSON.stringify(value);
+ }} catch (_e) {{
+ return String(value);
+ }}
+}}
+
+function sessionID(event: any, ctx: any): string | undefined {{
+ const value = ctx?.sessionId ?? ctx?.sessionID ?? ctx?.sessionKey ?? event?.sessionId ?? event?.sessionID ?? event?.sessionKey;
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}}
+
+function cwd(event: any, ctx: any): string | undefined {{
+ const value = ctx?.workspaceDir ?? ctx?.cwd ?? event?.cwd ?? event?.workspaceDir;
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}}
+
+function payload(event: any, ctx: any, extra: Record<string, unknown> = {{}}): Record<string, unknown> {{
+ return {{
+ sessionID: sessionID(event, ctx),
+ cwd: cwd(event, ctx),
+ agentID: ctx?.agentId,
+ runID: ctx?.runId ?? event?.runId,
+ jobID: ctx?.jobId,
+ ...extra,
+ }};
+}}
+
+const startedSessions = new Set<string>();
+const handoffChecked = new Set<string>();
+const preCompactLast = new Map<string, number>();
+
+function rememberSession(event: any, ctx: any): void {{
+ const id = sessionID(event, ctx);
+ if (!id || startedSessions.has(id)) return;
+ startedSessions.add(id);
+ postHook("session-start", payload(event, ctx, {{ reason: event?.reason }}));
+}}
+
+function postPreCompact(event: any, ctx: any): void {{
+ rememberSession(event, ctx);
+ const key = sessionID(event, ctx) || "unknown";
+ const now = Date.now();
+ const last = preCompactLast.get(key) ?? 0;
+ if (now - last < 1000) return;
+ preCompactLast.set(key, now);
+ postHook("pre-compact", payload(event, ctx, {{ reason: event?.reason }}));
+}}
+
+function postHook(eventName: string, body: Record<string, unknown>): void {{
+ const url = new URL(`${{SERVER}}/hook`);
+ url.searchParams.set("event", eventName);
+ url.searchParams.set("agent", AGENT);
+ try {{
+ void fetch(url, {{
+ method: "POST",
+ headers: {{ "Content-Type": "application/json", ...authHeaders() }},
+ body: JSON.stringify(body),
+ signal: timeoutSignal(500),
+ }}).catch(() => undefined);
+ }} catch (_e) {{
+ // Fire-and-forget. Hooks must never block OpenClaw.
+ }}
+}}
+
+async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {{
+ const currentCwd = cwd(event, ctx);
+ if (!currentCwd) return undefined;
+ const url = new URL(`${{SERVER}}/handoff`);
+ url.searchParams.set("agent", AGENT);
+ url.searchParams.set("cwd", currentCwd);
+ try {{
+ const response = await fetch(url, {{
+ headers: authHeaders(),
+ signal: timeoutSignal(1000),
+ }});
+ const text = (await response.text()).trim();
+ return text.length > 0 ? text : undefined;
+ }} catch (_e) {{
+ return undefined;
+ }}
+}}
+
+export default definePluginEntry({{
+ id: "ai-memory",
+ name: "ai-memory",
+ description: "Capture OpenClaw lifecycle events into ai-memory.",
+ register(api) {{
+ api.on("session_start", (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ }});
+
+ api.on("session_end", (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ postHook("session-end", payload(event, ctx, {{ reason: event?.reason }}));
+ }});
+
+ api.on("before_prompt_build", async (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ postHook("user-prompt", payload(event, ctx, {{
+ prompt: textFrom(event?.prompt ?? event?.userPrompt ?? event?.message ?? event?.messages?.at?.(-1)),
+ }}));
+
+ const id = sessionID(event, ctx);
+ if (!id || handoffChecked.has(id)) return;
+ handoffChecked.add(id);
+ const handoff = await fetchHandoff(event, ctx);
+ return handoff ? {{ prependContext: handoff }} : undefined;
+ }});
+
+ api.on("before_tool_call", (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ postHook("pre-tool-use", payload(event, ctx, {{
+ tool: event?.toolName,
+ toolKind: event?.toolKind,
+ callID: event?.toolCallId,
+ args: event?.params,
+ }}));
+ }});
+
+ api.on("after_tool_call", (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ postHook("post-tool-use", payload(event, ctx, {{
+ tool: event?.toolName,
+ toolKind: event?.toolKind,
+ callID: event?.toolCallId,
+ args: event?.params,
+ output: textFrom(event?.result ?? event?.output ?? event?.content),
+ error: event?.error,
+ durationMs: event?.durationMs,
+ }}));
+ }});
+
+ api.on("before_compaction", (event: any, ctx: any) => {{
+ postPreCompact(event, ctx);
+ }});
+
+ api.on("agent_end", (event: any, ctx: any) => {{
+ rememberSession(event, ctx);
+ postHook("stop", payload(event, ctx, {{ success: event?.success }}));
+ }});
+ }},
+}});
+"#,
+ server_literal = ts_string_literal(server_url),
+ token_line = token_line,
+ )
+}
+
/// 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
@@ -1089,9 +1420,9 @@ fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<Path
AgentChoice::Cursor => "cursor",
AgentChoice::GeminiCli => "gemini-cli",
AgentChoice::OpenCode => "opencode",
- // OMP/OpenClaw have no shell hook scripts → no script dir needed. Return a
- // sentinel that's never touched; the caller's apply path
- // short-circuits before any filesystem use.
+ // OMP/OpenClaw use generated TypeScript integrations → no script dir
+ // needed. Return a sentinel that's never touched; the caller's apply
+ // path short-circuits before any filesystem use.
AgentChoice::Omp => return Ok(PathBuf::from("/dev/null")),
AgentChoice::Openclaw => return Ok(PathBuf::from("/dev/null")),
};
@@ -1384,16 +1715,64 @@ mod tests {
);
}
+ // ----------------------------------------------------------------
+ // OpenClaw tests
+ // ----------------------------------------------------------------
+
+ #[test]
+ fn openclaw_plugin_package_has_manifest_and_hook_entrypoint() {
+ let package = openclaw_package_json();
+ let manifest = openclaw_manifest_json();
+ let plugin = build_openclaw_plugin("http://127.0.0.1:49374", Some("tok"));
+
+ assert!(package.contains(r#""extensions""#));
+ assert!(package.contains(r#""./index.ts""#));
+ assert!(manifest.contains(r#""id": "ai-memory""#));
+ assert!(manifest.contains(r#""onCapabilities""#));
+ assert!(manifest.contains(r#""hook""#));
+ assert!(plugin.contains("definePluginEntry"));
+ assert!(plugin.contains("api.on(\"session_start\""));
+ assert!(plugin.contains("api.on(\"session_end\""));
+ assert!(plugin.contains("api.on(\"before_prompt_build\""));
+ assert!(plugin.contains("api.on(\"before_tool_call\""));
+ assert!(plugin.contains("api.on(\"after_tool_call\""));
+ assert!(plugin.contains("api.on(\"before_compaction\""));
+ assert!(plugin.contains("api.on(\"agent_end\""));
+ assert!(plugin.contains("postHook(\"session-start\""));
+ assert!(plugin.contains("postHook(\"user-prompt\""));
+ assert!(plugin.contains("fetchHandoff"));
+ assert!(plugin.contains("prependContext: handoff"));
+ assert!(plugin.contains("Bearer ${TOKEN}"));
+ assert!(plugin.contains("tok"));
+ }
+
+ #[test]
+ fn openclaw_plugin_package_writes_all_required_files() {
+ let tmp = TempDir::new().unwrap();
+ let outcomes =
+ write_openclaw_plugin_package(tmp.path(), "http://127.0.0.1:49374", None).unwrap();
+
+ assert_eq!(outcomes.len(), 3);
+ assert!(tmp.path().join("package.json").is_file());
+ assert!(tmp.path().join("openclaw.plugin.json").is_file());
+ assert!(tmp.path().join("index.ts").is_file());
+ assert!(
+ fs::read_to_string(tmp.path().join("index.ts"))
+ .unwrap()
+ .contains("const TOKEN: string | null = null;")
+ );
+ }
+
#[cfg(unix)]
#[test]
- fn curl_installer_accepts_pi_aliases_as_omp_extension() {
+ fn curl_installer_accepts_generated_integration_agents() {
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("scripts")
.join("install-hooks.sh");
- for alias in ["pi", "oh-my-pi"] {
+ for alias in ["opencode", "openclaw", "pi", "oh-my-pi"] {
let output = Command::new("bash")
.arg(&script)
.arg("--agent")
@@ -1405,20 +1784,21 @@ mod tests {
assert!(
output.status.success(),
- "script rejected alias {alias}: stdout={}, stderr={}",
+ "script rejected generated integration alias {alias}: stdout={}, stderr={}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
- assert!(
- stdout.contains("install-hooks --agent omp --apply"),
- "script should route alias {alias} to the generated OMP extension path; stdout={stdout}"
- );
- assert!(
- stdout.contains("~/.omp/agent/extensions/ai-memory.ts"),
- "script should describe the OMP extension file for alias {alias}; stdout={stdout}"
- );
+ match alias {
+ "opencode" => assert!(stdout.contains("install-hooks --agent opencode --apply")),
+ "openclaw" => assert!(stdout.contains("install-hooks --agent openclaw --apply")),
+ "pi" | "oh-my-pi" => {
+ assert!(stdout.contains("install-hooks --agent omp --apply"));
+ assert!(stdout.contains("~/.omp/agent/extensions/ai-memory.ts"));
+ }
+ _ => unreachable!(),
+ }
}
}
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 16f949d2..88db8bac 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -189,7 +189,8 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];
if let Some(b) = &bearer {
cmd_args.push(json!("--header"));
- cmd_args.push(json!(format!("Authorization: {b}")));
+ cmd_args.push(json!("Authorization:${AI_MEMORY_AUTH_HEADER}"));
+ entry.insert("env".into(), json!({"AI_MEMORY_AUTH_HEADER": b}));
}
entry.insert("command".into(), json!("npx"));
entry.insert("args".into(), serde_json::Value::Array(cmd_args));
@@ -453,12 +454,19 @@ fn render_cursor(args: &InstallMcpArgs) -> Result<String> {
fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {
// mcp-remote's --header flag is how we plumb the Authorization
- // through Claude Desktop's stdio-only config.
+ // through Claude Desktop's stdio-only config. Put the Bearer value
+ // in env so Windows subprocess parsing never has to split a value
+ // containing a space.
+ let bearer = bearer_header_value(args.auth_token.as_deref());
let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];
- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {
+ let mut server = serde_json::Map::new();
+ if let Some(b) = &bearer {
cmd_args.push(json!("--header"));
- cmd_args.push(json!(format!("Authorization: {b}")));
+ cmd_args.push(json!("Authorization:${AI_MEMORY_AUTH_HEADER}"));
+ server.insert("env".into(), json!({"AI_MEMORY_AUTH_HEADER": b}));
}
+ server.insert("command".into(), json!("npx"));
+ server.insert("args".into(), serde_json::Value::Array(cmd_args));
Ok(format!(
"# Claude Desktop — write to claude_desktop_config.json:\n\
# - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\n\
@@ -473,12 +481,7 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {
# Updates\" is not enough.\n\
{snippet}\n",
snippet = serde_json::to_string_pretty(&json!({
- "mcpServers": {
- args.name.as_str(): {
- "command": "npx",
- "args": cmd_args,
- }
- }
+ "mcpServers": { args.name.as_str(): server }
}))?,
))
}
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 0ab29c2d..1a899e5a 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -135,12 +135,13 @@ pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
/// 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] = [
+pub(crate) const CURSOR_EVENTS: [(&str, &str); 8] = [
("sessionStart", "session-start.sh"),
("sessionEnd", "session-end.sh"),
("beforeSubmitPrompt", "user-prompt-submit.sh"),
("preToolUse", "pre-tool-use.sh"),
("postToolUse", "post-tool-use.sh"),
+ ("postToolUseFailure", "post-tool-use.sh"),
("preCompact", "pre-compact.sh"),
("stop", "stop.sh"),
];
@@ -460,6 +461,7 @@ mod tests {
.unwrap_or_default();
assert!(events.contains(&"sessionStart"));
assert!(events.contains(&"preToolUse"));
+ assert!(events.contains(&"postToolUseFailure"));
assert!(
!events.contains(&"SessionStart"),
"Cursor uses camelCase, not PascalCase"
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 6f7b9c7e..762b2119 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -51,7 +51,10 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),
..args
};
- if matches!(args.agent, AgentChoice::OpenCode | AgentChoice::Omp) {
+ if matches!(
+ args.agent,
+ AgentChoice::OpenCode | AgentChoice::Omp | AgentChoice::Openclaw
+ ) {
emit_extension_setup_hint(&args);
return Ok(());
}
@@ -62,14 +65,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
AgentChoice::GeminiCli => "gemini-cli",
AgentChoice::OpenCode => unreachable!("opencode handled above"),
AgentChoice::Omp => unreachable!("omp handled above"),
- 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."
- );
- }
+ AgentChoice::Openclaw => unreachable!("openclaw handled above"),
};
let source = resolve_source(args.source.as_deref(), agent_sub)?;
@@ -130,11 +126,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
AgentChoice::OpenCode => unreachable!("opencode handled above"),
AgentChoice::Omp => unreachable!("omp handled above"),
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");
+ unreachable!("openclaw handled by the generated-integration hint above");
}
}
Ok(())
@@ -154,7 +146,13 @@ fn emit_extension_setup_hint(args: &SetupAgentArgs) {
"Then restart OMP so it loads ~/.omp/agent/extensions/ai-memory.ts.",
"pi",
),
- _ => unreachable!("only extension-based agents reach this hint"),
+ AgentChoice::Openclaw => (
+ "OpenClaw",
+ "openclaw",
+ "Then restart the OpenClaw gateway if it does not auto-restart after plugin install.",
+ "openclaw",
+ ),
+ _ => unreachable!("only generated-integration agents reach this hint"),
};
println!("# {label} uses a TypeScript extension/plugin, not extracted shell scripts.");
println!("# Install it directly instead:");
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index 853cf19e..4233f1b9 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -169,6 +169,15 @@ pub enum AgentKind {
Codex,
/// OpenCode (open-source coding agent).
OpenCode,
+ /// Cursor IDE agent.
+ Cursor,
+ /// Google Gemini CLI.
+ GeminiCli,
+ /// Anthropic Claude Desktop.
+ ClaudeDesktop,
+ /// OpenClaw personal AI gateway.
+ #[serde(rename = "openclaw", alias = "open-claw")]
+ OpenClaw,
/// Oh My Pi (`omp`) / Pi-compatible coding agent.
Omp,
/// Anything else (manual capture, future agents).
@@ -183,6 +192,10 @@ impl AgentKind {
Self::ClaudeCode => "claude-code",
Self::Codex => "codex",
Self::OpenCode => "open-code",
+ Self::Cursor => "cursor",
+ Self::GeminiCli => "gemini-cli",
+ Self::ClaudeDesktop => "claude-desktop",
+ Self::OpenClaw => "openclaw",
Self::Omp => "omp",
Self::Other => "other",
}
@@ -257,5 +270,12 @@ mod tests {
let omp = serde_json::to_string(&AgentKind::Omp).unwrap();
assert_eq!(omp, "\"omp\"");
+
+ let openclaw = serde_json::to_string(&AgentKind::OpenClaw).unwrap();
+ assert_eq!(openclaw, "\"openclaw\"");
+ assert_eq!(
+ serde_json::from_str::<AgentKind>("\"open-claw\"").unwrap(),
+ AgentKind::OpenClaw
+ );
}
}
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 7181ee71..56bd21f9 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
pub struct HookQuery {
/// Lifecycle event identifier (kebab-case or snake_case).
pub event: String,
- /// Agent CLI identifier (`claude-code`, `codex`, `open-code`, `omp`).
+ /// Agent CLI identifier (`claude-code`, `codex`, `cursor`, etc.).
pub agent: Option<String>,
}
@@ -63,14 +63,23 @@ impl HookEvent {
#[must_use]
pub fn parse(s: &str) -> Self {
match s {
- "session-start" | "session_start" | "SessionStart" => Self::SessionStart,
- "user-prompt" | "user_prompt" | "UserPromptSubmit" => Self::UserPrompt,
- "pre-tool-use" | "pre_tool_use" | "PreToolUse" => Self::PreToolUse,
- "post-tool-use" | "post_tool_use" | "PostToolUse" => Self::PostToolUse,
- "pre-compact" | "pre_compact" | "PreCompact" => Self::PreCompact,
+ "session-start" | "session_start" | "SessionStart" | "sessionStart" => {
+ Self::SessionStart
+ }
+ "user-prompt" | "user_prompt" | "UserPromptSubmit" | "beforeSubmitPrompt" => {
+ Self::UserPrompt
+ }
+ "pre-tool-use" | "pre_tool_use" | "PreToolUse" | "preToolUse" | "BeforeTool" => {
+ Self::PreToolUse
+ }
+ "post-tool-use" | "post_tool_use" | "PostToolUse" | "postToolUse"
+ | "postToolUseFailure" | "PostToolUseFailure" | "AfterTool" => Self::PostToolUse,
+ "pre-compact" | "pre_compact" | "PreCompact" | "preCompact" | "PreCompress" => {
+ Self::PreCompact
+ }
"notification" | "Notification" => Self::Notification,
"stop" | "Stop" => Self::Stop,
- "session-end" | "session_end" | "SessionEnd" => Self::SessionEnd,
+ "session-end" | "session_end" | "SessionEnd" | "sessionEnd" => Self::SessionEnd,
_ => Self::Other,
}
}
@@ -100,6 +109,10 @@ pub fn parse_agent(s: &str) -> AgentKind {
"claude-code" | "claude_code" | "claude" => AgentKind::ClaudeCode,
"codex" => AgentKind::Codex,
"open-code" | "opencode" => AgentKind::OpenCode,
+ "cursor" => AgentKind::Cursor,
+ "gemini-cli" | "gemini" => AgentKind::GeminiCli,
+ "claude-desktop" | "claude_desktop" => AgentKind::ClaudeDesktop,
+ "openclaw" | "open-claw" => AgentKind::OpenClaw,
"omp" | "pi" | "oh-my-pi" => AgentKind::Omp,
_ => AgentKind::Other,
}
@@ -416,6 +429,11 @@ mod tests {
assert_eq!(parse_agent("codex"), AgentKind::Codex);
assert_eq!(parse_agent("opencode"), AgentKind::OpenCode);
assert_eq!(parse_agent("open-code"), AgentKind::OpenCode);
+ assert_eq!(parse_agent("cursor"), AgentKind::Cursor);
+ assert_eq!(parse_agent("gemini-cli"), AgentKind::GeminiCli);
+ assert_eq!(parse_agent("gemini"), AgentKind::GeminiCli);
+ assert_eq!(parse_agent("claude-desktop"), AgentKind::ClaudeDesktop);
+ assert_eq!(parse_agent("openclaw"), AgentKind::OpenClaw);
assert_eq!(parse_agent("omp"), AgentKind::Omp);
assert_eq!(parse_agent("pi"), AgentKind::Omp);
assert_eq!(parse_agent("oh-my-pi"), AgentKind::Omp);
@@ -424,7 +442,6 @@ mod tests {
// attributed to the catch-all bucket.
assert_eq!(parse_agent(""), AgentKind::Other);
assert_eq!(parse_agent("CLAUDE-CODE"), AgentKind::Other); // case-sensitive on purpose
- assert_eq!(parse_agent("gemini-cli"), AgentKind::Other);
assert_eq!(parse_agent("../../etc/passwd"), AgentKind::Other);
}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index a610c6a1..a2c27a79 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -555,6 +555,10 @@ fn agent_kind_as_str(kind: AgentKind) -> &'static str {
AgentKind::ClaudeCode => "claude-code",
AgentKind::Codex => "codex",
AgentKind::OpenCode => "open-code",
+ AgentKind::Cursor => "cursor",
+ AgentKind::GeminiCli => "gemini-cli",
+ AgentKind::ClaudeDesktop => "claude-desktop",
+ AgentKind::OpenClaw => "openclaw",
AgentKind::Omp => "omp",
AgentKind::Other => "other",
}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 88930c1f..6835ee59 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1995,6 +1995,10 @@ fn parse_agent(s: &str) -> AgentKind {
"claude-code" => AgentKind::ClaudeCode,
"codex" => AgentKind::Codex,
"open-code" => AgentKind::OpenCode,
+ "cursor" => AgentKind::Cursor,
+ "gemini-cli" => AgentKind::GeminiCli,
+ "claude-desktop" => AgentKind::ClaudeDesktop,
+ "openclaw" => AgentKind::OpenClaw,
"omp" => AgentKind::Omp,
_ => AgentKind::Other,
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 9cb81cf7..81f8c036 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -7,8 +7,8 @@
## Purpose
ai-memory is a single Rust binary that gives AI coding agents (Claude
-Code, OpenAI Codex, Cursor, Gemini CLI, OpenCode, OMP, and MCP-capable
-clients) long-term memory shared across CLIs.
+Code, OpenAI Codex, Cursor, Gemini CLI, OpenClaw, OpenCode, OMP, and
+MCP-capable clients) long-term memory shared across CLIs.
Quit one mid-task; open another in the same directory; continue. No
manual `write_note` ceremony, no copy-pasting summaries between
sessions.
@@ -26,7 +26,8 @@ markdown stays the source of truth.
┌──────────────────────┐
│ Claude Code / Codex │
│ Cursor / Gemini CLI │
- │ OpenCode / OMP │
+ │ OpenClaw / OpenCode │
+ │ OMP │
└──────────┬───────────┘
lifecycle hooks │ stdio
(fire-and-forget HTTP) ▼
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 8111ad14..44845a9e 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -8,8 +8,8 @@
A self-contained Rust binary that:
-1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, OpenCode, OMP, and MCP-capable clients).
-2. Captures the agent's session **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that the agent CLIs invoke (Claude Code / Codex / Cursor / Gemini CLI lifecycle hooks, OpenCode/OMP TypeScript integrations). Optional transcript-tail fallback for agents without hook APIs.
+1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, OpenClaw, OpenCode, OMP, and MCP-capable clients).
+2. Captures the agent's session **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that the agent CLIs invoke (Claude Code / Codex / Cursor / Gemini CLI lifecycle hooks, OpenClaw / OpenCode / OMP TypeScript integrations). Optional transcript-tail fallback for agents without hook APIs.
3. Maintains a **Karpathy-style wiki**: incrementally-compiled markdown pages with cross-links, supersession, an `index.md` and a `log.md`.
4. Serves retrieval via the MCP `tools/list` to coding agents: a handful of *narrow* tools, not 50.
5. Ships a **Docker image** (`docker run -v ai-memory-data:/data -p 49374:49374 ai-memory`) so it can move between desktop and homelab.
diff --git a/docs/install.md b/docs/install.md
index bcc64a09..ed51869f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -81,17 +81,17 @@ Each agent CLI needs two things:
Without this, the agent can still query memory but capture
becomes manual.
-Claude Desktop and OpenClaw are MCP-only today. Claude Code, Codex,
-OpenCode, OMP, Cursor, and Gemini CLI have lifecycle capture paths
-through `install-hooks`.
+Claude Desktop is MCP-only today. Claude Code, Codex, OpenCode, OMP,
+Cursor, Gemini CLI, and OpenClaw have lifecycle capture paths through
+`install-hooks`.
> **Two-step hook install pattern.** Claude Code, Codex, Cursor, and
> Gemini CLI use shell/PowerShell hook scripts: (1) `docker cp` the
> bundled scripts to your home dir, (2) `docker run --rm install-hooks`
> to render the config snippet.
-> OpenCode and OMP are different: they use generated TypeScript
-> plugin/extension files, so no shell-script extraction is needed for
-> those clients.
+> OpenClaw, OpenCode, and OMP are different: they use generated
+> TypeScript plugin/extension files, so no shell-script extraction is
+> needed for those clients.
### OpenAI Codex
@@ -190,6 +190,10 @@ docker run --rm akitaonrails/ai-memory:latest \
install-mcp --client cursor --auth-token "$TOKEN" \
--server-url "http://homelab:49374/mcp"
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent cursor --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374"
+
docker run --rm akitaonrails/ai-memory:latest \
install-mcp --client claude-desktop --auth-token "$TOKEN" \
--server-url "http://homelab:49374/mcp"
@@ -205,21 +209,25 @@ docker run --rm akitaonrails/ai-memory:latest \
docker run --rm akitaonrails/ai-memory:latest \
install-mcp --client openclaw --auth-token "$TOKEN" \
--server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent openclaw --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374"
```
-Cursor and Gemini CLI support both `install-mcp` and `install-hooks`.
-Claude Desktop and OpenClaw are MCP-only here, so you'll need to nudge
-the model to call `memory_query` / `memory_handoff_accept` itself. For
-clients with `install-hooks` support, the capture path handles handoff
-injection at session start.
+Cursor, Gemini CLI, and OpenClaw support both `install-mcp` and
+`install-hooks`. Claude Desktop is MCP-only here, so you'll need to
+nudge the model to call `memory_query` / `memory_handoff_accept` itself.
+For clients with `install-hooks` support, the capture path handles
+handoff injection at session start.
---
## Installing hooks without docker
If you only need to use ai-memory *from* a machine (i.e. that
-machine doesn't run the server), the curl installer pulls the seven
-hook scripts straight from GitHub:
+machine doesn't run the server), the curl installer pulls shell hook
+scripts straight from GitHub for shell-hook agents:
```bash
curl -sSL https://raw.githubusercontent.com/akitaonrails/ai-memory/main/scripts/install-hooks.sh \
@@ -234,10 +242,11 @@ docker run --rm akitaonrails/ai-memory:latest \
--auth-token "$TOKEN"
```
-The curl script installer supports `--agent claude-code|codex|opencode|omp|pi`
-and `--to <dir>`; `--help` prints the full flag list. OpenCode and OMP do
-not need this script installer because `install-hooks --agent opencode`
-and `install-hooks --agent omp` / `--agent pi` generate TypeScript files instead.
+The curl script installer supports
+`--agent claude-code|codex|cursor|gemini-cli|opencode|openclaw|omp|pi`
+and `--to <dir>`; `--help` prints the full flag list. OpenCode,
+OpenClaw, and OMP do not need script extraction because `install-hooks`
+generates TypeScript plugin/extension files for them instead.
This path is friction-free when:
- You have curl + bash but not docker
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index d67977a1..e328235a 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -19,24 +19,24 @@
This page documents how to register ai-memory as an MCP server with
agent CLIs beyond the README quick start.
-Claude Code, OpenAI Codex, Cursor, Gemini CLI, OpenCode, and OMP have
-automatic capture integrations (shell/PowerShell hooks for Claude Code /
-Codex / Cursor / Gemini CLI, TypeScript plugin/extension files for
-OpenCode / OMP) and are covered in the [main README](../README.md#quick-start).
+Claude Code, OpenAI Codex, Cursor, Gemini CLI, OpenClaw, OpenCode, and
+OMP have automatic capture integrations (shell/PowerShell hooks for
+Claude Code / Codex / Cursor / Gemini CLI, TypeScript plugin/extension
+files for OpenClaw / OpenCode / OMP) and are covered in the
+[main README](../README.md#quick-start).
-Some clients on this page are **MCP-only**: they expose long-term
-memory to their LLM via ai-memory's MCP tools (`memory_query`,
-`memory_recent`, `memory_handoff_accept`, etc.), but they do not
-auto-capture session events into ai-memory's `/hook` endpoint. The
-trade-off:
+Claude Desktop is **MCP-only** here: it exposes long-term memory to its
+LLM via ai-memory's MCP tools (`memory_query`, `memory_recent`,
+`memory_handoff_accept`, etc.), but it does not auto-capture session
+events into ai-memory's `/hook` endpoint. The trade-off:
| | What you get | What you don't get |
|---|---|---|
| **MCP only** | LLM can query the wiki, accept handoffs, run memory_consolidate | No automatic session-end summaries; no auto-handoff at session boundaries |
| **MCP + hooks** | All of the above *plus* every prompt/tool-call captured automatically; handoffs surface at SessionStart with no human prompting | - |
-For MCP-only clients, you can still cover the session-boundary gap by
-asking the LLM to call `memory_handoff_begin` manually before quitting.
+For MCP-only use, you can still cover the session-boundary gap by asking
+the LLM to call `memory_handoff_begin` manually before quitting.
> **One-shot tip:** every snippet below is also reachable from the
> CLI:
@@ -68,10 +68,13 @@ asking the LLM to call `memory_handoff_begin` manually before quitting.
**Gotchas:**
- Cursor uses the `url` key for HTTP/SSE transports. Stdio uses
`command` + `args` instead.
-- After editing `mcp.json`, restart Cursor or toggle the server
- off+on in **Settings → MCP**. Live reload is in newer builds but
- still occasionally requires a manual restart.
-- Source: <https://cursor.com/docs/context/mcp>
+- Cursor hooks live in `~/.cursor/hooks.json` or `.cursor/hooks.json`.
+ ai-memory maps `sessionStart`, `sessionEnd`, `beforeSubmitPrompt`,
+ `preToolUse`, `postToolUse`, `postToolUseFailure`, `preCompact`, and
+ `stop` to the shared capture path.
+- Cursor watches `hooks.json` on save. For MCP config changes, restart
+ Cursor or toggle the server off+on in **Settings → MCP**.
+- Sources: <https://cursor.com/docs/mcp>, <https://cursor.com/docs/hooks.md>
---
@@ -104,10 +107,18 @@ stdio shim. Requires Node.js installed on the same machine.
**Gotchas:**
- After editing the config, **fully quit and relaunch** Claude
Desktop. "Check for Updates…" is not enough.
+- Claude Desktop also has account-level remote custom connectors and
+ `.mcpb` desktop extensions. The ai-memory CLI manages the local
+ JSON-config path because it works with localhost/LAN servers and does
+ not require publishing an HTTPS connector.
+- Claude Desktop exposes MCP tools but no lifecycle hooks, so automatic
+ prompt/tool capture and session-boundary handoffs are not possible
+ unless Anthropic adds a desktop hook/plugin surface.
- If the MCP indicator doesn't appear after restart, check the logs:
`~/Library/Logs/Claude/mcp*.log` (macOS) or `%APPDATA%\Claude\logs\`
(Windows).
-- Source: <https://modelcontextprotocol.io/quickstart/user>
+- Sources: <https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop>,
+ <https://support.claude.com/en/articles/11175166-how-to-connect-remote-mcp-integrations-to-claude>
---
@@ -157,9 +168,8 @@ capture path; `SessionStart` also fetches pending handoffs.
## OpenClaw
-**Status:** ✅ MCP supported. ⚠️ Hooks exist (TypeScript plugins,
-not POSIX shell). Hook integration would need a small TS plugin in
-`integrations/openclaw/`; not shipped here.
+**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a native
+OpenClaw plugin generated by `ai-memory install-hooks --agent openclaw --apply`.
**Config file:** `~/.openclaw/config.json` (the OpenClaw docs reference
this path indirectly; verify with your `openclaw config show`).
@@ -181,13 +191,19 @@ OpenClaw distinguishes transports explicitly. Use
```
**Gotchas:**
-- OpenClaw config keys under `mcp.*` hot-reload without a gateway
- restart. Hook config changes do require restarting the gateway.
-- A TypeScript hook plugin that mirrors the Claude Code hook bundle
- would let OpenClaw auto-capture sessions; until that exists, treat
- OpenClaw as MCP-only.
+- `install-hooks --agent openclaw --apply` writes a local plugin package
+ under ai-memory's data dir, then runs `openclaw plugins install --link
+ <dir> --force` when the `openclaw` CLI is on `PATH`. If the CLI is not
+ available, it prints the exact install command.
+- The plugin registers OpenClaw `session_start`, `session_end`,
+ `before_prompt_build`, `before_tool_call`, `after_tool_call`,
+ `before_compaction`, and `agent_end` hooks. `before_prompt_build`
+ injects pending handoffs via OpenClaw's `prependContext` hook result.
+- Plugin installs or updates require a Gateway restart unless your
+ managed OpenClaw Gateway auto-restarts after plugin source changes.
- Sources: <https://docs.openclaw.ai/cli/mcp>,
- <https://docs.openclaw.ai/automation/hooks>
+ <https://docs.openclaw.ai/plugins/hooks>,
+ <https://docs.openclaw.ai/plugins/manage-plugins>
---
@@ -262,9 +278,9 @@ isn't being picked up. Check:
return a JSON-RPC error (not a connection refused). If refused,
start ai-memory: `docker start ai-memory` or
`ai-memory serve --transport http`.
-2. **Did the client reload the config?** Cursor, Claude Desktop, and
- OMP need a restart. Gemini CLI and OpenClaw usually pick it up on
- next session-start.
+2. **Did the client reload the config?** Claude Desktop and OMP need a
+ restart. Cursor watches hooks but usually needs MCP reload/toggle.
+ OpenClaw plugin changes need a Gateway restart unless it auto-restarted.
3. **Are you on the right port?** ai-memory's default is **49374**
(`0xC0DE` in hex). If you remapped, update the URL in every
client's config.
@@ -284,16 +300,14 @@ that *starts* the next one - to play nicely with ai-memory:
| Side | What's needed | Covered by |
|---|---|---|
-| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Codex, Cursor, Gemini CLI, and OMP. OpenCode has no true session-end event, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |
-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Cursor / Gemini CLI / OpenCode / OMP. (b) works for any MCP-capable client if you nudge the model - see [the CLAUDE.md snippet](../README.md#nudging-the-agent-to-use-memory-proactively). |
+| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Codex, Cursor, Gemini CLI, OpenClaw, and OMP. OpenCode has no true session-end event, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |
+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Cursor / Gemini CLI / OpenClaw / OpenCode / OMP. (b) works for any MCP-capable client if you nudge the model - see [the CLAUDE.md snippet](../README.md#nudging-the-agent-to-use-memory-proactively). |
So a typical mixed workflow looks like:
- **Claude Code → Cursor.** Claude Code's `SessionEnd` creates the
- handoff automatically. Cursor doesn't have a SessionStart hook, so
- in Cursor's first chat you nudge the model: "Call
- memory_handoff_accept to resume prior work." The model fetches the
- handoff via MCP and continues.
+ handoff automatically. Cursor's `sessionStart` hook fetches and
+ prepends it when `install-hooks --agent cursor --apply` is installed.
- **Claude Desktop → Claude Code.** Claude Desktop doesn't write a
handoff (no hooks). To resume in Claude Code, you'd have had to
call `memory_handoff_begin` manually in Claude Desktop before
diff --git a/docs/windows.md b/docs/windows.md
index 3f6a5856..1b124055 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -141,16 +141,16 @@ Windows agent builds.
- Claude Code may be used natively on Windows or from inside WSL2. Test
which process launches the hooks before assuming path format.
-- Codex, OpenCode, Cursor, and Gemini CLI may each choose different
+- Codex, OpenCode, Cursor, Gemini CLI, and OpenClaw may each choose different
Windows config locations or shell execution behavior. ai-memory uses
the current best-known defaults, but they need validation on real
installations.
- MCP over HTTP should be less path-sensitive than hooks, but
`install-mcp --apply` still writes to a client-specific config file;
confirm the agent actually loads it.
-- OpenCode and OMP/Pi use generated TypeScript integrations rather than
- the shell hook bundle, so their Windows behavior depends on the host
- runtime loading those files correctly.
+- OpenClaw, OpenCode, and OMP/Pi use generated TypeScript integrations
+ rather than the shell hook bundle, so their Windows behavior depends
+ on the host runtime loading those files correctly.
## Suggested Test Checklist
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
index db74b362..c67f6ea4 100755
--- a/scripts/install-hooks.sh
+++ b/scripts/install-hooks.sh
@@ -10,8 +10,9 @@
# | bash -s -- --agent claude-code
#
# Options:
-# --agent <claude-code|codex|opencode|omp|pi> which agent (default: claude-code;
-# opencode/omp/pi print extension hints)
+# --agent <claude-code|codex|cursor|gemini-cli|opencode|openclaw|omp|pi>
+# which agent (default: claude-code;
+# generated-plugin agents print hints)
# --to <dir> install root (default: $HOME/.ai-memory/hooks)
# --ref <git-ref> repo ref to pull from (default: main)
#
@@ -45,9 +46,9 @@ while [[ $# -gt 0 ]]; do
done
case "$AGENT" in
- claude-code|codex|opencode|omp|pi|oh-my-pi) ;;
+ claude-code|codex|cursor|gemini-cli|opencode|openclaw|omp|pi|oh-my-pi) ;;
*)
- echo "unsupported agent: $AGENT (expected claude-code | codex | opencode | omp | pi | oh-my-pi)" >&2
+ echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | opencode | openclaw | omp | pi | oh-my-pi)" >&2
exit 64 ;;
esac
@@ -58,6 +59,13 @@ if [[ "$AGENT" == "opencode" ]]; then
exit 0
fi
+if [[ "$AGENT" == "openclaw" ]]; then
+ echo "OpenClaw uses a generated native TypeScript plugin, not shell hook scripts."
+ echo "Run: ai-memory install-hooks --agent openclaw --apply"
+ echo "Then restart the OpenClaw gateway if it does not auto-restart after plugin install."
+ exit 0
+fi
+
if [[ "$AGENT" == "omp" || "$AGENT" == "pi" || "$AGENT" == "oh-my-pi" ]]; then
echo "OMP uses a generated TypeScript extension, not shell hook scripts."
echo "Run: ai-memory install-hooks --agent omp --apply"