Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(plugins): add Kimi Code CLI memory plugin (#4787)

梧桐雨03391bae4335
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index fd104f798..94d849d28 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -66,6 +66,6 @@ The same settings can live in `~/.openviking/ovcli.conf`:
Environment variables take precedence over `ovcli.conf`. Restart the Agent after changing these settings so its hook processes reload the configuration. These are plugin-client settings; the server's `ov.conf` does not need to change.
-The `plugin` section is read by every memory plugin — claude-code, codex, cursor, trae, trae-cn, zcode, opencode, dsh and pi — and a `plugin.<harness>` object overrides the shared keys for one of them, under either spelling (`claude_code` or `claude-code`, `trae_cn` or `trae-cn`). Compression is the exception: the other harnesses honour `recallQueryExpansion` but ignore `recallCompress` and its companions, since none of them requests a server digest.
+The `plugin` section is read by every memory plugin — claude-code, codex, cursor, trae, trae-cn, zcode, kimicode, opencode, dsh and pi — and a `plugin.<harness>` object overrides the shared keys for one of them, under either spelling (`claude_code` or `claude-code`, `trae_cn` or `trae-cn`). Compression is the exception: the other harnesses honour `recallQueryExpansion` but ignore `recallCompress` and its companions, since none of them requests a server digest.
A context request waits longer than an ordinary request, because aborting it client-side discards the whole response rather than just the stage that ran long. The server pipeline is serial and each optional stage has its own fuse: query expansion (`retrieval.recall_intent_timeout_s`, 5s) runs first, then retrieval, body reads and budgeting, and only then the digest rewrite (`retrieval.recall_rewrite_timeout_s`, 30s). The deadline therefore follows what the request actually asks for — 15s once it carries a session and can spend the expansion fuse, 45s when it also asks for a digest, and the plugin's ordinary timeout when it asks for neither. Set `OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS` (or `plugin.recallContextTimeoutMs`) to pin it — keep it above the fuses the request will spend and below the Agent's own hook timeout.
diff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.md
index ce8e4165c..37e7a1560 100644
--- a/docs/en/agent-integrations/08-community-plugins.md
+++ b/docs/en/agent-integrations/08-community-plugins.md
@@ -47,6 +47,44 @@ After restarting ZCode, verify that:
Implementation details and currently verified ZCode assumptions are documented in the plugin's [README](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin) and [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md).
+## Kimi Code memory integration
+
+Source: [examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
+
+The Kimi Code integration is a native managed plugin. It reuses the shared
+OpenViking hook runtime and adds only Kimi-specific event mapping, wire
+transcript decoding, output formatting, and commit policy:
+
+- **UserPromptSubmit** recalls memory and prints raw context text for Kimi to inject.
+- **PreToolUse** blocks direct Read/Glob/Grep access to `viking://` URIs.
+- **Stop**, **PreCompact**, and **SessionEnd** capture new `wire.jsonl` turns; **Interrupt** runs the same capture synchronously within one two-second OpenViking request budget.
+- The plugin manifest exposes the OpenViking MCP server without editing Kimi's legacy config files.
+
+### Install
+
+Prerequisites: Node.js 18+, a running OpenViking server, and Kimi Code CLI.
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
+ --harness kimicode
+```
+
+Use the TOS mirror where GitHub is unavailable:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+ --harness kimicode --dist tos
+```
+
+The installer assembles a self-contained runtime under
+`$KIMI_CODE_HOME/plugins/managed/openviking-memory/` (default Kimi home:
+`~/.kimi-code/`), then updates only the `openviking-memory` entry in
+`plugins/installed.json`. Existing plugin records are preserved. Re-run the
+same command to upgrade, or add `--uninstall` to remove only this plugin.
+
+The verified host contract and version are recorded in
+[`hosts/kimicode/DESIGN.md`](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/hosts/kimicode/DESIGN.md).
+
## AstrBot plugin
[AstrBot](https://github.com/AstrBotDevs/AstrBot) is a multi-platform IM bot framework supporting QQ, Telegram, Discord, Lark, and 20+ other platforms.
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index f9999f605..d4a2b315d 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -21,7 +21,7 @@
## 1.1 Active tool surface (agentic calls)
-- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode, dsh, pi) share an identical active tool surface comprising 16 tools.** The server centrally defines these tools. The plugins read `~/.openviking/ovcli.conf` and connect to the server-defined MCP tools. pi uses the official MCP client inside its extension and registers the discovered tools as native pi tools.
+- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, kimicode, opencode, dsh, pi) share an identical active tool surface comprising 16 tools.** The server centrally defines these tools. The plugins read `~/.openviking/ovcli.conf` and connect to the server-defined MCP tools. pi uses the official MCP client inside its extension and registers the discovered tools as native pi tools.
- `trae-cli` means TraeCode CLI 2.0 (2.0 only). It is installed via a `codex` plugin alias and maintains format compatibility with `codex`. Therefore, it is consolidated into the `codex` row in the matrices below.
@@ -32,6 +32,7 @@
| cursor | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| trae / trae-cn | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| zcode | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| kimicode | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| opencode | MCP passthrough (host adds an `openviking_` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| dsh | MCP passthrough (`@deepseek-ai/dsh-mcp-client` → the shared stdio proxy; host adds an `mcp__openviking__` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| pi | MCP mirror (official client; extension adds an `openviking_` prefix) | 16, i.e. whatever `tools/list` returns (registration has preconditions³) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
@@ -55,6 +56,7 @@
| cursor | 6 hooks + MCP proxy + rule + skill | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) | ❌ | ✅ | ❌ |
| trae / trae-cn | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) | ❌ | ✅ | ❌ |
| zcode | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) | ❌ | ✅ | ❌ |
+| kimicode | 7 native plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), first successful prompt load | ❌ (PreCompact only captures/commits) | ✅ | ❌ |
| opencode | 8 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) + repo list into the system prompt | ❌ (commits once before and once after compacting) | ✅ | ❌ (toast instead) |
| dsh | native Cordis plugin (same process) + MCP proxy + skill | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), once per session | ❌ | ✅ | ❌ |
| pi | native extension (9 events) | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), rebuilt into systemPrompt every turn | ✅ **takeover** (on by default) | ✅ | ✅ |
@@ -71,7 +73,7 @@ In the profile injection column, the first number is the default `profileTokenBu
## 1.3 Grouping by form
- **Full suite** (hook automation + MCP tool surface + surrounding UX): claude-code and codex (`trae-cli` is installed via an alias and is included here).
-- **Thin hook** (sharing `agent-hook-runtime`, meaning core behaviors are essentially identical, with differences limited to host events and thresholds): cursor, trae/trae-cn, and zcode.
+- **Thin hook** (sharing `agent-hook-runtime`, meaning core behaviors are essentially identical, with differences limited to host events, transcript decoding, and thresholds): cursor, trae/trae-cn, zcode, and kimicode.
- **Plugin event**: opencode (offers the richest host event surface; `dispose` handles shutdown).
- **Native in-process**: dsh (Cordis), pi (extension + compaction takeover), openclaw (full ContextEngine takeover), and hermes (MemoryProvider).
- **Tool**: ov CLI (all operations are explicit calls; no automatic background actions).
@@ -172,6 +174,7 @@ Core modules at a glance (detailed further in the per-dimension sections):
| cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌ (shares the installer TUI) |
| trae / trae-cn | Config-driven (`~/.trae{,-cn}/hooks.json` + platform-specific mcp.json) | One-line `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |
| zcode | Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) | One-line `--harness zcode` | `zc-<sess_…>` | env + ovcli.conf `plugin.zcode` | ❌ |
+| kimicode | Native Kimi Code plugin (`kimi.plugin.json`, managed copy + `installed.json`) | One-line `--harness kimicode` | `kc-<session_id>` | env + ovcli.conf `plugin.kimicode` + workspace files | ❌ |
| opencode | npm plugin `@openviking/opencode-plugin` (its config hook dynamically injects the MCP entry) | One-line `--harness opencode` (uses npm registration with a proxy snapshot fallback) / manual npm / from source | `oc-<id>`; subagents use `oc-<parent>__subagent-<child>` | env + ovcli.conf `plugin.opencode` | ✅ |
| dsh | In-process Cordis plugin (`cordis.patch.yml` plugin group) | Unified installer (asks for the profile, default `web`), or `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id as-is>`; each subagent is assigned its own session | env + ovcli.conf `plugin.dsh` + the cordis patch config, which is the lowest behavior layer (credentials still come from the patch first) | ❌ |
| pi | Native pi extension (loaded from a directory, with TypeScript transpiled on the fly via jiti) | One-line `--harness pi` (copied into the auto-discovery directory, no `pi install` needed) | `pi-<piSessionId>` | env + ovcli.conf `plugin.pi` (credential fields are resolved via the shared credential chain) | ✅ |
@@ -181,13 +184,13 @@ Core modules at a glance (detailed further in the per-dimension sections):
### 3.1.2 Unified installer
-The unified install script (`examples/memory-plugin-shared/install.sh`) supports ten harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`. (Note that `openclaw` uses its own distribution channel, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:
+The unified install script (`examples/memory-plugin-shared/install.sh`) supports eleven harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, opencode, pi, dsh`. (Note that `openclaw` uses its own distribution channel, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:
- **Interactive prompts:** Two distributions (`--dist github|tos`) and three sources (`--source remote|archive|dev`) are available. When executed via `bash <(curl …)`, it reads input directly from `/dev/tty` to ensure prompts remain interactive.
- **Usage:** In the official documentation, the canonical one-line command omits the `--harness` flag, which launches a TUI multi-select menu. However, the setup-helper forwarding scripts bundled with each plugin append the `--harness` flag automatically.
- **Idempotent merging:** Hooks and MCP entries are identified by the `OPENVIKING_INTEGRATION_ID` marker. This ensures stale entries are pruned and new ones are appended without affecting third-party configurations. Writes are atomic: the script creates a `.bak` backup, writes to a temporary file, and then renames it over the target with `0600` permissions.
- **Credential wizard:** This writes to `~/.openviking/ovcli.conf`. Users can select from three targets (local `http://127.0.0.1:1933` / Volcengine Cloud `https://api.vikingdb.cn-beijing.volces.com/openviking` / custom). If a configuration already exists, the script displays the current values first and asks whether to keep or reconfigure them, masking the API key for security.
-- **Uninstallation:** The `--uninstall` flag covers `cursor`, `trae`, `trae-cn`, and `zcode`, and also cleans up any legacy trae-cli hook config. The Codex-format and host-managed plugins (`claude`, `codex`, `trae-cli`, `opencode`, and `pi`) are removed via their respective host's plugin management systems.
+- **Uninstallation:** The `--uninstall` flag covers `cursor`, `trae`, `trae-cn`, `zcode`, and `kimicode`, and also cleans up any legacy trae-cli hook config. The other Codex-format and host-managed plugins are removed via their respective host's plugin management systems.
- **Post-installation self-check:** This includes grepping the configuration, running `node --check`, and executing a smoke test with `OPENVIKING_MEMORY_ENABLED=0`.
- **Node.js requirement:** The installer enforces a minimum version of Node 18+.
@@ -539,7 +542,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## claude-code
- **Integration docs**: [Claude Code Memory Plugin](./02-claude-code.md)
-- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 16 tools), a slash command, a statusline, and 4 skills (`openviking-memory`, `openviking-skills`, `ov-experience-memory`, `ov-memory-doctor`). Version 0.6.0.
+- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 16 tools), a slash command, a statusline, and 4 skills (`openviking-memory`, `openviking-skills`, `ov-experience-memory`, `ov-memory-doctor`). Version 0.6.1.
- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep|Edit|Write|Bash` (5s, `uri-guard`: denies a file tool whose path is a `viking://` URI, pointing a Write/Edit on a skill URI to `add_skill`, and adds a notice to a Bash command that carries one) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: The session ID format is `cc-<raw_CC_session_id>`, while subagents use `…__subagent-<agent_id>`. `Stop` commits at a threshold of 20000 (keep 10), and `PreCompact` commits synchronously. Automatic recall excludes resources ([§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)). The incremental cursor is stored in `/tmp` (if cleared by the system, the entire session is pushed again).
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 70 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.
@@ -548,7 +551,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## codex
- **Integration docs**: [Codex Memory Plugin](./04-codex.md)
-- **Form**: A Codex plugin (marketplace). Features 6 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s / `PreToolUse:Bash` 5s), an MCP proxy, and the same 4 skills as claude-code. Version 0.10.0.
+- **Form**: A Codex plugin (marketplace). Features 6 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s / `PreToolUse:Bash` 5s), an MCP proxy, and the same 4 skills as claude-code. Version 0.10.1.
- **Capability highlights**: A local recall-compression pipeline (`codex exec`, [§3.2.5](#_3-2-5-recall-digest)). `SessionEnd` (Codex ≥ 0.145) commits the session on a graceful exit, catching up any turns `Stop` missed, and a `SessionStart` fallback sweep reclaims messages left unarchived by exits that never fired it ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). `PreToolUse:Bash` (`uri-guard`) lets a shell command that carries a `viking://` URI run and adds a notice suggesting the OpenViking MCP tools. Codex edits files through `apply_patch`, whose input has no path argument, so the guard never denies a call.
- **Behavior notes**: The session ID format is `cx-<safeId>` (derived deterministically without reading state). `SessionEnd` fires only on a graceful exit and only on Codex 0.145+, so signals, crashes, older builds and `codex app-server` deferral fall to the sweep. Has no on-disk pending queue (while offline, the cursor simply doesn't advance, and the next turn resends to compensate, [§3.3.4](#_3-3-4-pending-queue-offline-compensation-comparison)). Idle-TTL is 1800000ms, lock wait 120000ms (configured via env). `Stop` and `SessionEnd` detach by default (the `appended N turn(s)` notice is hidden by default); a per-session mkdir lock serializes the Stop worker, PreCompact, the SessionEnd worker and the sweep. A newly registered hook has no Codex trust record, so after an upgrade `/hooks` must approve each hook the upgrade added (`SessionEnd`, `PreToolUse`).
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.codex`), and `ov.conf` (`codex`). Hooks authenticate with `Authorization: Bearer` alone ([§3.1.3](#_3-1-3-credential-systems)).
@@ -565,7 +568,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## cursor
- **Integration docs**: [Cursor Memory Integration](./12-cursor.md)
-- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and 2 skills (`openviking-memory`, `openviking-skills`). Includes 6 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring). Version 0.4.0.
+- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and 2 skills (`openviking-memory`, `openviking-skills`). Includes 6 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring). Version 0.5.0.
- **Capability highlights**: Features a `uri-guard` on `beforeReadFile` (independent of the plugin toggle) that denies reading a `viking://` path. Shell commands are not checked, and an upgrade removes the `beforeShellExecution` entry an older install registered. The rule and both skills are installed alongside it.
- **Behavior notes**: The session ID format is `cu-<conversation_id>`. `stop` commits every 8 messages (`commitTurnThreshold=8`, counted in messages, keep 0). `sessionEnd` only fires on `window_close`. By then, the host has already destroyed the shell-exec host, so it practically never runs ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) — sessions ending below the 8-message watermark leave their tail to be archived by a later message in the same session ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the server is unreachable, every turn waits out the full 15s recall timeout.
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.cursor`), and the workspace files ([§3.1.4](#_3-1-4-configuration-layers)).
@@ -573,7 +576,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## trae / trae-cn (IDE editions)
- **Integration docs**: [TRAE Memory Integration](./13-trae.md)
-- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). `PreToolUse` denies Read/Glob/Grep calls whose path is a `viking://` URI, while a Bash/RunCommand command that carries one runs with a notice attached. The shared library is introduced via relative imports, and the MCP server is named `openviking`. Version 0.4.0.
+- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). `PreToolUse` denies Read/Glob/Grep calls whose path is a `viking://` URI, while a Bash/RunCommand command that carries one runs with a notice attached. The shared library is introduced via relative imports, and the MCP server is named `openviking`. Version 0.5.0.
- **Capability highlights**: Features the simplest and most direct behavior of the group. Every Stop that carries content is committed (keep 0). Consequently, upon shutdown, the largest possible backlog is merely the last in-flight turn ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: trae and trae-cn differ only in their session ID prefixes (`tr-` vs. `trcn-`) and installation paths. The same workload lands in two separate sets of sessions across the two clients, and cross-client sharing occurs via the server-side memory space after extraction rather than by reusing sessions. Note that there is no handling for PreCompact, status lines, skills, or subagents.
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.trae` / `plugin.trae_cn`), and the workspace files.
@@ -582,16 +585,25 @@ Each card serves as a quick-reference entry point. It records only the facts and
## zcode
- **Integration docs**: [Community Integrations → ZCode](./08-community-plugins.md)
-- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors nothing: the installer assembles its shared runtime the same way it does for cursor and trae. Version 0.4.0.
+- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors nothing: the installer assembles its shared runtime the same way it does for cursor and trae. Version 0.5.0.
- **Capability highlights**: The rollout file `~/.zcode/cli/rollout/model-io-<sid>.jsonl` serves as the source of truth for increments (a `lastTurnId` diff backfills any missed Stop events). Stop detaches by default, meaning Ctrl+C does not result in lost writes.
- **Behavior notes**: Commits on every Stop (keep 0). The capture path only strips the three types of injection blocks without performing any further text cleanup ([§3.2.6](#_3-2-6-injection-backflow-protection)). The initial capture reads the entire rollout at once, meaning that installing it into a long-running session will produce a single large push.
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.zcode`), and the workspace files; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).
+## kimicode
+
+- **Integration docs**: [Community Integrations → Kimi Code](./08-community-plugins.md)
+- **Form**: Native managed plugin with 7 hooks and an MCP proxy. The installer assembles one self-contained copy under `$KIMI_CODE_HOME/plugins/managed/openviking-memory`; no shared runtime is committed for Kimi. Version 0.5.0; verified with Kimi Code CLI 0.43.1.
+- **Capability highlights**: `wire.jsonl` provides stable incremental turns. Profile injection retries on prompt hooks until successful. Stop, PreCompact, and SessionEnd may detach; Interrupt stays synchronous with one two-second OpenViking request budget.
+- **Behavior notes**: UserPromptSubmit emits raw context text, not a JSON string. A turn advances the cursor only after send or durable queueing. Installation preserves unrelated plugin records and does not edit legacy `config.toml` or `mcp.json`.
+- **Configuration**: Environment variables, `ovcli.conf` (`plugin.kimicode`), and workspace files.
+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).
+
## opencode
- **Integration docs**: [OpenCode Plugin](./10-opencode.md)
-- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 8 plugin hooks: config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. `tool.execute.before` denies read/glob/grep calls whose path is a `viking://` URI, and `tool.execute.after` appends a notice to the output of a bash command that carries one. Version 0.3.3.
+- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 8 plugin hooks: config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. `tool.execute.before` denies read/glob/grep calls whose path is a `viking://` URI, and `tool.execute.after` appends a notice to the output of a bash command that carries one. Version 0.4.1.
- **Capability highlights**: The `dispose` hook covers all four standard shutdown paths (on hosts ≥1.15.11). The repository list is injected into the system prompt ([§3.2.3](#_3-2-3-profile-opening-injection)). It boasts the richest host event surface of any integration, with `session.idle`, `compacted`, `deleted`, and `error` each carrying their own specific semantics.
- **Behavior notes**: Features a `commitTokenThreshold` of 20000 (positive values only; 0 falls back to the default) and a commit timeout of 30000ms. A single host compaction equates to two commits. Within the `dispose` hook's 5-second host budget, a slow commit spanning several sessions might be cut short, and the pending queue does not cover this scenario ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). On host versions below 1.15.11, the `dispose` hook is unavailable, meaning shutdowns do not trigger a commit. Leftover sessions are not flushed upon restart. The opening injection is attempted once per session ([§3.2.3](#_3-2-3-profile-opening-injection)). Finally, directory matching in `bypassSessionPatterns` does not apply to opencode, as the input does not carry a current working directory (cwd).
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.opencode`), and the workspace files.
@@ -599,7 +611,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## dsh (DeepSeek Harness)
-- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). Its tool surface is the server's MCP surface, mounted through `@deepseek-ai/dsh-mcp-client` and the shared stdio proxy (published as `mcp__openviking__*`), while its hooks call REST directly. It features 6 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush / tools/pre-execute / tools/post-execute. Version 0.5.0.
+- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). Its tool surface is the server's MCP surface, mounted through `@deepseek-ai/dsh-mcp-client` and the shared stdio proxy (published as `mcp__openviking__*`), while its hooks call REST directly. It features 6 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush / tools/pre-execute / tools/post-execute. Version 0.5.1.
- **Capability highlights**: `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it. Pre-step injection is transmitted as a user message, aligning with the `complete:true` rendering mode of the DSH persona.
- **Behavior notes**: The unified installer covers dsh and asks which profile to install into (default `web`, overridable with `--dsh-profile`); npm is the bundle's only distribution channel, so the github/tos choice does not apply and every mode except `dev` installs the published package; `dev` packs the checkout first, because `dsh plugin` forwards to pnpm and a linked source tree cannot resolve the dsh peers the bundle imports. The teardown commit is allocated 3 seconds with no threshold, and it does not trigger on SIGHUP or a consecutive Ctrl+C ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). Compaction remains invisible to the plugin: injected content shrinks alongside the host's compaction, and the profile is not re-injected. Each subagent is assigned its own session ([§3.3.5](#_3-3-5-subagent-session-comparison)). The tool surface is the server's own MCP surface, reached through the same stdio proxy the other integrations use and published under `mcp__openviking__*`, so a server upgrade adds tools without a bundle release; the trade-off is that the proxy runs once per profile, so tool calls carry a process-level actor peer and `remember` is not session-scoped (recall, capture, and commit still resolve a peer per session). The bundle also ships the shared `openviking-memory` and `openviking-skills` skills. `uri-guard` lowercases tool names before matching: `tools/pre-execute` denies a file tool whose path is a `viking://` URI (a write or edit on a skill URI is pointed to `mcp__openviking__add_skill`), and `tools/post-execute` adds a notice (`form: "notice"`) when a `bash` command carries one.
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.dsh`), the workspace files, and the cordis patch, which is the lowest layer for behavior knobs. Credentials are the exception: an endpoint, key, account, user, or peer named in the patch overrides the credential chain.
@@ -608,7 +620,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## pi (pi Coding Agent Extension)
- **Integration docs**: [pi Coding Agent Extension](./11-pi.md)
-- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). The extension uses the official MCP client and republishes every descriptor from the server's `tools/list` as a pi tool named `openviking_<tool>`: 16 today ([§2.1](#_2-1-server-side-mcp-tool-surface)). Nothing in the extension enumerates tools, so a server that gains or drops one changes pi's surface at the next session with no plugin release. Recall, session sync, profile injection and takeover still go over REST. It features 9 events + a `/viking` command; `tool_call` blocks read/grep/find/ls/write/edit calls whose path is a `viking://` URI, and `tool_result` appends a notice to the result of a `bash` command that carries one. Version 0.4.0.
+- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). The extension uses the official MCP client and republishes every descriptor from the server's `tools/list` as a pi tool named `openviking_<tool>`: 16 today ([§2.1](#_2-1-server-side-mcp-tool-surface)). Nothing in the extension enumerates tools, so a server that gains or drops one changes pi's surface at the next session with no plugin release. Recall, session sync, profile injection and takeover still go over REST. It features 9 events + a `/viking` command; `tool_call` blocks read/grep/find/ls/write/edit calls whose path is a `viking://` URI, and `tool_result` appends a notice to the result of a `bash` command that carries one. Version 0.4.1.
- **Highlights**: Features takeover compaction (enabled by default, [§3.4.2](#_3-4-2-pi-takeover)). Employs a two-stage recall system: it queues at `before_agent_start` and performs synchronous retrieval during the context event, ensuring the current turn's prompt receives its corresponding memories. It also includes a status line. The `session_shutdown` event triggers across all shutdown paths and is properly awaited.
- **Behavior**: When takeover is enabled, exiting does not trigger a commit. Instead, the handler persists local state, and archiving waits either for the next resumed run to hit the threshold or for a manual `/viking commit` command ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). The takeover threshold is set to 30000 tokens while keeping the last 3 turns (keep 3, which the server interprets as a message count). When takeover is disabled, the threshold is 20000 tokens (keep 10), and exiting triggers an unconditional commit. Tool registration requires `health`, `ensureSession` and a `/mcp` handshake ([§1.1](#_1-1-active-tool-surface-agentic-calls)); a root API key is refused on `/mcp` with a 403, so a credential chain ending at `ov.conf`'s `server.root_api_key` produces a session with no tools — before 0.4.0 the REST tools registered and quietly answered "No results found." instead. `openviking_remember` runs on the MCP surface, meaning its own one-shot session committed immediately rather than a write folded into pi's session ([§2.1](#_2-1-server-side-mcp-tool-surface)). `openviking_add_resource` ingests a remote URL directly; for a local path the server returns an upload instruction whose URL the model has to POST the bytes to with `bash`, as on every other MCP harness. `openviking_read` returns full text only: a directory URI comes back as `Cannot render …: URI points to a directory`, and the old `level="abstract"/"overview"` tiers have no MCP equivalent — use `openviking_search(mode="context", detail="overview")` or `openviking_tree(include_abstract=true)`, while takeover keeps injecting the archive overview itself over REST. A tool call is bounded by the shared `timeoutMs` (15000ms, `OPENVIKING_TIMEOUT_MS`), which a `write`/`edit` with `wait=true` or a synchronous `add_resource` ingest can outlast; a timeout or ESC fails the call locally only, so the request it already sent runs to completion and a write may have landed anyway. Upgrading from 0.3.x renames every tool with no alias period, so a `--tools` / `--exclude-tools` allowlist that pinned `viking_*` has to be rewritten or the tools silently disappear. If takeover is off, resuming via `pi -c` will re-report the entire branch.
- **Config**: Configured via environment variables, `ovcli.conf` (`plugin.pi`), and the workspace files (credentials always pass through the credential chain, [§3.1.3](#_3-1-3-credential-systems)). Bypass goes through the shared `isBypassed` glob matcher under the key `bypassSessionPatterns`; the older `bypassPatterns` still reads. The shared `mcpEnabled: false` now takes effect here as well: no bridge, no tools, and `/viking` reports that as a setting rather than a fault.
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 7cea38c7b..6e9319f57 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -66,6 +66,6 @@ export OPENVIKING_RECALL_COMPRESS=off
环境变量优先于 `ovcli.conf`。修改后重启对应的 Agent,让 hook 进程重新加载配置。上述设置属于插件客户端,不需要修改服务端的 `ov.conf`。
-`plugin` 段由每个记忆插件读取——claude-code、codex、cursor、trae、trae-cn、zcode、opencode、dsh 和 pi;`plugin.<harness>` 对象只覆盖其中某一个 harness 的共享键,两种写法都认(`claude_code` 或 `claude-code`、`trae_cn` 或 `trae-cn`)。压缩是例外:其余 harness 认 `recallQueryExpansion`,但忽略 `recallCompress` 及其配套项——它们都不会请求服务端 digest。
+`plugin` 段由每个记忆插件读取——claude-code、codex、cursor、trae、trae-cn、zcode、kimicode、opencode、dsh 和 pi;`plugin.<harness>` 对象只覆盖其中某一个 harness 的共享键,两种写法都认(`claude_code` 或 `claude-code`、`trae_cn` 或 `trae-cn`)。压缩是例外:其余 harness 认 `recallQueryExpansion`,但忽略 `recallCompress` 及其配套项——它们都不会请求服务端 digest。
context 请求的等待时间比普通请求更长,因为客户端提前中断会丢掉整个响应,而不只是超时的那一段。服务端流水线是串行的,每个可选阶段各有保险丝:先是查询扩展(`retrieval.recall_intent_timeout_s`,5 秒),然后是检索、正文读取和预算规划,最后才是 digest 重写(`retrieval.recall_rewrite_timeout_s`,30 秒)。因此这个上限按请求实际启用的阶段决定——带 session、会走查询扩展时取 15 秒,同时还要 digest 时取 45 秒,两者都不涉及时沿用插件自身的普通超时。可以用 `OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS`(或 `plugin.recallContextTimeoutMs`)指定这个上限,取值应高于该请求会用到的保险丝、低于 Agent 自身的 hook 超时。
diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.md
index 48e187995..202e8019d 100644
--- a/docs/zh/agent-integrations/08-community-plugins.md
+++ b/docs/zh/agent-integrations/08-community-plugins.md
@@ -47,6 +47,41 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
实现细节与当前已验证的 ZCode 假设见插件目录中的 [README](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin) 和 [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md)。
+## Kimi Code 记忆集成
+
+源码:[examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
+
+Kimi Code 集成是原生 managed plugin。它复用 OpenViking 的共享 Hook 运行时,只在适配层保留 Kimi 特有的事件映射、wire transcript 解码、输出格式和 commit 策略:
+
+- **UserPromptSubmit** 召回记忆,并输出 Kimi 可直接注入的原始文本。
+- **PreToolUse** 拒绝 Read/Glob/Grep 直接访问 `viking://` URI。
+- **Stop**、**PreCompact** 和 **SessionEnd** 增量捕获 `wire.jsonl` 回合;**Interrupt** 同步执行同一捕获流程,全部 OpenViking 请求共用 2 秒总预算。
+- 原生插件 manifest 提供 OpenViking MCP server,不修改 Kimi 的旧式配置文件。
+
+### 安装
+
+前置条件:Node.js 18+、正在运行的 OpenViking 服务,以及 Kimi Code CLI。
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
+ --harness kimicode
+```
+
+GitHub 不可用的地区可使用 TOS 镜像:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+ --harness kimicode --dist tos
+```
+
+安装器会在 `$KIMI_CODE_HOME/plugins/managed/openviking-memory/`
+下组装自包含运行时(Kimi home 默认为 `~/.kimi-code/`),并且只更新
+`plugins/installed.json` 中的 `openviking-memory` 记录,不动其他插件。
+重跑同一命令可升级;加上 `--uninstall` 只卸载该插件。
+
+已验证的宿主契约和版本见
+[`hosts/kimicode/DESIGN.md`](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/hosts/kimicode/DESIGN.md)。
+
## AstrBot 插件
[AstrBot](https://github.com/AstrBotDevs/AstrBot) 是一个多平台 IM Bot 框架,支持 QQ、Telegram、Discord、飞书等 20+ 平台。
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 36a6cdec8..3b60abdfa 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -21,7 +21,7 @@
## 1.1 主动工具面(Agentic 调用能力)
-- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode、dsh、pi)的主动工具面完全一致,共 16 个工具**:这些工具由服务端统一定义,各插件读取 `~/.openviking/ovcli.conf` 并连接服务端 MCP 工具;pi 在扩展中使用官方 MCP 客户端,再把发现的工具注册成 pi 原生工具。
+- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、kimicode、opencode、dsh、pi)的主动工具面完全一致,共 16 个工具**:这些工具由服务端统一定义,各插件读取 `~/.openviking/ovcli.conf` 并连接服务端 MCP 工具;pi 在扩展中使用官方 MCP 客户端,再把发现的工具注册成 pi 原生工具。
- trae-cli 指 TraeCode CLI 2.0(仅支持 2.0),经 codex 插件别名安装,插件与 codex 格式兼容,下文矩阵并入 codex 行。
@@ -32,6 +32,7 @@
| cursor | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| trae / trae-cn | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| zcode | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| kimicode | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| opencode | MCP 透传(宿主加 `openviking_` 前缀) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| dsh | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| pi | MCP 镜像(官方客户端;扩展加 `openviking_` 前缀) | 16,即 `tools/list` 返回什么就是什么(注册有前置条件³) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
@@ -55,6 +56,7 @@
| cursor | 6 hook + MCP 代理 + rule + skill | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) | ❌ | ✅ | ❌ |
| trae / trae-cn | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) | ❌ | ✅ | ❌ |
| zcode | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) | ❌ | ✅ | ❌ |
+| kimicode | 7 个原生 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),首次成功 prompt 加载 | ❌(PreCompact 只捕获/commit) | ✅ | ❌ |
| opencode | 8 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) + repo 列表进 system prompt | ❌(compacting 前后各 commit 一次) | ✅ | ❌(有 toast) |
| dsh | Cordis 原生插件(同进程)+ MCP 代理 + skill | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),每 session 一次 | ❌ | ✅ | ❌ |
| pi | 原生扩展(9 事件) | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),进 systemPrompt 每轮重拼 | ✅ **takeover**(默认开) | ✅ | ✅ |
@@ -71,7 +73,7 @@ profile 注入列里,第一个数字是 `profileTokenBudget` 的默认值,`<
## 1.3 形态分组
- **全家桶型**(hook 自动化 + MCP 工具面 + 周边 UX 齐全):claude-code、codex(trae-cli 经别名安装同属此档)。
-- **瘦 hook 型**(共享 agent-hook-runtime,核心行为基本一致,差异仅体现在宿主事件与阈值上):cursor、trae/trae-cn、zcode。
+- **瘦 hook 型**(共享 agent-hook-runtime,核心行为基本一致,差异仅体现在宿主事件、transcript 解码与阈值上):cursor、trae/trae-cn、zcode、kimicode。
- **plugin 事件型**:opencode(宿主事件面最丰富,dispose 覆盖关闭)。
- **同进程原生型**:dsh(Cordis)、pi(扩展 + takeover 压缩接管)、openclaw(context-engine 全接管)、hermes(MemoryProvider)。
- **工具型**:ov CLI(所有操作均为显式调用,不存在任何自动行为)。
@@ -174,6 +176,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌(共用安装器 TUI) |
| trae / trae-cn | 配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json) | 一键 `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |
| zcode | 配置驱动(合并进 `~/.zcode/cli/config.json`,并强制 `hooks.enabled=true`) | 一键 `--harness zcode` | `zc-<sess_…>` | env + ovcli.conf `plugin.zcode` | ❌ |
+| kimicode | Kimi Code 原生插件(`kimi.plugin.json`,managed copy + `installed.json`) | 一键 `--harness kimicode` | `kc-<session_id>` | env + ovcli.conf `plugin.kimicode` + workspace 文件 | ❌ |
| opencode | npm 插件 `@openviking/opencode-plugin`(config hook 自注入 MCP 条目) | 一键 `--harness opencode`(npm 注册 + 代理快照兜底)/ 手动 npm / 源码 | `oc-<id>`;subagent 格式为 `oc-<parent>__subagent-<child>` | env + ovcli.conf `plugin.opencode` | ✅ |
| dsh | Cordis 同进程插件(`cordis.patch.yml` plugin group) | 统一安装器(会询问 profile,默认 `web`),或执行 `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id 原样>`;subagent 各自独立会话 | env + ovcli.conf `plugin.dsh` + cordis patch config(行为旋钮的最低层;凭据仍以 patch 优先) | ❌ |
| pi | pi 原生扩展(目录装载,jiti 直译 TS) | 一键 `--harness pi`(复制到自动发现目录,无需 `pi install`) | `pi-<piSessionId>` | env + ovcli.conf `plugin.pi`(凭据字段由凭据链统一解析) | ✅ |
@@ -183,13 +186,13 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
### 3.1.2 统一安装器
-统一安装脚本 `examples/memory-plugin-shared/install.sh` 覆盖 10 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`(其中 openclaw 走自有渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:
+统一安装脚本 `examples/memory-plugin-shared/install.sh` 覆盖 11 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, opencode, pi, dsh`(其中 openclaw 走自有渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:
- 双分发:`--dist github|tos`;三源:`--source remote|archive|dev`。以 `bash <(curl …)` 方式执行时会从 `/dev/tty` 读取输入,从而保留交互。
- 官方 docs 的规范一键命令是不带 `--harness` 的裸命令(执行后进入 TUI 多选);而各插件自带的 setup-helper 转发脚本在调用时会自动补 `--harness`。
- 幂等合并:hooks/mcp 条目按 `OPENVIKING_INTEGRATION_ID` 标记识别自有条目,做到剔旧追新的同时不动第三方;写入采用原子操作——先备份 `.bak`,写 tmp 后 rename 覆盖,权限 0600。
- 凭据向导写 `~/.openviking/ovcli.conf`:三选一(本地 `http://127.0.0.1:1933` / 火山云 `https://api.vikingdb.cn-beijing.volces.com/openviking` / 自定义),已有配置先展示当前值再问"沿用/重配",API key 掩码。
-- 卸载:`--uninstall` 覆盖 cursor / trae / trae-cn / zcode,并顺带清理 trae-cli 遗留的旧 hook 配置;claude / codex / trae-cli / opencode / pi 这些 Codex 格式或宿主托管的插件,通过各自宿主的插件管理卸载。
+- 卸载:`--uninstall` 覆盖 cursor / trae / trae-cn / zcode / kimicode,并顺带清理 trae-cli 遗留的旧 hook 配置;其他 Codex 格式或宿主托管插件通过各自宿主的插件管理卸载。
- 安装后自检:grep 配置 + `node --check` + 一次 `OPENVIKING_MEMORY_ENABLED=0` 的 smoke run。
- Node 门槛:安装器检查 18+。
@@ -520,7 +523,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## claude-code
- **集成文档**:[Claude Code 记忆插件](./02-claude-code.md)
-- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(16 工具透传)+ slash command + statusline + 4 个 skill(`openviking-memory`、`openviking-skills`、`ov-experience-memory`、`ov-memory-doctor`)。版本 0.6.0。
+- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(16 工具透传)+ slash command + statusline + 4 个 skill(`openviking-memory`、`openviking-skills`、`ov-experience-memory`、`ov-memory-doctor`)。版本 0.6.1。
- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep\|Edit\|Write\|Bash(5s,uri-guard:文件工具的路径是 `viking://` URI 时拒绝,针对 skill URI 的 Write/Edit 会被引导到 `add_skill`;Bash 命令带 `viking://` URI 时附加提示) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:session id 为 `cc-<CC session_id 原文>`,subagent 为 `…__subagent-<agent_id>`;Stop 阈值 commit 20000/keep 10,PreCompact 同步 commit;自动召回排除 resources([§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));增量游标存于 `/tmp`(被系统清理后,同一会话会整段重推)。
- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 70 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。
@@ -529,7 +532,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## codex
- **集成文档**:[Codex 记忆插件](./04-codex.md)
-- **形态**:Codex 插件(marketplace),6 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s / PreToolUse:Bash 5s)+ MCP 代理 + 与 claude-code 相同的 4 个 skill。版本 0.10.0。
+- **形态**:Codex 插件(marketplace),6 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s / PreToolUse:Bash 5s)+ MCP 代理 + 与 claude-code 相同的 4 个 skill。版本 0.10.1。
- **能力亮点**:本地召回压缩管线(`codex exec`,[§3.2.5](#_3-2-5-召回再摘要));SessionEnd(Codex ≥ 0.145)在正常退出时补齐 Stop 漏掉的轮次并 commit,SessionStart 的兜底扫描回收那些没触发 SessionEnd 的退出所遗留的未归档消息([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));PreToolUse:Bash(uri-guard)放行带 `viking://` URI 的 shell 命令,并附加提示,建议改用 OpenViking MCP 工具;Codex 通过 `apply_patch` 编辑文件,输入里没有路径参数,因此 guard 不会拒绝任何调用。
- **行为要点**:session id 为 `cx-<safeId>`(确定性推导,不读 state);SessionEnd 只在正常退出、且 Codex 0.145+ 时触发,信号、崩溃、旧版本以及 `codex app-server` 延后的场景都落到扫描路径;不使用磁盘 pending queue(离线靠游标不推进、下一轮重发补偿,[§3.3.4](#_3-3-4-pending-queue-离线补偿对照));idle-TTL 1800000ms、锁等待 120000ms(env 配置);Stop 与 SessionEnd 默认 detach(`appended N turn(s)` 提示默认不展示);单会话 mkdir 锁串行化 Stop worker、PreCompact、SessionEnd worker 与扫描。新增的 hook 在 Codex 侧没有信任记录,升级后需在 `/hooks` 中批准这次升级新增的 hook(SessionEnd、PreToolUse)。
- **配置**:env + ovcli.conf `plugin.codex` + ov.conf `codex`;hooks 只用 `Authorization: Bearer` 认证([§3.1.3](#_3-1-3-凭据体系))。
@@ -546,7 +549,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## cursor
- **集成文档**:[Cursor 记忆集成](./12-cursor.md)
-- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + 2 个 skill(`openviking-memory`、`openviking-skills`)。6 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。版本 0.4.0。
+- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + 2 个 skill(`openviking-memory`、`openviking-skills`)。6 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。版本 0.5.0。
- **能力亮点**:beforeReadFile 上的 uri-guard 拒绝读取 `viking://` 路径(不受插件开关控制);shell 命令不做检查,升级时会移除旧版本注册的 beforeShellExecution 条目;rule 与两个 skill 随装。
- **行为要点**:session id 为 `cu-<conversation_id>`;stop 每 8 条消息 commit(`commitTurnThreshold=8`,消息条数计数,keep 0);`sessionEnd` 仅 window_close 触发,且此时宿主已销毁 shell-exec host,实践中不执行([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——结束在 <8 条消息水位的会话,尾部依赖后续同会话消息触发归档([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));服务端不可达时,每轮等满 15s 召回超时。
- **配置**:env + ovcli.conf `plugin.cursor` + workspace 文件([§3.1.4](#_3-1-4-配置体系分层))。
@@ -555,7 +558,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## trae / trae-cn(IDE 版)
- **集成文档**:[TRAE 记忆集成](./13-trae.md)
-- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。PreToolUse 对路径是 `viking://` URI 的 Read/Glob/Grep 直接拒绝;Bash/RunCommand 命令带 `viking://` URI 时照常执行,并附加提示。相对 import 共享 lib。MCP server 名为 `openviking`。版本 0.4.0。
+- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。PreToolUse 对路径是 `viking://` URI 的 Read/Glob/Grep 直接拒绝;Bash/RunCommand 命令带 `viking://` URI 时照常执行,并附加提示。相对 import 共享 lib。MCP server 名为 `openviking`。版本 0.5.0。
- **能力亮点**:行为最简单直接的一档——每个有内容的 Stop 都 commit(keep 0),关闭场景下最大待归档量只有最后一轮 in-flight([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:trae 与 trae-cn 的差异是 session id 前缀 `tr-` / `trcn-` 与安装路径——同一份记忆在两个客户端落到两组不同 session,跨客户端共享靠服务端抽取后的记忆空间而非 session 复用;无 PreCompact/statusline/skill/subagent 处理。
- **配置**:env + ovcli.conf `plugin.trae` / `plugin.trae_cn` + workspace 文件。
@@ -564,16 +567,25 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## zcode
- **集成文档**:[社区插件 → ZCode](./08-community-plugins.md)
-- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。自身不 vendoring 任何共享模块:安装器按 cursor / trae 同样的方式为它拼装共享运行时。版本 0.4.0。
+- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。自身不 vendoring 任何共享模块:安装器按 cursor / trae 同样的方式为它拼装共享运行时。版本 0.5.0。
- **能力亮点**:以 rollout 文件 `~/.zcode/cli/rollout/model-io-<sid>.jsonl` 为增量真相源(`lastTurnId` 差集补齐漏掉的 Stop);Stop 默认 detach(Ctrl+C 不丢写入)。
- **行为要点**:每 Stop commit(keep 0);捕获路径仅剥离三类注入块(不做额外文本清洗,[§3.2.6](#_3-2-6-注入回流防护));首次捕获会一次性读取整个 rollout(长会话首装时单次推送量大)。
- **配置**:env + ovcli.conf `plugin.zcode` + workspace 文件;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。
+## kimicode
+
+- **集成文档**:[社区插件 → Kimi Code](./08-community-plugins.md)
+- **形态**:原生 managed plugin,包含 7 个 hook 和 MCP 代理。安装器在 `$KIMI_CODE_HOME/plugins/managed/openviking-memory` 下组装一份自包含副本,不向仓库提交 Kimi 的共享运行时副本。版本 0.5.0;已在 Kimi Code CLI 0.43.1 契约上验证。
+- **能力亮点**:`wire.jsonl` 作为稳定的增量回合来源;profile 在 prompt hook 上重试,直到首次成功。Stop、PreCompact 和 SessionEnd 可 detached;Interrupt 保持同步,所有 OpenViking 请求共用 2 秒总预算。
+- **行为要点**:UserPromptSubmit 输出原始上下文文本,不输出 JSON 字符串。只有在发送成功或已持久化入队后才推进增量游标。安装时保留其他插件记录,不修改旧式 `config.toml` 或 `mcp.json`。
+- **配置**:env + ovcli.conf `plugin.kimicode` + workspace 文件。
+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。
+
## opencode
- **集成文档**:[OpenCode 插件](./10-opencode.md)
-- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。8 个 plugin hook:config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。tool.execute.before 拒绝路径是 `viking://` URI 的 read/glob/grep;bash 命令带 `viking://` URI 时,tool.execute.after 在输出末尾追加提示。版本 0.3.3。
+- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。8 个 plugin hook:config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。tool.execute.before 拒绝路径是 `viking://` URI 的 read/glob/grep;bash 命令带 `viking://` URI 时,tool.execute.after 在输出末尾追加提示。版本 0.4.1。
- **能力亮点**:`dispose` hook 覆盖全部四种常规关闭方式(宿主 ≥1.15.11);repo 列表进 system prompt([§3.2.3](#_3-2-3-profile-开场注入));宿主事件面最丰富(session.idle/compacted/deleted/error 各有语义)。
- **行为要点**:`commitTokenThreshold=20000`(取正数,0 回落默认值);commit 超时 30000ms;一次宿主压缩 = 两次 commit;dispose 的 5s 宿主预算下,多会话慢 commit 可能被截断,且 pending queue 不覆盖此场景([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));<1.15.11 无 dispose 时关闭不 commit;重启后不主动 flush 遗留会话;开场注入每会话尝试一次([§3.2.3](#_3-2-3-profile-开场注入));`bypassSessionPatterns` 的目录匹配在 opencode 上不适用(input 无 cwd)。
- **配置**:env + ovcli.conf `plugin.opencode` + workspace 文件。
@@ -581,7 +593,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## dsh(DeepSeek Harness)
-- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),工具面就是服务端的 MCP 面,经 `@deepseek-ai/dsh-mcp-client` 与共享 stdio 代理接入(以 `mcp__openviking__*` 发布),hook 侧 REST 直连。6 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush / tools/pre-execute / tools/post-execute。版本 0.5.0。
+- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),工具面就是服务端的 MCP 面,经 `@deepseek-ai/dsh-mcp-client` 与共享 stdio 代理接入(以 `mcp__openviking__*` 发布),hook 侧 REST 直连。6 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush / tools/pre-execute / tools/post-execute。版本 0.5.1。
- **能力亮点**:`ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发;pre-step 注入走 user 消息,适配 DSH persona 的 `complete:true` 渲染模式。
- **行为要点**:统一安装器已覆盖 dsh,会询问装到哪个 profile(默认 `web`,可用 `--dsh-profile` 指定);npm 是该插件唯一的分发渠道,因此 github/tos 选择对它不适用,除 `dev` 外的模式一律装已发布的包;`dev` 会先把 checkout 打包再装——`dsh plugin` 转发给 pnpm,link 一个源码目录无法解析插件 import 的 dsh peer;teardown commit 3s 无阈值,SIGHUP/二次 Ctrl+C 不触发([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));compaction 不感知(注入内容随宿主压缩收缩,profile 不重投);subagent 各自独立会话([§3.3.5](#_3-3-5-subagent-会话对照));工具面即服务端自身的 MCP 面,经与其他集成同一个 stdio 代理接入、以 `mcp__openviking__*` 发布,服务端升级即可增加工具而无需发版;代价是代理每个 profile 只起一个进程,因此工具调用带的是进程级 actor peer、`remember` 也不绑当前会话(召回/捕获/commit 仍按会话解析 peer);另随包附带共享的 `openviking-memory` 与 `openviking-skills` 两个 skill;uri-guard 先把工具名转成小写再匹配,tools/pre-execute 拒绝路径是 `viking://` URI 的文件工具(针对 skill URI 的 write/edit 会被引导到 `mcp__openviking__add_skill`),bash 命令带 `viking://` URI 时由 tools/post-execute 附加提示(`form: "notice"`)。
- **配置**:env + ovcli.conf `plugin.dsh` + workspace 文件 + cordis patch(行为旋钮的最低层);凭据是例外,patch 里写的 endpoint / key / account / user / peer 仍然压过凭据链。
@@ -590,7 +602,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## pi(pi Coding Agent Extension)
- **集成文档**:[pi Coding Agent 扩展](./11-pi.md)
-- **形态**:pi 原生扩展(目录装载,jiti 直译 TS)。扩展使用 `@modelcontextprotocol/client`,把服务端 `tools/list` 的每个描述符注册成名为 `openviking_<tool>` 的 pi 工具,当前 16 个([§2.1](#_2-1-服务端-mcp-工具面))。扩展里没有任何工具目录,服务端增删工具,pi 下一次会话即跟上,不需要发插件版本。召回、会话同步、profile 注入与 takeover 仍走 REST。9 事件 + `/viking` 命令;tool_call 拦截路径是 `viking://` URI 的 read/grep/find/ls/write/edit,bash 命令带 `viking://` URI 时,tool_result 在结果末尾追加提示。版本 0.4.0。
+- **形态**:pi 原生扩展(目录装载,jiti 直译 TS)。扩展使用 `@modelcontextprotocol/client`,把服务端 `tools/list` 的每个描述符注册成名为 `openviking_<tool>` 的 pi 工具,当前 16 个([§2.1](#_2-1-服务端-mcp-工具面))。扩展里没有任何工具目录,服务端增删工具,pi 下一次会话即跟上,不需要发插件版本。召回、会话同步、profile 注入与 takeover 仍走 REST。9 事件 + `/viking` 命令;tool_call 拦截路径是 `viking://` URI 的 read/grep/find/ls/write/edit,bash 命令带 `viking://` URI 时,tool_result 在结果末尾追加提示。版本 0.4.1。
- **能力亮点**:takeover 压缩接管(默认开,[§3.4.2](#_3-4-2-pi-takeover));两段式召回(before_agent_start 排队 + context 事件同步检索,当前轮 prompt 拿当前轮记忆);statusline;`session_shutdown` 在所有关闭方式下都触发且被 await。
- **行为要点**:默认 takeover 下退出不 commit(handler 持久化本地状态,归档靠下次续跑攒满阈值或 `/viking commit`,[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));takeover 阈值 30000 token + 保留 3 轮(keep 3,服务端按消息条数解释);非 takeover 阈值 20000/keep 10、退出无条件 commit;工具注册需 health、ensureSession 与 `/mcp` 握手三项前置([§1.1](#_1-1-主动工具面-agentic-调用能力)),ROOT 角色的 API key 访问 `/mcp` 会被 403 拒绝,凭据链最终落到 `ov.conf` 的 `server.root_api_key` 时本次会话就没有工具——0.4.0 之前是 REST 工具照常注册、每次调用静默返回 "No results found.";`openviking_remember` 走 MCP 面,即自建一次性会话并立即提交,不再并入 pi 的会话([§2.1](#_2-1-服务端-mcp-工具面));`openviking_add_resource` 可直接摄取远端 URL,本地路径则由服务端返回一条上传指引,需要模型用 `bash` 把文件 POST 上去,与其他 MCP harness 一致;`openviking_read` 只返回全文,目录 URI 会得到 `Cannot render …: URI points to a directory`,旧的 `level="abstract"/"overview"` 两档在 MCP 面没有对应工具,替代路径是 `openviking_search(mode="context", detail="overview")` 或 `openviking_tree(include_abstract=true)`,takeover 的归档 overview 仍由扩展自己经 REST 注入;单次工具调用受共享的 `timeoutMs` 约束(15000ms,`OPENVIKING_TIMEOUT_MS` 可调),`write`/`edit` 带 `wait=true` 或 `add_resource` 同步 ingest 有可能超过,而超时或 ESC 只让本地调用失败,已经发出的请求会跑完,写入仍可能已经生效;从 0.3.x 升级时全部工具改名且没有别名期,`--tools` / `--exclude-tools` 白名单里写死的 `viking_*` 必须手工替换,否则工具会静默消失;非 takeover 模式下 `pi -c` 续跑会重新上报整条 branch。
- **配置**:env + ovcli.conf `plugin.pi` + workspace 文件(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));bypass 走共享 `isBypassed` 的 glob 匹配,键名 `bypassSessionPatterns`(旧名 `bypassPatterns` 仍可读);共享键 `mcpEnabled: false` 现在对 pi 也生效:不发起桥接、不注册工具,`/viking` 标注成配置而非故障。
diff --git a/examples/agent-hook-plugin/README.md b/examples/agent-hook-plugin/README.md
index 341e99786..6658e34cd 100644
--- a/examples/agent-hook-plugin/README.md
+++ b/examples/agent-hook-plugin/README.md
@@ -1,29 +1,30 @@
-# OpenViking Memory for the config-driven hook hosts
+# OpenViking Memory for thin hook hosts
-Cursor, TRAE, TRAE CN and ZCode all install the same way: the shared installer writes lifecycle hooks and an MCP server entry into the host's own configuration files, and assembles the OpenViking runtime beside the integration. None of them has a marketplace listing to register or a separate MCP setup to do.
+Cursor, TRAE, TRAE CN and ZCode use host configuration files. Kimi Code uses its native managed-plugin directory. They share the same dispatcher and memory runtime; the installer assembles the runtime at install time rather than committing a copy per host.
```bash
bash examples/memory-plugin-shared/install.sh --harness cursor
bash examples/memory-plugin-shared/install.sh --harness trae,trae-cn
bash examples/memory-plugin-shared/install.sh --harness zcode
+bash examples/memory-plugin-shared/install.sh --harness kimicode
```
> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less `viking://user/memories` shorthand is rejected by newer servers.
## What the hooks do
-- **Session start** — injects the user profile and preferences, plus an `<available-skills>` catalog of the user's own and account-shared OpenViking skills, and replays anything an offline session queued. The catalog has its own budget, `skillCatalogTokenBudget` (default 1200 tokens), and falls back to names only when descriptions do not fit; `skillCatalog: false` or a budget of `0` drops it.
+- **Session start** — injects the user profile and preferences, plus an `<available-skills>` catalog of the user's own and account-shared OpenViking skills, and replays anything an offline session queued. Kimi replays a bounded batch at startup and injects the profile on the first successful prompt hook because its SessionStart output is not a context channel.
- **Prompt submit** — searches OpenViking for memories and skills relevant to the prompt and injects them, deduplicated by event id and a 500ms window.
- **Tool use** — denies local file tools a `viking://` virtual path and points the agent back at the OpenViking MCP tools. On TRAE a shell command that carries a `viking://` URI still runs, with a notice pointing at the same tools.
- **Stop** — captures the finished turn and commits the OpenViking session. Cursor also runs this before a compaction and at session end; ZCode answers first and finishes the writes in a detached worker.
## Layout
-`scripts/hook.mjs` is the single entry every hook command runs. It owns the state machine all four clients share — the debounce, the prompt dedup, the recall cache, the cross-process lock — and asks the adapter under `hosts/` for the four things that differ: the event vocabulary, the response envelope, how a prompt is read out of the payload, and how a finished turn is captured. `scripts/uri-guard.mjs` and `servers/mcp-proxy.mjs` are likewise one file each, with the host chosen from the client id the installer passes.
+`scripts/hook.mjs` is the single entry every hook command runs. It owns the state machine all five clients share — the debounce, the prompt dedup, the recall cache, the cross-process lock — and asks the adapter under `hosts/` for the four things that differ: the event vocabulary, the response envelope, how a prompt is read out of the payload, and how a finished turn is captured. `scripts/uri-guard.mjs` and `servers/mcp-proxy.mjs` are likewise one file each, with the host chosen from the client id the installer passes.
-The root `plugin.json` is host-neutral package metadata used for version checks and diagnostics. It is not a Claude Code, Cursor, TRAE, or ZCode native plugin manifest.
+The root `plugin.json` is host-neutral package metadata used for version checks and diagnostics. Kimi's native manifest lives under `hosts/kimicode/` and is copied to the root of its assembled installation.
-`hosts/<host>/` holds only what a host reads as configuration — `hooks.json`, `.mcp.json`, `openviking.integration.json`, plus Cursor's rule and its two skills, `openviking-memory` and `openviking-skills`; TRAE and ZCode ship no skill. Everything executable stays one level up, because `../../memory-plugin-shared/lib` is the path that resolves both in this repository and in an installed `~/.openviking/agent-integrations/<client>/`.
+`hosts/<host>/` holds host configuration or native-manifest files; executable adapters stay one level up. The `../../memory-plugin-shared/lib` import resolves in the repository, config-driven installs, and Kimi's assembled native bundle.
The memory logic itself is not here: recall, batching, the pending queue, credential resolution and the MCP proxy all come from `examples/memory-plugin-shared/lib`, which the installer copies to `~/.openviking/agent-integrations/memory-plugin-shared/lib`.
@@ -32,6 +33,7 @@ The memory logic itself is not here: recall, batching, the pending queue, creden
- **Cursor** — six events, including the `preCompact` and `sessionEnd` no other host in this plugin has. Commits on Stop once `capturedSinceCommit` reaches the threshold, and unconditionally before a compaction. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).
- **TRAE / TRAE CN** — capture reads `prompt`, `text_content` and `last_assistant_message` off the Stop event rather than parsing a transcript. Every Stop that carries content commits. Sessions are `tr-` and `trcn-`. See the [TRAE guide](../../docs/en/agent-integrations/13-trae.md).
- **ZCode** — the rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and let a later Stop recover missed turns, and hook stdin is only the fallback. ZCode supports neither `PreCompact` nor `SessionEnd`, so committing on every Stop stands in for both. Its output schema is strict, so a pass-through writes nothing at all. Sessions are `zc-`. [DESIGN.md](./DESIGN.md) records the verified extension surface.
+- **Kimi Code** — `wire.jsonl` is the authoritative transcript. UserPromptSubmit emits raw context text, while Stop, PreCompact and SessionEnd may detach; Interrupt remains synchronous under a two-second OpenViking request budget. The installer creates a self-contained native plugin without editing legacy `config.toml` or `mcp.json`. Sessions are `kc-`. [Host contract](./hosts/kimicode/DESIGN.md).
## Diagnostics
@@ -39,7 +41,13 @@ The memory logic itself is not here: recall, batching, the pending queue, creden
node ~/.openviking/agent-integrations/<client>/scripts/ov-memory-doctor.mjs --offline
```
-The client defaults to the one this copy was installed for; pass `cursor`, `trae`, `trae-cn` or `zcode` as an argument to override it, drop `--offline` to probe the server as well, and add `--json` for a machine-readable report.
+For Kimi's managed plugin, use its installed path instead:
+
+```bash
+node "${KIMI_CODE_HOME:-$HOME/.kimi-code}/plugins/managed/openviking-memory/agent-integrations/kimicode/scripts/ov-memory-doctor.mjs" kimicode --offline
+```
+
+For config-driven copies, the client defaults to the one that copy was installed for; pass `cursor`, `trae`, `trae-cn` or `zcode` as an argument to override it. Drop `--offline` to probe the server as well, and add `--json` for a machine-readable report.
## Tests
diff --git a/examples/agent-hook-plugin/README_CN.md b/examples/agent-hook-plugin/README_CN.md
index c84e43337..d8229c62a 100644
--- a/examples/agent-hook-plugin/README_CN.md
+++ b/examples/agent-hook-plugin/README_CN.md
@@ -1,29 +1,30 @@
-# OpenViking 记忆:配置驱动的 Hook 宿主
+# OpenViking 记忆:轻量 Hook 宿主
-Cursor、TRAE、TRAE CN 与 ZCode 的安装方式相同:共享安装脚本把生命周期 hook 与 MCP server 条目写进宿主自己的配置文件,并在集成目录旁装配 OpenViking 运行时。四家都不需要注册 marketplace,也不需要单独配置 MCP。
+Cursor、TRAE、TRAE CN 与 ZCode 使用宿主配置文件;Kimi Code 使用原生托管插件目录。它们共用同一个 dispatcher 和记忆运行时,安装脚本在安装时组装依赖,不在仓库里为每个宿主提交共享代码副本。
```bash
bash examples/memory-plugin-shared/install.sh --harness cursor
bash examples/memory-plugin-shared/install.sh --harness trae,trae-cn
bash examples/memory-plugin-shared/install.sh --harness zcode
+bash examples/memory-plugin-shared/install.sh --harness kimicode
```
> **需要支持 `viking://~` home alias 的 OpenViking 服务端。** 召回通过 `viking://~/memories` 与 `viking://~/skills` 指向调用者自己的上下文空间;不带 uid 的 `viking://user/memories` 简写会被较新的服务端拒绝。
## Hook 做什么
-- **会话开始** — 注入用户画像与偏好,外加 `<available-skills>` 清单,列出用户自己的和账号内共享的 OpenViking skill;同时重放离线会话排队的写入。清单有独立的预算 `skillCatalogTokenBudget`(默认 1200 token),描述放不下时只列名称;`skillCatalog: false` 或把预算设为 `0` 会去掉它。
+- **会话开始** — 注入用户画像与偏好,外加 `<available-skills>` 清单,列出用户自己的和账号内共享的 OpenViking skill;同时重放离线会话排队的写入。Kimi 启动时只重放一个有界小批次,并在第一次成功的 prompt hook 注入画像。
- **提交 prompt** — 搜索与 prompt 相关的记忆和 skill 并注入,按事件 id 与 500ms 窗口去重。
- **工具调用前** — 拦截本地文件工具对 `viking://` 虚拟路径的访问,引导回 OpenViking MCP 工具。在 TRAE 上,带 `viking://` URI 的 shell 命令照常执行,并附加一条指向同一组工具的提示。
-- **Stop** — 捕获完成的回合并提交 OpenViking 会话。Cursor 另外在压缩前与会话结束时执行;ZCode 先应答,再在 detached worker 里完成写入。
+- **Stop** — 捕获完成的回合并按宿主策略提交 OpenViking 会话。Kimi 还使用 PreCompact、SessionEnd 与同步 Interrupt 信号。
## 目录结构
-`scripts/hook.mjs` 是所有 hook 命令的唯一入口,持有四家共用的状态机——防抖、prompt 去重、召回缓存、跨进程锁——差异部分向 `hosts/` 下的适配器索取:事件词汇、响应信封、如何从 payload 读出 prompt、如何采集完成的回合。`scripts/uri-guard.mjs` 与 `servers/mcp-proxy.mjs` 同样各只有一份,按安装器传入的 client id 选择宿主。
+`scripts/hook.mjs` 是所有 hook 命令的唯一入口,持有五家共用的状态机——防抖、prompt 去重、召回缓存、跨进程锁——差异部分向 `hosts/` 下的适配器索取:事件词汇、响应信封、如何从 payload 读出 prompt、如何采集完成的回合。`scripts/uri-guard.mjs` 与 `servers/mcp-proxy.mjs` 同样各只有一份,按安装器传入的 client id 选择宿主。
-根目录的 `plugin.json` 是宿主无关的包元数据,只用于版本检查和诊断,不是 Claude Code、Cursor、TRAE 或 ZCode 的原生插件 manifest。
+根目录的 `plugin.json` 是宿主无关的包元数据,只用于版本检查和诊断。Kimi 的原生 manifest 位于 `hosts/kimicode/`,安装组装时复制到插件根目录。
-`hosts/<host>/` 只放宿主当作配置读取的东西——`hooks.json`、`.mcp.json`、`openviking.integration.json`,以及 Cursor 的 rule 和两个 skill(`openviking-memory`、`openviking-skills`);TRAE 与 ZCode 不带 skill。可执行文件一律放在上一层,因为 `../../memory-plugin-shared/lib` 这条相对路径要在本仓库和安装后的 `~/.openviking/agent-integrations/<client>/` 两处同时成立。
+`hosts/<host>/` 只放宿主配置或原生 manifest;可执行适配器放在上一层。`../../memory-plugin-shared/lib` 这条相对路径在源码树、配置型安装和 Kimi 组装后的原生插件里都成立。
记忆逻辑本身不在这里:召回、批量写入、待处理队列、凭据解析与 MCP 代理都来自 `examples/memory-plugin-shared/lib`,由安装脚本复制到 `~/.openviking/agent-integrations/memory-plugin-shared/lib`。
@@ -32,6 +33,7 @@ bash examples/memory-plugin-shared/install.sh --harness zcode
- **Cursor** — 六个事件,其中 `preCompact` 与 `sessionEnd` 是本插件里独有的。Stop 时 `capturedSinceCommit` 达到阈值才 commit,压缩前无条件 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。
- **TRAE / TRAE CN** — 采集直接读 Stop 事件的 `prompt`、`text_content`、`last_assistant_message`,不解析 transcript;每次带内容的 Stop 都 commit。会话前缀 `tr-` 与 `trcn-`。见 [TRAE 接入文档](../../docs/zh/agent-integrations/13-trae.md)。
- **ZCode** — rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能补回漏掉的回合,hook stdin 只是兜底。ZCode 不支持 `PreCompact` 与 `SessionEnd`,因此每次 Stop 都 commit 来补足这两个信号。它的输出 schema 是严格的,所以放行时不写任何内容。会话前缀 `zc-`。已验证的扩展面记录在 [DESIGN.md](./DESIGN.md)。
+- **Kimi Code** — `wire.jsonl` 是权威 transcript;UserPromptSubmit 输出原始上下文文本。Stop、PreCompact、SessionEnd 可后台写入,Interrupt 保持同步并共享 2 秒的 OpenViking 请求预算。安装脚本生成自包含原生插件,不修改旧的 `config.toml` 或 `mcp.json`。会话前缀 `kc-`。
## 体检
@@ -39,7 +41,13 @@ bash examples/memory-plugin-shared/install.sh --harness zcode
node ~/.openviking/agent-integrations/<client>/scripts/ov-memory-doctor.mjs --offline
```
-client 默认取这份副本安装时对应的那个;传 `cursor`、`trae`、`trae-cn` 或 `zcode` 可以覆盖,去掉 `--offline` 会连带探测服务端,加 `--json` 输出机器可读的报告。
+Kimi 的 managed plugin 需要使用它的实际安装路径:
+
+```bash
+node "${KIMI_CODE_HOME:-$HOME/.kimi-code}/plugins/managed/openviking-memory/agent-integrations/kimicode/scripts/ov-memory-doctor.mjs" kimicode --offline
+```
+
+对于配置型安装副本,client 默认取安装时对应的宿主;传 `cursor`、`trae`、`trae-cn` 或 `zcode` 可以覆盖。去掉 `--offline` 会连带探测服务端,加 `--json` 输出机器可读报告。
## 测试
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index 10d845f90..feb27ace6 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.4.0",
+ "version": "0.5.0",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/incremental-turn-capture.mjs b/examples/agent-hook-plugin/hosts/incremental-turn-capture.mjs
new file mode 100644
index 000000000..c8ca00352
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/incremental-turn-capture.mjs
@@ -0,0 +1,82 @@
+import { stableHash } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { shouldCaptureText } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+
+export function turnDedupKey(turn) {
+ return turn.turnId
+ ? `${turn.turnId}:${turn.role}`
+ : stableHash(turn.role, turn.content);
+}
+
+export function buildIncrementalCapturePlan(turns, state = {}, cfg = {}) {
+ const acknowledged = new Set(
+ Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
+ );
+ const candidates = [];
+ for (const turn of turns) {
+ const decision = shouldCaptureText(turn.content, turn.role, cfg);
+ if (!decision.shouldCapture) continue;
+ candidates.push({ dedupKey: turnDedupKey(turn), turn, content: decision.text });
+ }
+ const toSend = candidates.filter((item) => !acknowledged.has(item.dedupKey));
+ const payloads = toSend.map(({ turn, content }) => ({
+ role: turn.role,
+ content,
+ ...(turn.turnId ? { turn_id: turn.turnId } : {}),
+ }));
+ return { candidates, toSend, payloads };
+}
+
+function acknowledgedCursor(candidates, acknowledged) {
+ let cursor = null;
+ let currentTurnId = null;
+ let currentComplete = true;
+
+ for (const item of candidates) {
+ const turnId = item.turn.turnId || null;
+ if (!turnId) continue;
+ if (currentTurnId !== turnId) {
+ if (currentTurnId && currentComplete) cursor = currentTurnId;
+ if (currentTurnId && !currentComplete) return cursor;
+ currentTurnId = turnId;
+ currentComplete = true;
+ }
+ if (!acknowledged.has(item.dedupKey)) currentComplete = false;
+ }
+
+ if (currentTurnId && currentComplete) cursor = currentTurnId;
+ return cursor;
+}
+
+export function applyIncrementalCaptureResult(state, plan, result, cleanText) {
+ const acknowledged = new Set(
+ Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
+ );
+ const captured = Math.min(
+ plan.toSend.length,
+ Math.max(0, Number(result?.sent || 0) + Number(result?.queued || 0)),
+ );
+ for (const item of plan.toSend.slice(0, captured)) acknowledged.add(item.dedupKey);
+
+ const cursor = acknowledgedCursor(plan.candidates, acknowledged);
+ const pendingPrompt = cleanText(state.pendingPrompt?.prompt || "");
+ let pendingPromptItem = null;
+ if (pendingPrompt) {
+ for (let index = plan.candidates.length - 1; index >= 0; index--) {
+ const item = plan.candidates[index];
+ if (item.turn.role === "user" && cleanText(item.turn.content) === pendingPrompt) {
+ pendingPromptItem = item;
+ break;
+ }
+ }
+ }
+
+ return {
+ ...state,
+ capturedTurnIds: [...acknowledged].slice(-1000),
+ pendingPrompt: pendingPromptItem && acknowledged.has(pendingPromptItem.dedupKey)
+ ? null
+ : state.pendingPrompt,
+ lastTurnId: cursor || state.lastTurnId || null,
+ captured,
+ };
+}
diff --git a/examples/agent-hook-plugin/hosts/index.mjs b/examples/agent-hook-plugin/hosts/index.mjs
index a09b505af..79d6bc1fd 100644
--- a/examples/agent-hook-plugin/hosts/index.mjs
+++ b/examples/agent-hook-plugin/hosts/index.mjs
@@ -1,6 +1,7 @@
import { cursor } from "./cursor.mjs";
+import { kimicode } from "./kimicode.mjs";
import { trae, traeCn } from "./trae.mjs";
import { zcode } from "./zcode.mjs";
/** Every client id the installer can configure, keyed the way it names them. */
-export const HOSTS = { cursor, trae, "trae-cn": traeCn, zcode };
+export const HOSTS = { cursor, kimicode, trae, "trae-cn": traeCn, zcode };
diff --git a/examples/agent-hook-plugin/hosts/kimicode-turns.mjs b/examples/agent-hook-plugin/hosts/kimicode-turns.mjs
new file mode 100644
index 000000000..1685ae2d4
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode-turns.mjs
@@ -0,0 +1,138 @@
+/** Decode Kimi Code's wire log into stable incremental user/assistant turns. */
+
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { sanitizeCapturedText } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+
+export function cleanKimicodeText(value) {
+ if (value == null) return "";
+ const text = Array.isArray(value)
+ ? value.map((part) => (typeof part === "string" ? part : part?.text || "")).filter(Boolean).join("\n")
+ : typeof value === "object" && typeof value.text === "string"
+ ? value.text
+ : String(value);
+ return sanitizeCapturedText(text);
+}
+
+function kimiCodeHome() {
+ return process.env.KIMI_CODE_HOME || join(homedir(), ".kimi-code");
+}
+
+function textFromContent(content) {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .map((part) => (typeof part === "string" ? part : part?.text || ""))
+ .filter(Boolean)
+ .join("\n");
+}
+
+export function resolveKimicodeWirePath(input = {}, home = kimiCodeHome()) {
+ const sessionId = String(input.session_id || "").trim();
+ if (!sessionId) return "";
+ const indexPath = join(home, "session_index.jsonl");
+ if (existsSync(indexPath)) {
+ try {
+ for (const line of readFileSync(indexPath, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ const row = JSON.parse(line);
+ if (row.sessionId === sessionId && row.sessionDir) {
+ return join(row.sessionDir, "agents", "main", "wire.jsonl");
+ }
+ }
+ } catch {
+ // Fall back to the session directory scan.
+ }
+ }
+ const sessionsRoot = join(home, "sessions");
+ if (!existsSync(sessionsRoot)) return "";
+ try {
+ for (const cwdKey of readdirSync(sessionsRoot)) {
+ const candidate = join(sessionsRoot, cwdKey, sessionId, "agents", "main", "wire.jsonl");
+ if (existsSync(candidate)) return candidate;
+ }
+ } catch {
+ return "";
+ }
+ return "";
+}
+
+export function extractUnseenKimicodeTurns(wirePath, lastTurnId = null) {
+ if (!wirePath || !existsSync(wirePath)) return { status: "missing", turns: [] };
+ let raw;
+ try {
+ raw = readFileSync(wirePath, "utf8");
+ } catch (error) {
+ return { status: "unreadable", turns: [], error: error?.code || "read_failed" };
+ }
+
+ const users = new Map();
+ const assistants = new Map();
+ const order = [];
+ let pendingUser = "";
+ const remember = (value) => {
+ const turnId = String(value);
+ if (!order.includes(turnId)) order.push(turnId);
+ return turnId;
+ };
+ const attachPending = (value) => {
+ const turnId = remember(value ?? order.length);
+ if (pendingUser) {
+ users.set(turnId, `${users.get(turnId) || ""}${users.has(turnId) ? "\n" : ""}${pendingUser}`);
+ pendingUser = "";
+ }
+ return turnId;
+ };
+
+ for (const line of raw.split("\n")) {
+ if (!line.trim()) continue;
+ let row;
+ try {
+ row = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (row.type === "context.append_message" && row.message?.role === "user") {
+ pendingUser = textFromContent(row.message.content) || pendingUser;
+ continue;
+ }
+ if (row.type === "turn.prompt") {
+ if (!pendingUser) pendingUser = textFromContent(row.input);
+ continue;
+ }
+ if (row.type === "turn.ended") {
+ attachPending(row.turnId ?? row.event?.turnId);
+ continue;
+ }
+ if (row.type !== "context.append_loop_event") continue;
+ const event = row.event || {};
+ if (event.type === "turn.ended") {
+ attachPending(event.turnId ?? row.turnId);
+ continue;
+ }
+ if (event.type === "content.part" && event.part?.type === "text") {
+ const turnId = attachPending(event.turnId);
+ assistants.set(turnId, `${assistants.get(turnId) || ""}${event.part.text || ""}`);
+ }
+ }
+
+ const turns = [];
+ const lastIndex = lastTurnId == null || lastTurnId === ""
+ ? -1
+ : order.indexOf(String(lastTurnId));
+ for (const turnId of order.slice(lastIndex + 1)) {
+ const user = cleanKimicodeText(users.get(turnId) || "");
+ const assistant = cleanKimicodeText(assistants.get(turnId) || "");
+ if (user) turns.push({ role: "user", content: user, turnId });
+ if (assistant) turns.push({ role: "assistant", content: assistant, turnId });
+ }
+ return { status: "ok", turns };
+}
+
+export function buildKimicodeTurns(input = {}, state = {}) {
+ return extractUnseenKimicodeTurns(
+ resolveKimicodeWirePath(input),
+ state.lastTurnId || null,
+ );
+}
diff --git a/examples/agent-hook-plugin/hosts/kimicode.mjs b/examples/agent-hook-plugin/hosts/kimicode.mjs
new file mode 100644
index 000000000..e3523dbcf
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode.mjs
@@ -0,0 +1,78 @@
+import { addAgentMessages, commitAgentSession } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";
+import {
+ applyIncrementalCaptureResult,
+ buildIncrementalCapturePlan,
+} from "./incremental-turn-capture.mjs";
+import { buildKimicodeTurns, cleanKimicodeText } from "./kimicode-turns.mjs";
+
+export function shouldCommitKimicodeCapture(event, cfg = {}, previous = 0, captured = 0) {
+ if (captured <= 0) return false;
+ if (event === "interrupt" || event === "session-end") return true;
+ if (event === "pre-compact") return cfg.autoCommitOnCompact !== false;
+ return Number(previous || 0) + captured >= Number(cfg.commitTurnThreshold || Infinity);
+}
+
+function promptParts(input) {
+ if (typeof input === "string") return input;
+ if (!Array.isArray(input)) return "";
+ return input.map((part) => (typeof part === "string" ? part : part?.text || "")).filter(Boolean).join("\n");
+}
+
+export const kimicode = {
+ prefix: "kc-",
+ tracksPendingPrompt: true,
+ capturesOnlyWhenEnabled: true,
+ detachesCapture: true,
+ profileStage: "first-prompt",
+ requestBudgets: {
+ "session-start": 25_000,
+ "user-prompt-submit": 17_000,
+ interrupt: 2_000,
+ },
+ stages: {
+ "session-start": "start",
+ "user-prompt-submit": "prompt",
+ stop: "capture",
+ "pre-compact": "capture",
+ "session-end": "capture",
+ interrupt: "capture-sync",
+ },
+ envelope(event, block) {
+ return event === "user-prompt-submit" ? block || null : null;
+ },
+ guard(input = {}) {
+ const decision = evaluateUriGuard(input.tool_name, input.tool_input || {}, {
+ guarded: new Set(["read", "glob", "grep"]),
+ });
+ if (!decision) return {};
+ return {
+ hookSpecificOutput: {
+ permissionDecision: "deny",
+ permissionDecisionReason: decision.reason,
+ },
+ };
+ },
+ prompt(input) {
+ return cleanKimicodeText(promptParts(input.prompt));
+ },
+ async capture(ctx, state, event) {
+ const transcript = buildKimicodeTurns(ctx.input, state);
+ if (transcript.status !== "ok") {
+ ctx.log(`capture_${transcript.status}`, transcript.error ? { error: transcript.error } : {});
+ return null;
+ }
+ const plan = buildIncrementalCapturePlan(transcript.turns, state, ctx.cfg);
+ if (plan.toSend.length === 0) return null;
+
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads);
+ const next = applyIncrementalCaptureResult(state, plan, result, cleanKimicodeText);
+ let capturedSinceCommit = Number(state.capturedSinceCommit || 0) + next.captured;
+ if (shouldCommitKimicodeCapture(event, ctx.cfg, state.capturedSinceCommit, next.captured)) {
+ const committed = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
+ if (committed.ok) capturedSinceCommit = 0;
+ }
+ const { captured, ...persisted } = next;
+ return { ...persisted, capturedSinceCommit };
+ },
+};
diff --git a/examples/agent-hook-plugin/hosts/kimicode/DESIGN.md b/examples/agent-hook-plugin/hosts/kimicode/DESIGN.md
new file mode 100644
index 000000000..5e9336d9b
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode/DESIGN.md
@@ -0,0 +1,29 @@
+# Kimi Code host contract
+
+Verified against Kimi Code CLI 0.43.1 and Node.js 18+.
+
+- Kimi loads a native plugin from its managed plugin directory. The installer
+ assembles that directory; this source directory is not itself a complete
+ runnable plugin.
+- Hook stdin is snake-case JSON. The adapter consumes the verified
+ `session_id`, `cwd`, `prompt`, `tool_name`, and `tool_input` fields only;
+ `UserPromptSubmit.prompt` may be a string or an array of content parts.
+- `UserPromptSubmit` accepts raw text on stdout. Other lifecycle hooks are
+ silent; `PreToolUse` returns Kimi's `permissionDecision` JSON shape.
+- The stable transcript is the session's `agents/main/wire.jsonl`, located via
+ `session_index.jsonl`. `turn.ended` closes interrupted or tool-only turns.
+ If log rotation removes the acknowledged cursor, capture restarts from the
+ current file and the bounded acknowledgement set suppresses duplicates.
+- Stop, PreCompact, and SessionEnd capture may detach. Interrupt stays
+ synchronous and all of its OpenViking requests share a two-second budget.
+- The native plugin manifest owns hooks and MCP. Installation does not edit
+ legacy `config.toml` or `mcp.json` files.
+
+Shared configuration, recall, capture filtering, retry queues, HTTP, and MCP
+transport remain in `memory-plugin-shared`; `kimicode.mjs` owns only Kimi's
+event mapping, input/output shape, transcript decoding, and commit policy.
+
+Versioned host references:
+
+- [native plugin manifest and manager](https://github.com/MoonshotAI/kimi-code/tree/%40moonshot-ai/kimi-code%400.43.1/packages/agent-core-v2/src/app/plugin)
+- [hook event models](https://github.com/MoonshotAI/kimi-code/tree/%40moonshot-ai/kimi-code%400.43.1/packages/agent-core-v2/src/features/externalHooks)
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
new file mode 100644
index 000000000..77a200db9
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
@@ -0,0 +1,66 @@
+{
+ "name": "openviking-memory",
+ "version": "0.5.0",
+ "description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.",
+ "author": {
+ "name": "OpenViking",
+ "url": "https://github.com/volcengine/OpenViking"
+ },
+ "homepage": "https://github.com/volcengine/OpenViking",
+ "license": "Apache-2.0",
+ "keywords": ["memory", "openviking", "kimi-code", "long-term-memory"],
+ "interface": {
+ "displayName": "OpenViking Memory",
+ "shortDescription": "Recall and capture long-term memory through OpenViking"
+ },
+ "mcpServers": {
+ "openviking": {
+ "command": "node",
+ "args": ["./agent-integrations/kimicode/servers/mcp-proxy.mjs"],
+ "env": {
+ "OPENVIKING_HOOK_SOURCE": "kimicode"
+ }
+ }
+ },
+ "hooks": [
+ {
+ "event": "SessionStart",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs session-start kimicode",
+ "timeout": 30,
+ "env": {
+ "OPENVIKING_PENDING_REPLAY_LIMIT": "2"
+ }
+ },
+ {
+ "event": "UserPromptSubmit",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs user-prompt-submit kimicode",
+ "timeout": 20
+ },
+ {
+ "event": "PreToolUse",
+ "matcher": "Read|Glob|Grep",
+ "command": "node ./agent-integrations/kimicode/scripts/uri-guard.mjs kimicode",
+ "timeout": 5
+ },
+ {
+ "event": "Stop",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs stop kimicode",
+ "timeout": 30
+ },
+ {
+ "event": "PreCompact",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs pre-compact kimicode",
+ "timeout": 30
+ },
+ {
+ "event": "SessionEnd",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs session-end kimicode",
+ "timeout": 30
+ },
+ {
+ "event": "Interrupt",
+ "command": "node ./agent-integrations/kimicode/scripts/hook.mjs interrupt kimicode",
+ "timeout": 10
+ }
+ ]
+}
diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
new file mode 100644
index 000000000..ba53fa7bc
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
@@ -0,0 +1,12 @@
+{
+ "schemaVersion": 1,
+ "id": "openviking-memory",
+ "version": "0.5.0",
+ "clients": [
+ "kimicode"
+ ],
+ "capabilities": [
+ "hooks",
+ "mcp"
+ ]
+}
diff --git a/examples/agent-hook-plugin/hosts/kimicode/runtime-index.mjs b/examples/agent-hook-plugin/hosts/kimicode/runtime-index.mjs
new file mode 100644
index 000000000..0e4e5de5a
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/kimicode/runtime-index.mjs
@@ -0,0 +1,3 @@
+import { kimicode } from "./kimicode.mjs";
+
+export const HOSTS = { kimicode };
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index 92955453a..d7b86edaf 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.4.0",
+ "version": "0.5.0",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode-capture.mjs b/examples/agent-hook-plugin/hosts/zcode-capture.mjs
index 61f416c6b..26bf912fa 100644
--- a/examples/agent-hook-plugin/hosts/zcode-capture.mjs
+++ b/examples/agent-hook-plugin/hosts/zcode-capture.mjs
@@ -1,87 +1,16 @@
-import { stableHash } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { shouldCaptureText } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import {
+ applyIncrementalCaptureResult,
+ buildIncrementalCapturePlan,
+ turnDedupKey,
+} from "./incremental-turn-capture.mjs";
import { cleanZcodeText } from "./zcode-turns.mjs";
-export function zcodeTurnDedupKey(turn) {
- return turn.turnId
- ? `${turn.turnId}:${turn.role}`
- : stableHash(turn.role, turn.content);
-}
+export const zcodeTurnDedupKey = turnDedupKey;
export function buildZcodeCapturePlan(turns, state = {}, cfg = {}) {
- const capturedTurnIds = new Set(
- Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
- );
- const candidates = [];
- for (const turn of turns) {
- const decision = shouldCaptureText(turn.content, turn.role, cfg);
- if (!decision.shouldCapture) continue;
- // The dedup key stays keyed on the raw turn so raising captureMaxLength
- // never resends a turn the server already holds in truncated form.
- candidates.push({ dedupKey: zcodeTurnDedupKey(turn), turn, content: decision.text });
- }
- const toSend = candidates.filter((item) => !capturedTurnIds.has(item.dedupKey));
- const payloads = toSend.map(({ turn, content }) => ({
- role: turn.role,
- content,
- ...(turn.turnId ? { turn_id: turn.turnId } : {}),
- }));
- return { candidates, toSend, payloads };
-}
-
-function acknowledgedCursor(candidates, acknowledged) {
- let cursor = null;
- let currentTurnId = null;
- let currentComplete = true;
-
- for (const item of candidates) {
- const turnId = item.turn.turnId || null;
- if (!turnId) continue;
- if (currentTurnId !== turnId) {
- if (currentTurnId && currentComplete) cursor = currentTurnId;
- if (currentTurnId && !currentComplete) return cursor;
- currentTurnId = turnId;
- currentComplete = true;
- }
- if (!acknowledged.has(item.dedupKey)) currentComplete = false;
- }
-
- if (currentTurnId && currentComplete) cursor = currentTurnId;
- return cursor;
+ return buildIncrementalCapturePlan(turns, state, cfg);
}
export function applyZcodeCaptureResult(state, plan, result) {
- const acknowledged = new Set(
- Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
- );
- const captured = Math.min(
- plan.toSend.length,
- Math.max(0, Number(result?.sent || 0) + Number(result?.queued || 0)),
- );
- const newlyAcknowledged = plan.toSend.slice(0, captured);
- for (const item of newlyAcknowledged) acknowledged.add(item.dedupKey);
-
- const cursor = acknowledgedCursor(plan.candidates, acknowledged);
- const pendingPrompt = cleanZcodeText(state.pendingPrompt?.prompt || "");
- let pendingPromptItem = null;
- if (pendingPrompt) {
- for (let index = plan.candidates.length - 1; index >= 0; index--) {
- const item = plan.candidates[index];
- if (item.turn.role === "user" && cleanZcodeText(item.turn.content) === pendingPrompt) {
- pendingPromptItem = item;
- break;
- }
- }
- }
- const pendingPromptAcknowledged = pendingPromptItem
- ? acknowledged.has(pendingPromptItem.dedupKey)
- : false;
-
- return {
- ...state,
- capturedTurnIds: [...acknowledged].slice(-1000),
- pendingPrompt: pendingPromptAcknowledged ? null : state.pendingPrompt,
- lastTurnId: cursor || state.lastTurnId || null,
- captured,
- };
+ return applyIncrementalCaptureResult(state, plan, result, cleanZcodeText);
}
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index b9b31379e..c44fbac85 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.4.0",
+ "version": "0.5.0",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index f24a30f1a..7e778e8be 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agent-hook-plugin",
- "version": "0.4.0",
- "description": "Long-term semantic memory for the config-driven hook hosts — Cursor, TRAE, TRAE CN and ZCode — powered by OpenViking. Auto-recall relevant memories at session start and capture the conversation as it happens.",
+ "version": "0.5.0",
+ "description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode and Kimi Code — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
"url": "https://github.com/volcengine/OpenViking"
diff --git a/examples/agent-hook-plugin/scripts/hook.mjs b/examples/agent-hook-plugin/scripts/hook.mjs
index ac581a461..8cb393549 100644
--- a/examples/agent-hook-plugin/scripts/hook.mjs
+++ b/examples/agent-hook-plugin/scripts/hook.mjs
@@ -52,7 +52,8 @@ function emit(block) {
if (emitted) return;
emitted = true;
const value = host.envelope(event, block || "");
- if (value) process.stdout.write(`${JSON.stringify(value)}\n`);
+ if (typeof value === "string") process.stdout.write(`${value}\n`);
+ else if (value) process.stdout.write(`${JSON.stringify(value)}\n`);
}
const normalize = (input) => (host.normalizeInput ? host.normalizeInput(input) : input);
@@ -68,6 +69,7 @@ async function sessionStart(ctx) {
if (now - Number(state.lastSessionStartAt || 0) < 2000) return "";
await writeHookState(clientId, ctx.nativeSessionId, { ...state, lastSessionStartAt: now });
await replayAgentPending(ctx.fetchJSON, log).catch((error) => logError("pending", error));
+ if ((host.profileStage || "session-start") !== "session-start") return "";
const profile = await buildAgentProfile(ctx.fetchJSON, ctx.cfg, ctx.cwd).catch((error) => {
logError("profile", error);
return null;
@@ -89,6 +91,16 @@ async function promptSubmit(ctx) {
? state.promptEventId === promptEventId
: state.promptHash === promptHash && now - Number(state.promptAt || 0) < 500;
if (duplicateEvent) return "";
+ const parts = [];
+ let profileInjected = Boolean(state.profileInjected);
+ if (host.profileStage === "first-prompt" && !profileInjected) {
+ const profile = await buildAgentProfile(ctx.fetchJSON, ctx.cfg, ctx.cwd).catch((error) => {
+ logError("profile", error);
+ return null;
+ });
+ if (profile) parts.push(contextBlock("session-start", profile));
+ profileInjected = Boolean(profile);
+ }
const recallBlock = state.promptHash === promptHash && state.recallBlock
? state.recallBlock
: await recallForPrompt(ctx.fetchJSON, ctx.cfg, prompt, ctx.cwd, log, { sessionId: ctx.sessionId })
@@ -96,18 +108,40 @@ async function promptSubmit(ctx) {
logError("recall", error);
return null;
});
+ if (recallBlock) parts.push(recallBlock);
await writeHookState(clientId, ctx.nativeSessionId, {
...state,
promptHash,
promptEventId,
promptAt: now,
recallBlock,
+ ...(host.profileStage === "first-prompt" ? { profileInjected } : {}),
...(host.tracksPendingPrompt ? { pendingPrompt: { prompt, hash: promptHash, at: now } } : {}),
});
- return recallBlock || "";
+ return parts.join("\n\n");
});
}
+function withRequestBudget(fetchJSON, budgetMs) {
+ if (!budgetMs) return fetchJSON;
+ const deadline = Date.now() + budgetMs;
+ return (path, init = {}, options = {}) => {
+ const remaining = deadline - Date.now();
+ // ov-http deliberately clamps individual requests to one second. Do not
+ // start one inside that final second or the host-level total can overrun.
+ if (remaining < 1000) {
+ return Promise.resolve({
+ ok: false,
+ status: 0,
+ result: null,
+ error: { name: "AbortError", aborted: true, message: "hook request budget exhausted" },
+ });
+ }
+ const requested = Number(options.timeoutMs) || remaining;
+ return fetchJSON(path, init, { ...options, timeoutMs: Math.min(requested, remaining) });
+ };
+}
+
async function capture(ctx) {
if (host.capturesOnlyWhenEnabled && !isCaptureEnabled(ctx.cfg)) return "";
await withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
@@ -138,13 +172,14 @@ async function main() {
cfg = resolved;
const payload = normalize(input);
if (!stageName) return "";
+ const baseFetchJSON = makeAgentFetchJSON(cfg, cwd).fetchJSON;
const ctx = {
cfg,
cwd,
input: payload,
nativeSessionId: resolveNativeSessionId(payload),
sessionId: deriveAgentSessionId(host.prefix, payload),
- fetchJSON: makeAgentFetchJSON(cfg, cwd).fetchJSON,
+ fetchJSON: withRequestBudget(baseFetchJSON, host.requestBudgets?.[event]),
log,
logError,
};
diff --git a/examples/agent-hook-plugin/tests/kimicode-turns.test.mjs b/examples/agent-hook-plugin/tests/kimicode-turns.test.mjs
new file mode 100644
index 000000000..dad221c47
--- /dev/null
+++ b/examples/agent-hook-plugin/tests/kimicode-turns.test.mjs
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import {
+ buildKimicodeTurns,
+ cleanKimicodeText,
+ extractUnseenKimicodeTurns,
+} from "../hosts/kimicode-turns.mjs";
+
+test("content parts are normalized and injected context is removed", () => {
+ assert.equal(cleanKimicodeText([
+ { type: "text", text: "hello" },
+ { type: "text", text: "<openviking-context>old</openviking-context>world" },
+ ]), "hello\n world");
+});
+
+test("wire decoding groups prompt and assistant text under a stable turn id", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-kimi-wire-"));
+ const wire = join(dir, "wire.jsonl");
+ writeFileSync(wire, [
+ JSON.stringify({ type: "turn.prompt", input: [{ type: "text", text: "question" }] }),
+ JSON.stringify({ type: "context.append_message", message: { role: "user", content: [{ type: "text", text: "question" }] } }),
+ JSON.stringify({ type: "context.append_loop_event", event: { type: "content.part", turnId: "7", part: { type: "think", think: "hidden" } } }),
+ JSON.stringify({ type: "context.append_loop_event", event: { type: "content.part", turnId: "7", part: { type: "text", text: "answer" } } }),
+ ].join("\n") + "\n");
+
+ assert.deepEqual(extractUnseenKimicodeTurns(wire).turns, [
+ { role: "user", content: "question", turnId: "7" },
+ { role: "assistant", content: "answer", turnId: "7" },
+ ]);
+});
+
+test("turn.ended closes an interrupted user-only turn", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-kimi-wire-"));
+ const wire = join(dir, "wire.jsonl");
+ writeFileSync(wire, [
+ JSON.stringify({ type: "turn.prompt", input: [{ type: "text", text: "cancel me" }] }),
+ JSON.stringify({ type: "turn.ended", turnId: "8", reason: "cancelled" }),
+ ].join("\n") + "\n");
+ assert.deepEqual(extractUnseenKimicodeTurns(wire).turns, [
+ { role: "user", content: "cancel me", turnId: "8" },
+ ]);
+});
+
+test("a missing wire waits for a stable transcript instead of guessing hook fields", () => {
+ const previous = process.env.KIMI_CODE_HOME;
+ process.env.KIMI_CODE_HOME = mkdtempSync(join(tmpdir(), "ov-kimi-home-"));
+ try {
+ assert.deepEqual(buildKimicodeTurns(
+ { session_id: "missing" },
+ { pendingPrompt: { prompt: "question" } },
+ ), { status: "missing", turns: [] });
+ } finally {
+ if (previous === undefined) delete process.env.KIMI_CODE_HOME;
+ else process.env.KIMI_CODE_HOME = previous;
+ }
+});
+
+test("an unreadable wire is distinct from a readable wire with no new turns", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-kimi-wire-"));
+ const unreadable = join(dir, "wire.jsonl");
+ mkdirSync(unreadable);
+ assert.equal(extractUnseenKimicodeTurns(unreadable).status, "unreadable");
+
+ const empty = join(dir, "empty.jsonl");
+ writeFileSync(empty, "");
+ assert.deepEqual(extractUnseenKimicodeTurns(empty), { status: "ok", turns: [] });
+});
+
+test("a rotated wire restarts from its current first turn when the old cursor is absent", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-kimi-wire-"));
+ const wire = join(dir, "wire.jsonl");
+ writeFileSync(wire, [
+ JSON.stringify({ type: "turn.prompt", input: [{ type: "text", text: "new question" }] }),
+ JSON.stringify({
+ type: "context.append_loop_event",
+ event: { type: "content.part", turnId: "12", part: { type: "text", text: "new answer" } },
+ }),
+ ].join("\n") + "\n");
+
+ assert.deepEqual(extractUnseenKimicodeTurns(wire, "rotated-away").turns, [
+ { role: "user", content: "new question", turnId: "12" },
+ { role: "assistant", content: "new answer", turnId: "12" },
+ ]);
+});
diff --git a/examples/agent-hook-plugin/tests/kimicode.test.mjs b/examples/agent-hook-plugin/tests/kimicode.test.mjs
new file mode 100644
index 000000000..ebef9a637
--- /dev/null
+++ b/examples/agent-hook-plugin/tests/kimicode.test.mjs
@@ -0,0 +1,130 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
+const HOOK = join(ROOT, "scripts", "hook.mjs");
+const URI_GUARD = join(ROOT, "scripts", "uri-guard.mjs");
+
+function runScript(script, args, input, env = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [script, ...args], {
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ child.stdin.end(JSON.stringify(input));
+ });
+}
+
+const runHook = (args, input, env) => runScript(HOOK, args, input, env);
+
+test("URI guard emits Kimi's permission decision at the process boundary", async () => {
+ const result = await runScript(URI_GUARD, ["kimicode"], {
+ tool_name: "Read",
+ tool_input: { file_path: "viking://~/memories/profile.md" },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.deepEqual(Object.keys(output.hookSpecificOutput).sort(), [
+ "permissionDecision",
+ "permissionDecisionReason",
+ ]);
+ assert.equal(output.hookSpecificOutput.permissionDecision, "deny");
+});
+
+test("profile retries until success, emits raw text, then injects only once", async (t) => {
+ let profileReads = 0;
+ const server = createServer((request, response) => {
+ const url = new URL(request.url, "http://localhost");
+ let result = {};
+ if (url.pathname.endsWith("/system/status")) result = { user: "default" };
+ else if (url.pathname.endsWith("/content/read")) {
+ profileReads++;
+ result = profileReads === 1 ? {} : "profile line";
+ }
+ else if (url.pathname.endsWith("/fs/ls")) result = [];
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end(JSON.stringify({ result }));
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+ const home = mkdtempSync(join(tmpdir(), "ov-kimi-hook-"));
+ const env = {
+ HOME: home,
+ KIMI_CODE_HOME: home,
+ OPENVIKING_HOOK_STATE_DIR: join(home, "state"),
+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
+ OPENVIKING_AUTO_RECALL: "0",
+ OPENVIKING_SKILL_CATALOG: "0",
+ };
+ const first = await runHook(["user-prompt-submit", "kimicode"], {
+ session_id: "session-1", request_id: "1", cwd: home, prompt: [{ type: "text", text: "hello" }],
+ }, env);
+ assert.equal(first.status, 0, first.stderr);
+ assert.equal(first.stdout, "");
+
+ const second = await runHook(["user-prompt-submit", "kimicode"], {
+ session_id: "session-1", request_id: "2", cwd: home, prompt: [{ type: "text", text: "retry" }],
+ }, env);
+ assert.equal(second.status, 0, second.stderr);
+ assert.match(second.stdout, /^<openviking-context source="session-start">/);
+ assert.doesNotMatch(second.stdout, /^"/);
+ assert.doesNotMatch(second.stdout, /\\n/);
+
+ const third = await runHook(["user-prompt-submit", "kimicode"], {
+ session_id: "session-1", request_id: "3", cwd: home, prompt: [{ type: "text", text: "later" }],
+ }, env);
+ assert.equal(third.status, 0, third.stderr);
+ assert.equal(third.stdout, "");
+ assert.equal(profileReads, 2);
+});
+
+test("Interrupt shares one two-second request budget across capture and commit", async (t) => {
+ let requests = 0;
+ const server = createServer((_request, response) => {
+ requests++;
+ setTimeout(() => {
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end('{"result":{}}');
+ }, 1400);
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+
+ const home = mkdtempSync(join(tmpdir(), "ov-kimi-interrupt-"));
+ const sessionId = "session-budget";
+ const sessionDir = join(home, "sessions", "wd", sessionId);
+ mkdirSync(join(sessionDir, "agents", "main"), { recursive: true });
+ writeFileSync(join(home, "session_index.jsonl"), `${JSON.stringify({ sessionId, sessionDir })}\n`);
+ writeFileSync(join(sessionDir, "agents", "main", "wire.jsonl"), [
+ JSON.stringify({ type: "turn.prompt", input: [{ type: "text", text: "question" }] }),
+ JSON.stringify({ type: "context.append_loop_event", event: { type: "content.part", turnId: "9", part: { type: "text", text: "answer" } } }),
+ ].join("\n") + "\n");
+
+ const started = Date.now();
+ const result = await runHook(["interrupt", "kimicode"], {
+ session_id: sessionId,
+ cwd: home,
+ }, {
+ HOME: home,
+ KIMI_CODE_HOME: home,
+ OPENVIKING_HOOK_STATE_DIR: join(home, "state"),
+ OPENVIKING_PENDING_DIR: join(home, "pending"),
+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
+ OPENVIKING_TIMEOUT_MS: "10000",
+ });
+ const elapsed = Date.now() - started;
+ assert.equal(result.status, 0, result.stderr);
+ assert.ok(elapsed < 2100, `Interrupt took ${elapsed}ms`);
+ assert.equal(requests, 1, "commit started after the remaining budget was below one request quantum");
+});
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index b1cc1a971..bb849192b 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index 2f2de19df..aee029ef6 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs
index e84b0f3dc..4e2efafbd 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs
@@ -243,6 +243,7 @@ export const HARNESS_KEYS = {
claudeCode: "claude_code",
codex: "codex",
cursor: "cursor",
+ kimicode: "kimicode",
trae: "trae",
traeCn: "trae_cn",
zcode: "zcode",
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index a1f2ca775..3b0979f44 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.10.0",
+ "version": "0.10.1",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/scripts/shared/config-schema.mjs b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs
index e84b0f3dc..4e2efafbd 100644
--- a/examples/codex-memory-plugin/scripts/shared/config-schema.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs
@@ -243,6 +243,7 @@ export const HARNESS_KEYS = {
claudeCode: "claude_code",
codex: "codex",
cursor: "cursor",
+ kimicode: "kimicode",
trae: "trae",
traeCn: "trae_cn",
zcode: "zcode",
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
index 4dc131008..6d1646c48 100644
--- a/examples/dsh-memory-plugin/config.mjs
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -1,7 +1,7 @@
import { buildPluginConfig } from "./shared/plugin-config.mjs";
import { loadCredentialFiles } from "./shared/credentials.mjs";
-export const PLUGIN_VERSION = "0.5.0";
+export const PLUGIN_VERSION = "0.5.1";
/**
* Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index 1ed144de9..3b85d39f4 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.0",
+ "version": "0.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.0",
+ "version": "0.5.1",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index 147618219..ce563027b 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.0",
+ "version": "0.5.1",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"type": "module",
"main": "index.mjs",
diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
index 7c411f20c..5aafc02b9 100644
--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs
+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
@@ -74,6 +74,54 @@ function runUninstall(home, harnesses = "cursor,trae,trae-cn,zcode") {
assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
}
+test("Kimi installs a self-contained native bundle without legacy config edits", () => {
+ const home = mkdtempSync(join(tmpdir(), "openviking-kimi-hooks-"));
+ try {
+ writeJson(join(home, ".kimi-code", "plugins", "installed.json"), {
+ version: 1,
+ plugins: [{ id: "third-party", root: "/third-party", enabled: false }],
+ });
+
+ const result = runInstaller(home, [
+ "--harness", "kimicode",
+ "--source", "dev",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:1933",
+ "--api-key", "",
+ "--yes",
+ ]);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+
+ const root = join(home, ".kimi-code", "plugins", "managed", "openviking-memory");
+ const manifest = JSON.parse(readFileSync(join(root, "kimi.plugin.json"), "utf8"));
+ assert.deepEqual(manifest.hooks.map((hook) => hook.event), [
+ "SessionStart", "UserPromptSubmit", "PreToolUse", "Stop", "PreCompact", "SessionEnd", "Interrupt",
+ ]);
+ assert.equal(manifest.hooks[0].env.OPENVIKING_PENDING_REPLAY_LIMIT, "2");
+ assert.match(manifest.mcpServers.openviking.args[0], /agent-integrations\/kimicode\/servers\/mcp-proxy\.mjs$/);
+ assert.ok(existsSync(join(root, "agent-integrations", "kimicode", "scripts", "hook.mjs")));
+ assert.ok(existsSync(join(root, "agent-integrations", "memory-plugin-shared", "lib", "agent-hook-runtime.mjs")));
+ assert.equal(existsSync(join(root, "agent-integrations", "memory-plugin-shared", "lib", "install")), false);
+ assert.equal(existsSync(join(root, "agent-integrations", "kimicode", "tests")), false);
+ assert.equal(existsSync(join(root, "agent-integrations", "kimicode", "hosts", "cursor.mjs")), false);
+ assert.equal(existsSync(join(root, "agent-integrations", "kimicode", "hosts", "zcode.mjs")), false);
+ assert.equal(existsSync(join(home, ".kimi-code", "config.toml")), false);
+ assert.equal(existsSync(join(home, ".kimi-code", "mcp.json")), false);
+
+ const registry = JSON.parse(readFileSync(join(home, ".kimi-code", "plugins", "installed.json"), "utf8"));
+ assert.deepEqual(registry.plugins.map((plugin) => plugin.id).sort(), ["openviking-memory", "third-party"]);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "kimicode", "lib", "install", "kimicode-plugin.mjs")));
+
+ const removed = runInstaller(home, ["--harness", "kimicode", "--uninstall", "--yes"]);
+ assert.equal(removed.status, 0, `${removed.stdout}\n${removed.stderr}`);
+ assert.equal(existsSync(root), false);
+ const after = JSON.parse(readFileSync(join(home, ".kimi-code", "plugins", "installed.json"), "utf8"));
+ assert.deepEqual(after.plugins.map((plugin) => plugin.id), ["third-party"]);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+});
+
test("TraeCode CLI 2.0 installs the Codex plugin alias and removes the deprecated integration", () => {
const home = mkdtempSync(join(tmpdir(), "openviking-trae-cli-hooks-"));
try {
diff --git a/examples/memory-plugin-shared/install-lib-closure.test.mjs b/examples/memory-plugin-shared/install-lib-closure.test.mjs
index db1852581..410947a2c 100644
--- a/examples/memory-plugin-shared/install-lib-closure.test.mjs
+++ b/examples/memory-plugin-shared/install-lib-closure.test.mjs
@@ -18,7 +18,7 @@ import test from "node:test";
import { MANIFEST_PATH, ROOT, assembledClosure, resolveTargets } from "./sync.mjs";
-test("lib/MANIFEST holds the closure of what cursor, trae and zcode import", async () => {
+test("lib/MANIFEST holds the closure of what the thin hook hosts import", async () => {
const manifest = readFileSync(MANIFEST_PATH, "utf8");
assert.ok(manifest.endsWith("\n"), "the installer reads the manifest a line at a time");
assert.deepEqual(
diff --git a/examples/memory-plugin-shared/install-tui.test.mjs b/examples/memory-plugin-shared/install-tui.test.mjs
index 85d4cb0eb..4f5738370 100644
--- a/examples/memory-plugin-shared/install-tui.test.mjs
+++ b/examples/memory-plugin-shared/install-tui.test.mjs
@@ -35,6 +35,7 @@ SEL_PI=1
SEL_CURSOR_APP=1
SEL_TRAE=1
SEL_TRAE_CN=0
+SEL_KIMICODE=0
tui_finish_selection
printf '%s\\n' "$SELECTED_HARNESSES"
`);
diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.sh
index 50773c5db..e373f7649 100644
--- a/examples/memory-plugin-shared/install.sh
+++ b/examples/memory-plugin-shared/install.sh
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
#
# OpenViking Memory Plugin shared installer for Claude Code, Codex, Cursor,
-# TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, OpenCode, and pi.
+# TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, Kimi Code, OpenCode, and pi.
#
# One-liner (GitHub):
# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
# One-liner (TOS mirror, for regions where GitHub is unreachable):
# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos
# Non-interactive:
-# bash install.sh --harness claude,codex,cursor,trae,trae-cn,trae-cli,zcode,opencode,pi,dsh --dist github --lang en --url http://127.0.0.1:1933
+# bash install.sh --harness claude,codex,cursor,trae,trae-cn,trae-cli,zcode,kimicode,opencode,pi,dsh --dist github --lang en --url http://127.0.0.1:1933
# Format-compatible CLI aliases:
# bash install.sh --harness trae-cli
# bash install.sh --harness claude --claude-bin claude,seed
@@ -143,7 +143,7 @@ usage() {
Usage: install.sh [options]
Options:
- --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh.
+ --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, opencode, pi, dsh.
Use trae-cli for TraeCode CLI 2.0 (installed through its Codex-compatible plugin format).
--claude-bin LIST Comma-separated Claude-format CLI commands (default: claude).
--codex-bin LIST Comma-separated Codex-format CLI commands (default: codex).
@@ -157,7 +157,7 @@ Options:
--user ID Optional OpenViking user.
--statusline Register the Claude Code statusline without asking.
--no-statusline Skip the statusline prompt.
- --uninstall Remove Cursor/TRAE/TRAE CN/ZCode integration files and config,
+ --uninstall Remove Cursor/TRAE/TRAE CN/ZCode/Kimi Code integration files and config,
plus any legacy TraeCode CLI hook config.
For Codex-format plugins, use the client's plugin uninstall command.
--yes, -y Use defaults for prompts when possible.
@@ -382,7 +382,7 @@ EOF
}
refresh_available_harnesses() {
- HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_TRAE_CLI=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0; HAVE_DSH=0
+ HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_TRAE_CLI=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0; HAVE_KIMICODE=0; HAVE_DSH=0
has_available_bin "$CLAUDE_BINS" && HAVE_CLAUDE=1
has_available_bin "$CODEX_BINS" && HAVE_CODEX=1
{ command -v cursor >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1 || [ -d "/Applications/Cursor.app" ] || [ -d "$HOME/.cursor" ]; } && HAVE_CURSOR=1
@@ -393,6 +393,7 @@ refresh_available_harnesses() {
command -v pi >/dev/null 2>&1 && HAVE_PI=1
command -v dsh >/dev/null 2>&1 && HAVE_DSH=1
{ command -v zcode >/dev/null 2>&1 || [ -d "$HOME/.zcode" ]; } && HAVE_ZCODE=1
+ { command -v kimi >/dev/null 2>&1 || [ -d "$HOME/.kimi-code" ]; } && HAVE_KIMICODE=1
return 0
}
@@ -543,7 +544,7 @@ EOF
}
tui_selectable_count() {
- printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 7 ))
+ printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 8 ))
}
tui_total_count() {
@@ -579,6 +580,8 @@ EOF
if [ "$i" -eq "$idx" ]; then printf 'trae-cn|trae-cn'; return 0; fi
i=$((i + 1))
if [ "$i" -eq "$idx" ]; then printf 'zcode|zcode'; return 0; fi
+ i=$((i + 1))
+ if [ "$i" -eq "$idx" ]; then printf 'kimicode|kimi'; return 0; fi
printf 'add|'
}
@@ -611,6 +614,7 @@ tui_bin_label() {
trae:*) printf 'TRAE' ;;
trae-cn:*) printf 'TRAE CN' ;;
zcode:*) printf 'ZCode' ;;
+ kimicode:*) printf 'Kimi Code' ;;
claude:*) printf '%s %s' "$bin" "$(t '(Claude-format)' '(Claude 格式)')" ;;
codex:*) printf '%s %s' "$bin" "$(t '(Codex-format)' '(Codex 格式)')" ;;
esac
@@ -634,8 +638,10 @@ tui_bin_selected() {
[ "$SEL_TRAE" -eq 1 ]
elif [ "$kind" = "trae-cn" ]; then
[ "$SEL_TRAE_CN" -eq 1 ]
- else
+ elif [ "$kind" = "zcode" ]; then
[ "$SEL_ZCODE" -eq 1 ]
+ else
+ [ "$SEL_KIMICODE" -eq 1 ]
fi
}
@@ -645,6 +651,7 @@ tui_bin_detected() { # tui_bin_detected <kind> <bin>
trae) [ "$HAVE_TRAE" -eq 1 ] ;;
trae-cn) [ "$HAVE_TRAE_CN" -eq 1 ] ;;
zcode) [ "$HAVE_ZCODE" -eq 1 ] ;;
+ kimicode) [ "$HAVE_KIMICODE" -eq 1 ] ;;
*) command -v "$2" >/dev/null 2>&1 ;;
esac
}
@@ -659,6 +666,7 @@ tui_set_all_bins() {
SEL_TRAE=1
SEL_TRAE_CN=1
SEL_ZCODE=1
+ SEL_KIMICODE=1
}
tui_toggle_bin() {
@@ -682,8 +690,10 @@ tui_toggle_bin() {
SEL_TRAE=$((1 - SEL_TRAE)); return 0
elif [ "$kind" = "trae-cn" ]; then
SEL_TRAE_CN=$((1 - SEL_TRAE_CN)); return 0
- else
+ elif [ "$kind" = "zcode" ]; then
SEL_ZCODE=$((1 - SEL_ZCODE)); return 0
+ else
+ SEL_KIMICODE=$((1 - SEL_KIMICODE)); return 0
fi
if list_contains_line "$selected" "$bin"; then
while IFS= read -r item; do
@@ -754,6 +764,7 @@ tui_reset_bin_selection() {
SEL_TRAE=0
SEL_TRAE_CN=0
SEL_ZCODE=0
+ SEL_KIMICODE=0
while IFS= read -r bin; do
[ -n "$bin" ] || continue
if command -v "$bin" >/dev/null 2>&1; then
@@ -779,6 +790,7 @@ EOF
if [ "$HAVE_TRAE" -eq 1 ]; then SEL_TRAE=1; any=1; fi
if [ "$HAVE_TRAE_CN" -eq 1 ]; then SEL_TRAE_CN=1; any=1; fi
if [ "$HAVE_ZCODE" -eq 1 ]; then SEL_ZCODE=1; any=1; fi
+ if [ "$HAVE_KIMICODE" -eq 1 ]; then SEL_KIMICODE=1; any=1; fi
if [ "$any" -ne 1 ]; then
SEL_CLAUDE_BINS="$TUI_CLAUDE_BINS"
SEL_CODEX_BINS="$TUI_CODEX_BINS"
@@ -866,7 +878,8 @@ tui_add_compatible_cli() {
tui_has_selection() {
[ -n "$(list_words "$SEL_CLAUDE_BINS")" ] || [ -n "$(list_words "$SEL_CODEX_BINS")" ] \
|| [ "$SEL_OPENCODE" -eq 1 ] || [ "$SEL_PI" -eq 1 ] || [ "$SEL_DSH" -eq 1 ] || [ "$SEL_CURSOR_APP" -eq 1 ] \
- || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ] || [ "$SEL_ZCODE" -eq 1 ]
+ || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ] || [ "$SEL_ZCODE" -eq 1 ] \
+ || [ "$SEL_KIMICODE" -eq 1 ]
}
tui_finish_selection() {
@@ -882,6 +895,7 @@ tui_finish_selection() {
[ "$SEL_TRAE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae"
[ "$SEL_TRAE_CN" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae-cn"
[ "$SEL_ZCODE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}zcode"
+ [ "$SEL_KIMICODE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}kimicode"
return 0
}
@@ -954,6 +968,7 @@ select_harnesses() {
[ "$HAVE_PI" -eq 1 ] && detected="${detected:+$detected,}pi"
[ "$HAVE_DSH" -eq 1 ] && detected="${detected:+$detected,}dsh"
[ "$HAVE_ZCODE" -eq 1 ] && detected="${detected:+$detected,}zcode"
+ [ "$HAVE_KIMICODE" -eq 1 ] && detected="${detected:+$detected,}kimicode"
if [ -n "$REQUESTED_HARNESSES" ]; then
SELECTED_HARNESSES="$REQUESTED_HARNESSES"
@@ -1107,7 +1122,7 @@ validate_selected_harnesses() {
local h bad=0
while IFS= read -r h; do
case "$h" in
- claude|codex|cursor|trae|trae-cn|opencode|pi|zcode|dsh) ;;
+ claude|codex|cursor|trae|trae-cn|opencode|pi|zcode|kimicode|dsh) ;;
trae-cli) [ "$UNINSTALL" -eq 1 ] || bad=1 ;;
*) err "Unsupported harness: $h"; bad=1 ;;
esac
@@ -1148,7 +1163,7 @@ EOF
if contains_harness dsh && command -v dsh >/dev/null 2>&1; then ok=1; fi
# Cursor and TRAE are config-driven integrations. They may be installed
# before the desktop app itself, so a CLI in PATH is not required.
- if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness trae-cli || contains_harness zcode; then ok=1; fi
+ if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness trae-cli || contains_harness zcode || contains_harness kimicode; then ok=1; fi
if [ "$ok" -ne 1 ]; then
err "$(t 'No selected compatible CLI command was found in PATH.' '未在 PATH 中找到任何已选择的兼容 CLI 命令。')"
exit 2
@@ -1928,15 +1943,15 @@ install_codex_tos_git() {
# Cursor / TRAE lifecycle hooks
# ---------------------------------------------------------------------------
-AGENT_HOOK_HOSTS="cursor trae zcode"
+AGENT_HOOK_HOSTS="cursor trae zcode kimicode"
-copy_agent_integration() { # copy_agent_integration <host> <dest-name>
- local host="$1" dest_name="$2" source dest tmp other
+copy_agent_integration() { # copy_agent_integration <host> <dest-name> [destination]
+ local host="$1" dest_name="$2" explicit_dest="${3:-}" source dest tmp other
source="$(plugin_dir_on_disk agent-hook-plugin)" || {
err "$(t 'Agent integration sources not found:' '未找到 Agent 接入源码:') agent-hook-plugin"
return 1
}
- dest="$OV_HOME/agent-integrations/$dest_name"
+ dest="${explicit_dest:-$OV_HOME/agent-integrations/$dest_name}"
tmp="$dest.tmp"
rm -rf "$tmp"
mkdir -p "$tmp"
@@ -1956,18 +1971,24 @@ copy_agent_integration() { # copy_agent_integration <host> <dest-name>
printf '%s' "$dest"
}
-# Cursor, TRAE and ZCode keep only their client-specific adapters in the repository.
+# Thin hook hosts keep only their client-specific adapters in the repository.
# Assemble a self-contained installation by adding the canonical shared runtime
# at install time instead of committing generated copies for every client.
-assemble_agent_integration() { # assemble_agent_integration <host> <dest-name>
- local host="$1" dest_name="$2" root shared shared_dest manifest file
- root="$(copy_agent_integration "$host" "$dest_name")" || return 1
+assemble_agent_integration() { # assemble_agent_integration <host> <dest-name> [bundle-root]
+ local host="$1" dest_name="$2" bundle_root="${3:-}" root_dest root shared shared_dest manifest file
+ if [ -n "$bundle_root" ]; then
+ root_dest="$bundle_root/agent-integrations/$dest_name"
+ shared_dest="$bundle_root/agent-integrations/memory-plugin-shared/lib"
+ else
+ root_dest="$OV_HOME/agent-integrations/$dest_name"
+ shared_dest="$OV_HOME/agent-integrations/memory-plugin-shared/lib"
+ fi
+ root="$(copy_agent_integration "$host" "$dest_name" "$root_dest")" || return 1
shared="$(plugin_dir_on_disk memory-plugin-shared)" || {
err "$(t 'Shared agent runtime not found.' '未找到共享 Agent 运行时。')"
return 1
}
- shared_dest="$OV_HOME/agent-integrations/memory-plugin-shared/lib"
- # The closure of what cursor, trae and zcode import, written by sync.mjs and
+ # The closure of what the hook hosts import, written by sync.mjs and
# shipped beside the modules. Regenerating it here is not an option: the
# generator finds no plugin sources in a flat marketplace archive.
manifest="$shared/lib/MANIFEST"
@@ -1982,9 +2003,12 @@ assemble_agent_integration() { # assemble_agent_integration <host> <dest-name>
cp "$shared/lib/$file" "$shared_dest.tmp/$file" || return 1
done < "$manifest"
cp "$manifest" "$shared_dest.tmp/MANIFEST"
- # Not part of the closure and never imported by a hook; it is here so that an
- # uninstall piped from a URL can reclaim this host's entries without a source.
- cp -R "$shared/lib/install" "$shared_dest.tmp/install" || return 1
+ # Config-driven installs retain the uninstall helpers beside the shared
+ # runtime. A native Kimi bundle persists its one helper outside the plugin,
+ # so carrying every installer module inside that bundle would be dead weight.
+ if [ -z "$bundle_root" ]; then
+ cp -R "$shared/lib/install" "$shared_dest.tmp/install" || return 1
+ fi
rm -rf "$shared_dest"
mkdir -p "$(dirname "$shared_dest")"
mv "$shared_dest.tmp" "$shared_dest"
@@ -2100,11 +2124,44 @@ CLEAN_NODE
rm -rf "$OV_HOME/agent-integrations/zcode"
info "$(t 'Removed ZCode OpenViking hooks and MCP config.' '已移除 ZCode OpenViking hooks 与 MCP 配置。')"
fi
+ if contains_harness kimicode; then
+ local kimi_home="${KIMI_CODE_HOME:-$HOME/.kimi-code}" kimicode_lib kimicode_installed
+ kimicode_lib="$OV_HOME/agent-integrations/kimicode/lib/install"
+ kimicode_installed="$($NODE_BIN - "$kimi_home" <<'NODE'
+const fs = require("node:fs");
+const path = require("node:path");
+const file = path.join(process.argv[2], "plugins", "installed.json");
+if (!fs.existsSync(file)) process.stdout.write("no");
+else {
+ try {
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
+ process.stdout.write(Array.isArray(value.plugins)
+ && value.plugins.some((plugin) => plugin?.id === "openviking-memory") ? "yes" : "no");
+ } catch { process.stdout.write("invalid"); }
+}
+NODE
+)"
+ [ -e "$kimi_home/plugins/managed/openviking-memory" ] && kimicode_installed="yes"
+ if [ "$kimicode_installed" = "invalid" ]; then
+ err "$(t 'Kimi Code plugin registry is invalid; refusing to overwrite it.' 'Kimi Code 插件注册表无效,拒绝覆盖。')"
+ return 1
+ fi
+ if [ "$kimicode_installed" = "yes" ]; then
+ [ -f "$kimicode_lib/kimicode-plugin.mjs" ] || {
+ err "$(t 'Kimi Code uninstall runtime is missing.' 'Kimi Code 卸载运行时缺失。')"
+ return 1
+ }
+ "$NODE_BIN" "$kimicode_lib/kimicode-plugin.mjs" remove "$kimi_home" || return 1
+ fi
+ rm -rf "$OV_HOME/agent-integrations/kimicode"
+ info "$(t 'Removed the native Kimi Code plugin.' '已移除 Kimi Code 原生插件。')"
+ fi
if [ ! -d "$OV_HOME/agent-integrations/cursor" ] \
&& [ ! -d "$OV_HOME/agent-integrations/trae" ] \
&& [ ! -d "$OV_HOME/agent-integrations/trae-cn" ] \
&& [ ! -d "$OV_HOME/agent-integrations/trae-cli" ] \
- && [ ! -d "$OV_HOME/agent-integrations/zcode" ]; then
+ && [ ! -d "$OV_HOME/agent-integrations/zcode" ] \
+ && [ ! -d "$OV_HOME/agent-integrations/kimicode" ]; then
rm -rf "$OV_HOME/agent-integrations/memory-plugin-shared"
fi
}
@@ -2193,6 +2250,64 @@ install_zcode() {
info "$(t 'ZCode MCP installed:' 'ZCode MCP 已安装:') $config_path (mcp.servers)"
}
+install_kimicode() {
+ heading "$(t 'Kimi Code CLI integration' 'Kimi Code CLI 集成')"
+ local bundle kimi_home install_lib persisted_dir persisted_tmp persisted_backup root
+ bundle="$OV_HOME/agent-integrations/kimicode-bundle.$$"
+ rm -rf "$bundle"
+ mkdir -p "$bundle"
+ root="$(assemble_agent_integration kimicode kimicode "$bundle")" || {
+ rm -rf "$bundle"
+ return 1
+ }
+ rm -rf "$root/tests"
+ rm -f "$root/README.md" "$root/README_CN.md" "$root/DESIGN.md" "$root/plugin.json"
+ cp "$root/hosts/kimicode/kimi.plugin.json" "$bundle/kimi.plugin.json" || {
+ rm -rf "$bundle"
+ return 1
+ }
+ cp "$root/hosts/kimicode/runtime-index.mjs" "$root/hosts/index.mjs" || {
+ rm -rf "$bundle"
+ return 1
+ }
+ local host_module
+ for host_module in "$root"/hosts/*.mjs; do
+ case "$(basename "$host_module")" in
+ index.mjs|incremental-turn-capture.mjs|kimicode.mjs|kimicode-turns.mjs) ;;
+ *) rm -f "$host_module" ;;
+ esac
+ done
+ rm -rf "$root/hosts/kimicode"
+ kimi_home="${KIMI_CODE_HOME:-$HOME/.kimi-code}"
+ install_lib="$(require_install_lib_dir)" || { rm -rf "$bundle"; return 1; }
+ persisted_dir="$OV_HOME/agent-integrations/kimicode/lib/install"
+ persisted_tmp="$persisted_dir.tmp.$$"
+ persisted_backup="$persisted_dir.previous.$$"
+ rm -rf "$persisted_tmp"
+ mkdir -p "$persisted_tmp"
+ cp "$install_lib/kimicode-plugin.mjs" "$persisted_tmp/kimicode-plugin.mjs" || {
+ rm -rf "$bundle" "$persisted_tmp"
+ return 1
+ }
+ mkdir -p "$(dirname "$persisted_dir")"
+ rm -rf "$persisted_backup"
+ [ ! -e "$persisted_dir" ] || mv "$persisted_dir" "$persisted_backup"
+ mv "$persisted_tmp" "$persisted_dir" || {
+ [ ! -e "$persisted_backup" ] || mv "$persisted_backup" "$persisted_dir"
+ rm -rf "$bundle"
+ return 1
+ }
+ "$NODE_BIN" "$persisted_dir/kimicode-plugin.mjs" install "$kimi_home" "$bundle" || {
+ rm -rf "$bundle" "$persisted_dir"
+ [ ! -e "$persisted_backup" ] || mv "$persisted_backup" "$persisted_dir"
+ return 1
+ }
+ rm -rf "$persisted_backup"
+ rm -rf "$bundle"
+ info "$(t 'Kimi Code native plugin installed:' 'Kimi Code 原生插件已安装:') openviking-memory"
+ info "$(t 'Run /reload or start a new session to activate it.' '请运行 /reload 或新建会话以启用。')"
+}
+
install_trae_variant() { # install_trae_variant <trae|trae-cn>
local client_id="$1" root hooks_path mcp_path
root="$(assemble_agent_integration trae "$client_id")" || return 1
@@ -2550,6 +2665,30 @@ EOF
ok=0; agent_fatal=1
fi
fi
+ if contains_harness kimicode; then
+ local kimi_home="${KIMI_CODE_HOME:-$HOME/.kimi-code}"
+ local kimi_root="$kimi_home/plugins/managed/openviking-memory"
+ local kimi_installer="$OV_HOME/agent-integrations/kimicode/lib/install/kimicode-plugin.mjs"
+ if [ -f "$kimi_installer" ] \
+ && "$NODE_BIN" "$kimi_installer" verify "$kimi_home" \
+ && [ -f "$kimi_root/kimi.plugin.json" ] \
+ && [ -f "$kimi_root/agent-integrations/kimicode/scripts/hook.mjs" ] \
+ && [ -f "$kimi_root/agent-integrations/kimicode/scripts/uri-guard.mjs" ] \
+ && [ -f "$kimi_root/agent-integrations/kimicode/servers/mcp-proxy.mjs" ] \
+ && [ -f "$kimi_root/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
+ "$NODE_BIN" --check "$kimi_root/agent-integrations/kimicode/scripts/hook.mjs" \
+ || { ok=0; agent_fatal=1; }
+ if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
+ "$NODE_BIN" "$kimi_root/agent-integrations/kimicode/scripts/hook.mjs" session-start kimicode >/dev/null; then
+ warn "kimicode: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
+ ok=0; agent_fatal=1
+ fi
+ info "kimicode: $(t 'native plugin installed (Hooks + MCP)' '原生插件已安装(Hooks + MCP)')"
+ else
+ warn "kimicode: $(t 'native plugin installation is incomplete' '原生插件安装不完整')"
+ ok=0; agent_fatal=1
+ fi
+ fi
if contains_harness opencode; then
local ocfg="$HOME/.config/opencode/opencode.json"
local ocfgc="$HOME/.config/opencode/opencode.jsonc"
@@ -2691,6 +2830,7 @@ if contains_harness cursor; then install_cursor; fi
if contains_harness trae; then install_trae_variant trae; fi
if contains_harness trae-cn; then install_trae_variant trae-cn; fi
if contains_harness zcode; then install_zcode; fi
+if contains_harness kimicode; then install_kimicode; fi
if contains_harness opencode; then install_opencode; fi
if contains_harness pi; then install_pi; fi
if contains_harness dsh; then install_dsh; fi
@@ -2712,6 +2852,7 @@ if contains_harness cursor; then info "Cursor: Hooks + MCP + Rule + Skill"; fi
if contains_harness trae; then info "TRAE: ~/.trae/hooks.json + MCP"; fi
if contains_harness trae-cn; then info "TRAE CN: ~/.trae-cn/hooks.json + MCP"; fi
if contains_harness zcode; then info "ZCode: ~/.zcode/cli/config.json (hooks + MCP)"; fi
+if contains_harness kimicode; then info "Kimi Code: native plugin (hooks + MCP)"; fi
if contains_harness opencode; then info "OpenCode: @openviking/opencode-plugin"; fi
if contains_harness pi; then info "pi: ~/.pi/agent/extensions/openviking"; fi
if contains_harness dsh; then info "DeepSeek Harness: $DSH_PACKAGE ($(t 'profile' '配置档') ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT})"; fi
diff --git a/examples/memory-plugin-shared/lib/config-schema.mjs b/examples/memory-plugin-shared/lib/config-schema.mjs
index 156f90895..f8af41d62 100644
--- a/examples/memory-plugin-shared/lib/config-schema.mjs
+++ b/examples/memory-plugin-shared/lib/config-schema.mjs
@@ -242,6 +242,7 @@ export const HARNESS_KEYS = {
claudeCode: "claude_code",
codex: "codex",
cursor: "cursor",
+ kimicode: "kimicode",
trae: "trae",
traeCn: "trae_cn",
zcode: "zcode",
diff --git a/examples/memory-plugin-shared/lib/install/kimicode-plugin.mjs b/examples/memory-plugin-shared/lib/install/kimicode-plugin.mjs
new file mode 100644
index 000000000..e7555ef23
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/install/kimicode-plugin.mjs
@@ -0,0 +1,120 @@
+#!/usr/bin/env node
+
+import { existsSync } from "node:fs";
+import { cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { join, resolve } from "node:path";
+
+const PLUGIN_ID = "openviking-memory";
+async function readJson(file) {
+ return JSON.parse(await readFile(file, "utf8"));
+}
+
+async function readRegistry(kimiHome) {
+ const file = join(kimiHome, "plugins", "installed.json");
+ if (!existsSync(file)) return { version: 1, plugins: [] };
+ const value = await readJson(file);
+ if (!value || !Array.isArray(value.plugins)) {
+ throw new Error(`invalid Kimi plugin registry: ${file}`);
+ }
+ return value;
+}
+
+async function writeRegistry(kimiHome, value) {
+ const pluginsDir = join(kimiHome, "plugins");
+ await mkdir(pluginsDir, { recursive: true });
+ const file = join(pluginsDir, "installed.json");
+ const temporary = `${file}.${process.pid}.tmp`;
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, "utf8");
+ await rename(temporary, file);
+}
+
+async function install(kimiHome, source) {
+ const sourceRoot = resolve(source);
+ const manifest = await readJson(join(sourceRoot, "kimi.plugin.json"));
+ if (manifest.name !== PLUGIN_ID) {
+ throw new Error(`expected plugin name ${PLUGIN_ID}, got ${String(manifest.name)}`);
+ }
+
+ const managedDir = join(kimiHome, "plugins", "managed");
+ const managedRoot = join(managedDir, PLUGIN_ID);
+ await mkdir(managedDir, { recursive: true });
+ const registry = await readRegistry(kimiHome);
+ const existing = registry.plugins.find((plugin) => plugin.id === PLUGIN_ID);
+ const stagingRoot = await mkdtemp(join(managedDir, `${PLUGIN_ID}-`));
+ const previousRoot = `${stagingRoot}-previous`;
+ let previousMoved = false;
+ try {
+ await cp(sourceRoot, stagingRoot, { recursive: true });
+ try {
+ await rename(managedRoot, previousRoot);
+ previousMoved = true;
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ await rename(stagingRoot, managedRoot);
+ const now = new Date().toISOString();
+ const record = {
+ ...(existing || {}),
+ id: PLUGIN_ID,
+ root: managedRoot,
+ source: "local-path",
+ enabled: existing?.enabled ?? true,
+ installedAt: existing?.installedAt || now,
+ updatedAt: now,
+ };
+ // The unified installer deletes its staging bundle after this helper exits.
+ // Do not preserve a stale originalSource from this or an earlier install.
+ delete record.originalSource;
+ await writeRegistry(kimiHome, {
+ ...registry,
+ version: registry.version || 1,
+ plugins: [...registry.plugins.filter((plugin) => plugin.id !== PLUGIN_ID), record],
+ });
+ } catch (error) {
+ await rm(managedRoot, { recursive: true, force: true });
+ if (previousMoved) await rename(previousRoot, managedRoot);
+ else await rm(stagingRoot, { recursive: true, force: true });
+ throw error;
+ }
+ if (previousMoved) await rm(previousRoot, { recursive: true, force: true }).catch(() => {});
+}
+
+async function remove(kimiHome) {
+ const registry = await readRegistry(kimiHome);
+ await writeRegistry(kimiHome, {
+ ...registry,
+ version: registry.version || 1,
+ plugins: registry.plugins.filter((plugin) => plugin.id !== PLUGIN_ID),
+ });
+ await rm(join(kimiHome, "plugins", "managed", PLUGIN_ID), { recursive: true, force: true });
+}
+
+async function verify(kimiHome) {
+ const registry = await readRegistry(kimiHome);
+ const root = join(kimiHome, "plugins", "managed", PLUGIN_ID);
+ return registry.plugins.some((plugin) => plugin.id === PLUGIN_ID && plugin.root === root)
+ && existsSync(join(root, "kimi.plugin.json"));
+}
+
+async function main(argv) {
+ const [action, kimiHomeArg, source] = argv;
+ if (!action || !kimiHomeArg) {
+ throw new Error("usage: kimicode-plugin.mjs <install|remove|verify> <kimi-home> [source]");
+ }
+ const kimiHome = resolve(kimiHomeArg);
+ if (action === "install") {
+ if (!source) throw new Error("install requires a plugin source directory");
+ await install(kimiHome, source);
+ } else if (action === "remove") {
+ await remove(kimiHome);
+ } else if (action === "verify") {
+ if (!(await verify(kimiHome))) process.exitCode = 1;
+ } else {
+ throw new Error(`unknown action: ${action}`);
+ }
+}
+
+main(process.argv.slice(2)).catch((error) => {
+ process.stderr.write(`${error?.message || error}\n`);
+ process.exitCode = 1;
+});
diff --git a/examples/memory-plugin-shared/lib/install/kimicode-plugin.test.mjs b/examples/memory-plugin-shared/lib/install/kimicode-plugin.test.mjs
new file mode 100644
index 000000000..ebd0b268b
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/install/kimicode-plugin.test.mjs
@@ -0,0 +1,101 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { existsSync } from "node:fs";
+import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const script = fileURLToPath(new URL("./kimicode-plugin.mjs", import.meta.url));
+
+function run(...args) {
+ return new Promise((resolve) => {
+ execFile(process.execPath, [script, ...args], (error, stdout, stderr) => {
+ resolve({ code: error?.code || 0, stdout, stderr });
+ });
+ });
+}
+
+test("install preserves unrelated records and remove deletes only OpenViking", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ov-kimi-install-"));
+ const source = join(root, "source");
+ const home = join(root, "home");
+ await mkdir(source, { recursive: true });
+ await mkdir(join(home, "plugins"), { recursive: true });
+ await writeFile(join(source, "kimi.plugin.json"), JSON.stringify({ name: "openviking-memory" }));
+ await writeFile(join(source, "marker"), "new");
+ await writeFile(join(home, "plugins", "installed.json"), JSON.stringify({
+ version: 2,
+ plugins: [
+ { id: "someone-else", root: "/third-party", enabled: false },
+ {
+ id: "openviking-memory",
+ root: "/stale-managed-copy",
+ source: "local-path",
+ originalSource: "/deleted-staging-bundle",
+ enabled: false,
+ installedAt: "2026-01-01T00:00:00.000Z",
+ },
+ ],
+ }));
+
+ const installed = await run("install", home, source);
+ assert.equal(installed.code, 0, installed.stderr);
+ let registry = JSON.parse(await readFile(join(home, "plugins", "installed.json"), "utf8"));
+ assert.equal(registry.version, 2);
+ assert.equal(registry.plugins.find((item) => item.id === "someone-else").enabled, false);
+ const ours = registry.plugins.find((item) => item.id === "openviking-memory");
+ assert.equal(ours.enabled, false);
+ assert.equal(ours.installedAt, "2026-01-01T00:00:00.000Z");
+ assert.equal("originalSource" in ours, false);
+ assert.equal(existsSync(join(ours.root, "marker")), true);
+
+ const removed = await run("remove", home);
+ assert.equal(removed.code, 0, removed.stderr);
+ registry = JSON.parse(await readFile(join(home, "plugins", "installed.json"), "utf8"));
+ assert.deepEqual(registry.plugins.map((item) => item.id), ["someone-else"]);
+ assert.equal(existsSync(ours.root), false);
+});
+
+test("invalid registry fails loudly without overwriting it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ov-kimi-invalid-"));
+ const source = join(root, "source");
+ const home = join(root, "home");
+ await mkdir(source, { recursive: true });
+ await mkdir(join(home, "plugins"), { recursive: true });
+ await writeFile(join(source, "kimi.plugin.json"), JSON.stringify({ name: "openviking-memory" }));
+ const registry = join(home, "plugins", "installed.json");
+ await writeFile(registry, "{invalid");
+ const result = await run("install", home, source);
+ assert.notEqual(result.code, 0);
+ assert.equal(await readFile(registry, "utf8"), "{invalid");
+});
+
+test("a registry write failure restores the previous managed copy", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ov-kimi-rollback-"));
+ const source = join(root, "source");
+ const home = join(root, "home");
+ const plugins = join(home, "plugins");
+ const managed = join(plugins, "managed");
+ const installed = join(managed, "openviking-memory");
+ await mkdir(source, { recursive: true });
+ await mkdir(installed, { recursive: true });
+ await writeFile(join(source, "kimi.plugin.json"), JSON.stringify({ name: "openviking-memory" }));
+ await writeFile(join(source, "marker"), "new");
+ await writeFile(join(installed, "marker"), "old");
+ const registry = join(plugins, "installed.json");
+ const originalRegistry = JSON.stringify({
+ version: 1,
+ plugins: [{ id: "openviking-memory", root: installed, enabled: true }],
+ });
+ await writeFile(registry, originalRegistry);
+
+ await chmod(plugins, 0o555);
+ const result = await run("install", home, source);
+ await chmod(plugins, 0o755);
+
+ assert.notEqual(result.code, 0);
+ assert.equal(await readFile(join(installed, "marker"), "utf8"), "old");
+ assert.equal(await readFile(registry, "utf8"), originalRegistry);
+});
diff --git a/examples/memory-plugin-shared/plugin-config.test.mjs b/examples/memory-plugin-shared/plugin-config.test.mjs
index d0236fb27..a6c3d656d 100644
--- a/examples/memory-plugin-shared/plugin-config.test.mjs
+++ b/examples/memory-plugin-shared/plugin-config.test.mjs
@@ -55,6 +55,7 @@ const LOADERS = {
trae: { harness: "trae", load: (cwd) => loadAgentHookConfig("trae", cwd), options: { logFile: "trae-hooks.log" }, owns: [] },
trae_cn: { harness: "trae-cn", load: (cwd) => loadAgentHookConfig("trae-cn", cwd), options: { logFile: "trae-cn-hooks.log" }, owns: [] },
zcode: { harness: "zcode", load: (cwd) => loadAgentHookConfig("zcode", cwd), options: { logFile: "zcode-hooks.log" }, owns: [] },
+ kimicode: { harness: "kimicode", load: (cwd) => loadAgentHookConfig("kimicode", cwd), options: { logFile: "kimicode-hooks.log" }, owns: [] },
};
// openclaw declares its own settings in TypeScript and still resolves them
diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjs
index 3974a6779..3d3fe7e3b 100644
--- a/examples/memory-plugin-shared/release-marketplace.test.mjs
+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs
@@ -100,6 +100,31 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
const bin = join(tmp, "bin");
mkdirSync(bin);
+ writeFileSync(join(bin, "kimi"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
+ const kimiInstalled = run("bash", [
+ installer,
+ "--harness", "kimicode",
+ "--dist", "tos",
+ "--source", "archive",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:1933",
+ "--api-key", "",
+ "--yes",
+ ], {
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: `${bin}:${process.env.PATH}`,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(tmp, "memory-plugin-marketplace.zip")}`,
+ },
+ });
+ assert.equal(kimiInstalled.status, 0, kimiInstalled.stdout + kimiInstalled.stderr);
+ const kimiRoot = join(home, ".kimi-code", "plugins", "managed", "openviking-memory");
+ assert.ok(existsSync(join(kimiRoot, "kimi.plugin.json")));
+ assert.ok(existsSync(join(kimiRoot, "agent-integrations", "kimicode", "scripts", "hook.mjs")));
+ assert.ok(existsSync(join(kimiRoot, "agent-integrations", "memory-plugin-shared", "lib", "agent-hook-runtime.mjs")));
+
writeFileSync(join(bin, "pi"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const piArgs = [installer, "--harness", "pi", "--dist", "tos", "--source", "archive",
"--lang", "en", "--url", "http://127.0.0.1:1933", "--api-key", "", "--yes"];
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index a1fc563cc..670a6728b 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.4.0",
+ "version": "0.4.1",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json
index 44220641f..7677b715f 100644
--- a/examples/pi-coding-agent-extension/package-lock.json
+++ b/examples/pi-coding-agent-extension/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.0",
+ "version": "0.4.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openviking-pi-extension",
- "version": "0.4.0",
+ "version": "0.4.1",
"dependencies": {
"@modelcontextprotocol/client": "2.0.0"
},
diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json
index 98caf3a20..60bcea404 100644
--- a/examples/pi-coding-agent-extension/package.json
+++ b/examples/pi-coding-agent-extension/package.json
@@ -1,6 +1,6 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.0",
+ "version": "0.4.1",
"description": "OpenViking memory and context extension for the pi coding agent",
"private": true,
"type": "module",