Skip to content

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

Rust

fix(kimi-code): complete hook and uninstall coverage

AkitaOnRails96c8f88f8680
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1d42639..992931c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,9 +27,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(Kimi Code treats `url` with no `transport` field as streamable HTTP) plus
optional bearer `headers`. `install-hooks` merges `[[hooks]]` entries into
`~/.kimi-code/config.toml`, preserving the provider/model settings the same
- file holds, and covers 9 events: `SessionStart`, `SessionEnd`,
- `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`,
- `SubagentStop`, and `PreCompact`. Both paths honor `$KIMI_CODE_HOME`.
+ file holds, and covers 10 events: `SessionStart`, `SessionEnd`,
+ `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`,
+ `SubagentStart`, `SubagentStop`, and `PreCompact`. Both paths honor
+ `$KIMI_CODE_HOME`.
Handoff injection happens at `SessionStart` through hook stdout, which Kimi
Code appends to the model context; `setup-agent` and `uninstall` handle the
new agent like the other first-class integrations. The `install-mcp` entry
diff --git a/README.md b/README.md
index 9826998a..066fd9b1 100644
--- a/README.md
+++ b/README.md
@@ -35,7 +35,7 @@
| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |
-| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 9 events including subagent start/stop); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `SessionStart` stdout. |
+| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including failed tools and subagent start/stop); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `SessionStart` stdout. |
| VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |
| Hermes Agent | Community | A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available. It is not part of ai-memory's first-party install surface; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. |
| LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode Zen/Go, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 93639f3f..aa254539 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -47,20 +47,22 @@ pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [
("SubagentStop", "subagent-stop.sh"),
];
-/// Kimi Code lifecycle events ai-memory hooks. Same 9-event vocabulary
-/// as Claude Code (`CLAUDE_CODE_EVENTS`), but Kimi Code wires hooks as
-/// `[[hooks]]` entries in `$KIMI_CODE_HOME/config.toml` (TOML) instead of
-/// a JSON settings file, so its payload comes from
+/// Kimi Code lifecycle events ai-memory hooks. Kimi exposes Claude Code's
+/// 9-event vocabulary plus a separate `PostToolUseFailure` event, because
+/// its `PostToolUse` event fires only for successful calls. Kimi Code wires
+/// hooks as `[[hooks]]` entries in `$KIMI_CODE_HOME/config.toml` (TOML)
+/// instead of a JSON settings file, so its payload comes from
/// [`kimi_code_hook_commands`] rather than the JSON hook shapes.
///
-/// Adding a hook event means updating this list AND adding the matching
-/// `.sh` and `.ps1` files under `hooks/kimi-code/`. The install-hooks
-/// parity test fails if the bundle drifts.
-pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 9] = [
+/// New handler scripts must also be added as `.sh` and `.ps1` files under
+/// `hooks/kimi-code/`. Multiple events may reuse one handler when they map to
+/// the same internal hook kind, as the two post-tool events do below.
+pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 10] = [
("SessionStart", "session-start.sh"),
("UserPromptSubmit", "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"),
("SessionEnd", "session-end.sh"),
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 3205734b..ffb036a2 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -37,8 +37,8 @@ use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, SetupAgentArgs};
use crate::commands::install_mcp;
use crate::commands::render_shared::{
- ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CLAUDE_CODE_EVENTS, CODEX_PROFILE,
- CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_devin_payload,
+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,
+ GEMINI_PROFILE, KIMI_CODE_EVENTS, build_claude_code_payload, build_devin_payload,
build_grok_payload, hook_script_for_current_platform,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -145,11 +145,10 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
&args,
&[&ANTIGRAVITY_TOOL_EVENTS, &ANTIGRAVITY_LIFECYCLE_EVENTS],
),
- // Kimi Code's nine hook events mirror Claude Code's vocabulary
- // exactly; its `[[hooks]]` TOML merge into config.toml (shared
- // with user provider/model settings) is owned by install-hooks
- // apply-mode, so print-mode stays a conservative script listing.
- AgentChoice::KimiCode => emit_other(&emit_root, agent_sub, &args, &[&CLAUDE_CODE_EVENTS]),
+ // Kimi's success and failure post-tool events share one script. The
+ // script listing is deduplicated below; apply-mode owns the exact
+ // `[[hooks]]` TOML merge into the user's config.toml.
+ AgentChoice::KimiCode => emit_other(&emit_root, agent_sub, &args, &[&KIMI_CODE_EVENTS]),
AgentChoice::OpenCode
| AgentChoice::Pi
| AgentChoice::Omp
@@ -363,7 +362,10 @@ fn event_script_paths(emit_root: &Path, event_lists: &[&[(&str, &str)]]) -> Vec<
for events in event_lists {
for (_, script) in *events {
let script = hook_script_for_current_platform(script);
- paths.push(emit_root.join(script.as_ref()));
+ let path = emit_root.join(script.as_ref());
+ if !paths.contains(&path) {
+ paths.push(path);
+ }
}
}
paths
@@ -632,12 +634,11 @@ mod tests {
}
#[test]
- fn kimi_code_manual_script_paths_cover_claude_code_event_set() {
- // Kimi Code's hook vocabulary (SessionStart, SessionEnd,
- // UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStart,
- // SubagentStop, PreCompact) mirrors Claude Code's nine events.
+ fn kimi_code_manual_script_paths_cover_all_events_without_duplicates() {
+ // Kimi registers ten rules, but its successful and failed post-tool
+ // events intentionally share the same handler script.
let root = Path::new("/hooks/kimi-code");
- let paths = event_script_paths(root, &[&CLAUDE_CODE_EVENTS]);
+ let paths = event_script_paths(root, &[&KIMI_CODE_EVENTS]);
let rendered = paths
.iter()
.map(|path| path.to_string_lossy())
@@ -660,6 +661,12 @@ mod tests {
"Kimi Code setup-agent must list {script}; got:\n{rendered}"
);
}
+ assert!(
+ KIMI_CODE_EVENTS
+ .iter()
+ .any(|(event, _)| *event == "PostToolUseFailure")
+ );
+ assert_eq!(KIMI_CODE_EVENTS.len(), 10);
assert_eq!(paths.len(), 9);
}
}
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index d4715c9f..062893e2 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -442,7 +442,9 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
}
RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,
RewriteOp::KimiCodeHooksToml => strip_kimi_code_hooks(&out)?.new_content,
- RewriteOp::McpJson(client) => strip_mcp_json(&out, client, name, url)?.0,
+ RewriteOp::McpJson(client) => {
+ strip_mcp_json_client(&out, client, name, url)?.0
+ }
RewriteOp::McpToml => strip_mcp_toml(&out, name, url)?.0,
};
}
diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rs
index 3ad3c234..0c2d3ece 100644
--- a/crates/ai-memory-cli/tests/removal.rs
+++ b/crates/ai-memory-cli/tests/removal.rs
@@ -1028,3 +1028,58 @@ fn uninstall_mcp_custom_url_removes_kimi_code_only_by_endpoint() {
);
assert!(after["mcpServers"].get("other").is_some());
}
+
+#[test]
+fn default_uninstall_removes_installed_kimi_code_flavored_url() {
+ let _guard = cli_test_lock();
+ let home = tempfile::tempdir().unwrap();
+ let kimi = home.path().join(".kimi-code");
+ std::fs::create_dir_all(&kimi).unwrap();
+ let mcp = kimi.join("mcp.json");
+ std::fs::write(
+ &mcp,
+ r#"{"mcpServers":{"other":{"url":"http://other/mcp"}}}"#,
+ )
+ .unwrap();
+
+ let install = command_with_home(home.path())
+ .args([
+ "install-mcp",
+ "--client",
+ "kimi-code",
+ "--server-url",
+ "http://127.0.0.1:49374",
+ "--apply",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ install.status.success(),
+ "install-mcp failed: {}",
+ String::from_utf8_lossy(&install.stderr)
+ );
+ let installed: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&mcp).unwrap()).unwrap();
+ assert_eq!(
+ installed["mcpServers"]["ai-memory"]["url"],
+ "http://127.0.0.1:49374/mcp?flavor=moonshot"
+ );
+
+ let output = command_with_home(home.path())
+ .args(["uninstall", "--apply", "--only", "mcp", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "uninstall failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let after: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&mcp).unwrap()).unwrap();
+ assert!(
+ after["mcpServers"].get("ai-memory").is_none(),
+ "the exact flavored URL install-mcp writes must be removed"
+ );
+ assert!(after["mcpServers"].get("other").is_some());
+}
diff --git a/docs/install.md b/docs/install.md
index 8c28dd99..772fc037 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -597,9 +597,10 @@ ai-memory install-hooks --agent kimi-code --apply \
```
`install-hooks` merges `[[hooks]]` entries into `config.toml`, preserving the
-provider/model settings the same file holds. Entries cover 9 events —
+provider/model settings the same file holds. Entries cover 10 events —
`SessionStart`, `SessionEnd`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
-`Stop`, `SubagentStart`, `SubagentStop`, and `PreCompact` — and default to
+`PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, and `PreCompact`
+— and default to
native `ai-memory hook --event … --agent kimi-code` commands on local installs
(local spool plus batched delivery, capture-policy v1 enforced); the staged
script bundle under `~/.local/share/ai-memory/hooks/kimi-code/` is the
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index c4462fb6..7cc6ac07 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -622,11 +622,11 @@ ai-memory install-hooks --agent kimi-code --apply \
--server-url "http://homelab:49374" --auth-token "$TOKEN"
```
-The installed entries cover 9 events — `SessionStart`, `SessionEnd`,
-`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`,
-`SubagentStop`, and `PreCompact` — with a Kimi Code-specific script bundle /
-native `ai-memory hook --event … --agent kimi-code` commands (native is the
-default for local installs; the staged scripts under
+The installed entries cover 10 events — `SessionStart`, `SessionEnd`,
+`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`,
+`SubagentStart`, `SubagentStop`, and `PreCompact` — with a Kimi Code-specific
+script bundle / native `ai-memory hook --event … --agent kimi-code` commands
+(native is the default for local installs; the staged scripts under
`~/.local/share/ai-memory/hooks/kimi-code/` are the compatibility fallback).
Capture is fire-and-forget; a pending handoff is injected at `SessionStart`
via the hook's stdout (Kimi Code appends stdout to context on exit 0), the
@@ -642,8 +642,10 @@ same pattern as Gemini CLI.
(seconds, 1-600, default 30). Any extra field makes Kimi Code fail to load
the entire `config.toml`, so prefer `install-hooks --apply` over hand
edits.
-- Kimi Code runs rules with an identical `command` only once; ai-memory's
- entries use a distinct command per event, so all 9 fire independently.
+- Kimi Code runs identical commands only once when multiple rules match the
+ same event. `PostToolUse` and `PostToolUseFailure` reuse one handler command,
+ but are mutually exclusive event triggers, so successful and failed calls
+ are both captured once.
## OpenClaw