Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'main' of https://github.com/akitaonrails/ai-memory into feat/kimi-code-support
Lucas Oliveiraa817fcf09ea7
diff --cc AGENTS.mdindex 5dbe8081,7fa8fb5a..9c55d453--- a/AGENTS.md+++ b/AGENTS.md@@@ -36,8 -36,8 +36,8 @@@ install or refresh workIf you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and- AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Kimi Code,-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI, but if the project-says one file is canonical, use that file.++AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code,+but if the project says one file is canonical, use that file.If the rule is a standing *user/team* preference that should apply toevery project (tech choices, code style, personal conventions), save it@@@ -53,8 -53,8 +53,9 @@@ latest binary's recommended copy- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / Cursor / Gemini / Kimi Code -> `AGENTS.md`), uses its Write /- Edit tool to replace or append the returned `markered_block` while preserving- OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`), uses its Write / Edit tool- to replace or append the returned `markered_block` while preserving++ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code -> `AGENTS.md`),++ uses its Write / Edit tool to replace or append the returned++ `markered_block` while preservingnon-ai-memory user content, then writes or updates each returned`managed_skills` item under the selected skill root from `target_hints`using its `relative_path`.diff --cc CHANGELOG.mdindex f58b0bd2,fa435077..ea432a7a--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -8,20 -8,31 +8,43 @@@ and this project adheres to [Semantic V## [Unreleased]### Added+- Kimi Code CLI is now a supported MCP + lifecycle-hook integration+ (`--client kimi-code` / `--agent kimi-code`, alias `kimi`). `install-mcp`+ merges an `mcpServers` entry into `~/.kimi-code/mcp.json` with a plain `url`+ (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`.+ 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.+ - Grok Build CLI is now a first-class MCP client as well as a hook agent:+ `install-mcp --client grok` renders and `--apply` merges a native HTTP+ entry into `$GROK_HOME/config.toml` (default `~/.grok/config.toml`)+ (`[mcp_servers.ai-memory]` with+ `url` / `enabled` / `[mcp_servers.ai-memory.headers]` — not Codex's+ `http_headers` key). `install-hooks --agent grok` reuses that entry to+ infer server URL and bearer token; `uninstall` strips the MCP table;+ `setup-agent --agent grok` prints the companion `install-mcp` tip.+ Managed routing skills can target `.grok/skills` / `$GROK_HOME/skills`+ (default `~/.grok/skills`) via+ `install-skills --agent grok` and `memory_install_self_routing`+ `target_hints`. Lifecycle capture was already present; handoff injection+ remains unavailable because Grok ignores SessionStart stdout — recover+ via MCP `memory_handoff_accept`.### Changed+ - `install-hooks --agent devin` now infers the server URL and bearer token from+ `~/.devin/config.json` when flags and environment settings are absent, keeping+ hooks aligned with an existing Devin MCP registration.+ - Grok routing guidance now treats Grok Build CLI as an AGENTS-based client and+ directs its managed skills to `.grok/skills` or `$GROK_HOME/skills` (default+ `~/.grok/skills`). The MCP self-routing payload and installed prompt surface+ now guard those targets;+ Grok (like Zero) still resumes handoffs through `memory_handoff_accept`+ because it ignores SessionStart stdout.- One-shot client commands (`rename-project`, `status`, `write-page`, …) nolonger print the "cannot write log files … falling back" warning when thelog directory is unwritable — they still degrade to temp/stderr loggingdiff --cc README.mdindex ee9c84d6,18f1b218..10af4974--- a/README.md+++ b/README.md@@@ -33,9 -33,8 +33,9 @@@| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |- | Grok Build CLI | Hooks | Lifecycle hooks via `install-hooks --agent grok` (`~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle, native `--agent grok`). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |+ | 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. || 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. |@@@ -271,8 -271,8 +272,8 @@@ docker run -d --name ai-memory# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts + auto-detecting ~/.claude/settings.json. Re-run with# `--agent codex`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,- # `--agent kimi-code`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,- # `--client gemini-cli`, etc.-# `--agent grok`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,++# `--agent grok`, `--agent kimi-code`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,+ # `--client gemini-cli`, `--client grok`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --applyai-memory install-hooks --agent claude-code --applydiff --cc crates/ai-memory-cli/src/cli.rsindex 8429d472,4a60faa8..6bdaf9f2--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@@ -937,9 -936,12 +940,15 @@@ pub enum McpClientZero,/// Devin CLI — `~/.devin/config.json`.Devin,+ /// xAI Grok Build CLI — `~/.grok/config.toml` under+ /// `[mcp_servers.<name>]` with native HTTP `url` + `headers`.+ /// Pair with `install-hooks --agent grok` for lifecycle capture.+ /// Grok ignores SessionStart stdout, so handoffs are recovered via+ /// MCP `memory_handoff_accept` rather than hook injection.+ Grok,+ /// Kimi Code CLI (Moonshot AI).+ #[value(alias = "kimi")]+ KimiCode,/// VS Code GitHub Copilot (agent mode) — per-workspace/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers/// from VS Code's own MCP framework (top-level `servers` key),diff --cc crates/ai-memory-cli/src/commands/install_hooks.rsindex 9244a48e,a89043a9..8cbe2004--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@@ -391,32 -358,77 +389,82 @@@ fn apply_base_path_to_hook_url(url: &st}}- fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {- let client = mcp_client_for_agent(agent)?;- let path = install_mcp::mcp_config_path(client).ok()?;- let content = fs::read_to_string(path).ok()?;- match client {- McpClient::ClaudeCode => {- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url")- }- McpClient::Codex => infer_codex_mcp_config(&content),- McpClient::OpenCode => infer_json_mcp_config(&content, &["mcp", "ai-memory"], "url"),- McpClient::Cursor => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),- McpClient::GeminiCli => {- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "httpUrl")- }- McpClient::Openclaw => {- infer_json_mcp_config(&content, &["mcp", "servers", "ai-memory"], "url")- }- McpClient::Omp => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),- McpClient::Zero => infer_json_mcp_config(&content, &["mcp", "servers", "ai-memory"], "url"),- McpClient::Pi => None,- McpClient::AntigravityCli => {- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "serverUrl")+ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpConfig>> {+ if agent == AgentChoice::Grok {+ let cwd = std::env::current_dir()+ .context("could not resolve current dir for Grok project configuration")?;+ let repo_root = ai_memory_consolidate::discover_repo_root(&cwd).ok();+ if let Some(project_config) = find_grok_project_overlay(&cwd, repo_root.as_deref()) {+ anyhow::bail!(+ "Grok project configuration {} may override GROK_HOME; pass explicit --server-url and --auth-token rather than inferring MCP settings",+ project_config.display()+ );}- McpClient::Devin => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),- McpClient::KimiCode => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),- McpClient::ClaudeDesktop => None,+ }+ let Some(client) = mcp_client_for_agent(agent) else {+ return Ok(None);+ };+ let path = install_mcp::mcp_config_path(client)?;+ let Ok(content) = fs::read_to_string(path) else {+ return Ok(None);+ };+ match client {+ McpClient::ClaudeCode => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "url",+ )),+ // Codex uses `http_headers`; Grok uses `headers`. The shared TOML+ // inferencer accepts both.+ McpClient::Codex => Ok(infer_toml_mcp_config(&content)),+ McpClient::Grok => infer_grok_mcp_config(&content),+ McpClient::OpenCode => Ok(infer_json_mcp_config(+ &content,+ &["mcp", "ai-memory"],+ "url",+ )),+ McpClient::Cursor => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "url",+ )),+ McpClient::GeminiCli => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "httpUrl",+ )),+ McpClient::Openclaw => Ok(infer_json_mcp_config(+ &content,+ &["mcp", "servers", "ai-memory"],+ "url",+ )),+ McpClient::Omp => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "url",+ )),+ McpClient::Zero => Ok(infer_json_mcp_config(+ &content,+ &["mcp", "servers", "ai-memory"],+ "url",+ )),+ McpClient::Pi => Ok(None),+ McpClient::AntigravityCli => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "serverUrl",+ )),+ McpClient::Devin => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory"],+ "url",+ )),++ McpClient::KimiCode => Ok(infer_json_mcp_config(++ &content,++ &["mcpServers", "ai-memory"],++ "url",++ )),+ McpClient::ClaudeDesktop => Ok(None),// MCP-only client: no AgentChoice counterpart routes here.// Reachable only if a future install_hooks flow targets VS// Code Copilot directly.@@@ -437,10 -482,11 +518,12 @@@ fn mcp_client_for_agent(agent: AgentChoAgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),AgentChoice::Zero => Some(McpClient::Zero),+ AgentChoice::Grok => Some(McpClient::Grok),+ AgentChoice::Devin => Some(McpClient::Devin),+ AgentChoice::KimiCode => Some(McpClient::KimiCode),- // Grok and Devin manage their own MCP config under ~/.grok/ and ~/.devin/;- // we don't auto-infer a hook server URL from it.- AgentChoice::Pi | AgentChoice::Grok | AgentChoice::Devin => None,+ // Pi bridges MCP through its generated extension, not a native+ // mcp.json the installer can scrape.+ AgentChoice::Pi => None,}}diff --cc crates/ai-memory-cli/src/commands/install_mcp.rsindex b9ca4813,f6a8112e..e2ae4fdf--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@@ -182,18 -181,17 +186,29 @@@ pub(crate) fn mcp_config_path(client: c})}+/// Kimi Code's data dir: `$KIMI_CODE_HOME` when set (non-empty), else+/// `~/.kimi-code`. The env value comes in as a parameter so tests can+/// exercise both branches without mutating process env.+fn kimi_code_home(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {+ if let Some(dir) = env_override.filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(dir));+ }+ Ok(home_dir()+ .context("could not locate $HOME for config-file auto-detect")?+ .join(".kimi-code"))+}++ /// Resolve Grok Build CLI's user configuration root. Grok honours+ /// `GROK_HOME`; otherwise it uses `~/.grok`.+ pub(crate) fn grok_home() -> Result<PathBuf> {+ if let Some(path) = std::env::var_os("GROK_HOME").filter(|path| !path.is_empty()) {+ return Ok(PathBuf::from(path));+ }+ Ok(home_dir()+ .context("could not locate $HOME for Grok configuration")?+ .join(".grok"))+ }+/// Resolve the user-config file for this client. Honours/// `--config-file` when provided, else uses the canonical default/// per client.diff --cc crates/ai-memory-cli/src/commands/setup_agent.rsindex 32f22137,2b21231a..312af3c2--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@@ -35,10 -35,11 +35,11 @@@ use std::path::{Path, PathBuf}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, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, build_claude_code_payload, build_devin_payload, build_grok_payload,- hook_script_for_current_platform,+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CLAUDE_CODE_EVENTS, CODEX_PROFILE,+ CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_devin_payload,+ build_grok_payload, hook_script_for_current_platform,};use crate::config::{Config, DEFAULT_SERVER_URL};diff --cc crates/ai-memory-core/src/routing_snippet.rsindex 56c73008,9acaf42c..0c02fe62--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@@ -64,8 -64,8 +64,8 @@@ install or refresh workIf you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and- AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Kimi Code,-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI, but if the project-says one file is canonical, use that file.++AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code,+but if the project says one file is canonical, use that file.If the rule is a standing *user/team* preference that should apply toevery project (tech choices, code style, personal conventions), save it@@@ -81,8 -81,8 +81,9 @@@ latest binary's recommended copy- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / Cursor / Gemini / Kimi Code -> `AGENTS.md`), uses its Write /- Edit tool to replace or append the returned `markered_block` while preserving- OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`), uses its Write / Edit tool- to replace or append the returned `markered_block` while preserving++ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code -> `AGENTS.md`),++ uses its Write / Edit tool to replace or append the returned++ `markered_block` while preservingnon-ai-memory user content, then writes or updates each returned`managed_skills` item under the selected skill root from `target_hints`using its `relative_path`.diff --cc crates/ai-memory-mcp/src/server.rsindex 5cb0bb30,d45d0a12..c618c81c--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -2453,7 -2453,7 +2453,8 @@@ impl AiMemoryServer"antigravity_cli": "AGENTS.md","zero": "AGENTS.md","devin": "AGENTS.md",+ "kimi_code": "AGENTS.md",+ "grok": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,diff --cc docs/install.mdindex 3eb036d1,8398ffce..341a9f12--- a/docs/install.md+++ b/docs/install.md@@@ -563,38 -563,11 +563,39 @@@ differencesThe `SessionStart` hook injects pending handoffs through Devin's`hookSpecificOutput.additionalContext`. Real Devin `SessionStart` and- `PostToolUse` payloads may omit `session_id` and `cwd`; ai-memory derives stable- session/cwd context from its hook state and process environment so those events- are still captured.+ `PostToolUse` payloads may omit `session_id` and `cwd`; ai-memory now infers cwd+ from `DEVIN_PROJECT_DIR` or the hook process working directory when the payload+ omits it, and mints/reuses a per-host session id from hook state when necessary,+ so those events are still captured. A payload-provided value always wins.+### Kimi Code++Kimi Code keeps MCP servers in `~/.kimi-code/mcp.json` and lifecycle hooks in+`~/.kimi-code/config.toml`; both move together when `$KIMI_CODE_HOME` is set.+The CLI also accepts `--agent kimi` as an alias.++```bash+ai-memory install-mcp --client kimi-code --apply \+ --server-url "http://homelab:49374/mcp" \+ --auth-token "$TOKEN"++ai-memory install-hooks --agent kimi-code --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"+```++`install-hooks` merges `[[hooks]]` entries into `config.toml`, preserving the+provider/model settings the same file holds, and stages the hook scripts under+`~/.local/share/ai-memory/hooks/kimi-code/`. Capture covers 9 events —+`SessionStart`, `SessionEnd`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,+`Stop`, `SubagentStart`, `SubagentStop`, and `PreCompact` — as fire-and-forget+POSTs to `/hook`. A pending handoff is injected at `SessionStart` through the+hook's stdout, which Kimi Code appends to the model context.++Kimi Code hook entries accept only `event`, `matcher`, `command`, and+`timeout`; extra fields make the whole `config.toml` fail to load, so prefer+`install-hooks --apply` over hand edits.+### OpenCode```bashdiff --cc docs/usage.mdindex aedb4cd2,4f070322..675cb153--- a/docs/usage.md+++ b/docs/usage.md@@@ -290,7 -292,7 +295,7 @@@ docker exec ai-memory git -C /data/wikDurable project rules belong in the agent's rules file, not only in thewiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,- Cursor, Kimi Code, and Gemini CLI it is usually `AGENTS.md`.-Cursor, Gemini CLI, and Grok Build CLI it is usually `AGENTS.md`.++Cursor, Gemini CLI, Grok Build CLI, and Kimi Code it is usually `AGENTS.md`.The consolidator classifies compiled observations as `decision`,`fact`, `rule`, or `gotcha`. Rule-tagged pages are routed to