Skip to content

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

feat(plugins): add Agent Plugins 1.0 portable package (#3998)

t0saki8abd61fcb6ae
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 4b5f63950..8e6949d73 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -63,7 +63,8 @@ jobs:
examples/memory-plugin-shared/uri-guard.test.mjs \
examples/opencode-plugin/tests/*.test.mjs \
examples/opencode-plugin/servers/mcp-proxy.test.mjs \
- examples/pi-coding-agent-extension/tests/*.test.mjs
+ examples/pi-coding-agent-extension/tests/*.test.mjs \
+ agent-plugins/plugin.test.mjs
- name: Check installer scripts parse
run: |
diff --git a/README.md b/README.md
index 2943d128c..befacb6bd 100644
--- a/README.md
+++ b/README.md
@@ -146,6 +146,7 @@ Integrations inject OpenViking recall into your agent's context and auto-commit
- [Trae](https://docs.openviking.ai/en/agent-integrations/13-trae)
- [OpenCode](https://docs.openviking.ai/en/agent-integrations/10-opencode)
- [pi](https://docs.openviking.ai/en/agent-integrations/11-pi)
+- [Agent Plugins 1.0](https://docs.openviking.ai/en/agent-integrations/15-agent-plugins)
- [MCP clients](https://docs.openviking.ai/en/agent-integrations/06-mcp-clients)
- [LangChain / LangGraph](https://docs.openviking.ai/en/agent-integrations/07-langchain-langgraph)
diff --git a/README_CN.md b/README_CN.md
index 5badf2847..abc19a7a3 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -155,6 +155,7 @@ Rust CLI 通过 `npm i -g @openviking/cli` 安装,也可以从源码构建:`
- [Trae](https://docs.openviking.ai/zh/agent-integrations/13-trae)
- [OpenCode](https://docs.openviking.ai/zh/agent-integrations/10-opencode)
- [pi](https://docs.openviking.ai/zh/agent-integrations/11-pi)
+- [Agent Plugins 1.0](https://docs.openviking.ai/zh/agent-integrations/15-agent-plugins)
- [MCP 客户端](https://docs.openviking.ai/zh/agent-integrations/06-mcp-clients)
- [LangChain / LangGraph](https://docs.openviking.ai/zh/agent-integrations/07-langchain-langgraph)
diff --git a/README_JA.md b/README_JA.md
index 794310bf3..7bf9c7ff2 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -155,6 +155,7 @@ Rust CLI は `npm i -g @openviking/cli` でインストールできます。ソ
- [Trae](https://docs.openviking.ai/en/agent-integrations/13-trae)
- [OpenCode](https://docs.openviking.ai/en/agent-integrations/10-opencode)
- [pi](https://docs.openviking.ai/en/agent-integrations/11-pi)
+- [Agent Plugins 1.0](https://docs.openviking.ai/en/agent-integrations/15-agent-plugins)
- [MCP クライアント](https://docs.openviking.ai/en/agent-integrations/06-mcp-clients)
- [LangChain / LangGraph](https://docs.openviking.ai/en/agent-integrations/07-langchain-langgraph)
diff --git a/agent-plugins/README.md b/agent-plugins/README.md
new file mode 100644
index 000000000..e39744bea
--- /dev/null
+++ b/agent-plugins/README.md
@@ -0,0 +1,79 @@
+# OpenViking Agent Plugins (Agent Plugins 1.0)
+
+Portable [Agent Plugins 1.0](https://agent-plugins.org/specification) package for [OpenViking](https://github.com/volcengine/OpenViking): long-term semantic memory and context for coding agents.
+
+Agent Plugins 1.0 is a vendor-neutral packaging format for extending AI coding agents, backed by Amazon, Cursor, Microsoft, OpenAI, and Vercel among others. A plugin is a plain directory with a `plugin.json` manifest, auto-discovered Agent Skills under `skills/`, and optional MCP server declarations in `mcp.json` — one package that any conforming client (Cursor, VS Code, Amazon- and OpenAI-side clients, ...) can load the same way. This directory is that package for OpenViking.
+
+## What's inside
+
+```
+plugin.json # Agent Plugins 1.0 manifest
+mcp.json # stdio MCP server: "openviking"
+servers/mcp-proxy.mjs # stdio -> streamable-HTTP proxy to the OV server's /mcp
+servers/config.mjs, debug-log.mjs # credential/config resolution (adapted from claude-code-memory-plugin)
+servers/shared/ # generated from examples/memory-plugin-shared/lib (do not edit)
+skills/openviking-memory/SKILL.md # teaches the model the recall + persist loop
+plugin.test.mjs # node --test conformance checks
+```
+
+Zero npm dependencies; the proxy and tests run on the Node.js standard library (Node 18+ for global `fetch`).
+
+## Install
+
+1. Have an OpenViking server reachable (see the [quickstart](../docs/en/getting-started/02-quickstart.md)); default local endpoint is `http://127.0.0.1:1933`.
+2. Point your Agent-Plugins-conforming client at this directory (each client has its own install command or plugin directory; consult its docs). The client will:
+ - register the `openviking` MCP server from `mcp.json` — it runs `node <plugin>/servers/mcp-proxy.mjs` over stdio;
+ - discover the `openviking-memory` skill from `skills/`.
+3. Configure credentials (next section) and start a session. The model gains `find` / `search` / `recall` / `read` / `remember` / `write` and the other OpenViking MCP tools.
+
+## Why a stdio proxy instead of a `streamable-http` entry
+
+OpenViking already speaks streamable HTTP at `/mcp`, but a `streamable-http` entry in `mcp.json` cannot work portably: the server URL is per-deployment (localhost for one user, a remote endpoint for another), and the Agent Plugins spec forbids credentials in the static `headers` map. The stdio proxy solves both — it resolves the URL and API key at runtime from the same local sources as the `ov` CLI, injects them per request, and forwards JSON-RPC over streamable HTTP unchanged.
+
+## Credential resolution
+
+Highest to lowest priority (same chain as the `ov` CLI and the other OpenViking plugins):
+
+1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
+2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account`, `user`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
+3. `~/.openviking/ov.conf` `server` section (`url` or `host`/`port`, `root_api_key`) — override the path with `OPENVIKING_CONFIG_FILE`
+4. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
+
+Config file changes are picked up by the running proxy without a restart. Debugging: set `OPENVIKING_DEBUG=1` to log JSON lines to `~/.openviking/logs/agent-plugins.log` (path override: `OPENVIKING_DEBUG_LOG`).
+
+## Scope: what this package does and doesn't do
+
+This package is the portable recall + write surface: skills plus MCP tools, driven by the model. Agent Plugins 1.0 deliberately excludes hooks, commands, and agents, so **automatic conversation capture and automatic pre-prompt recall are out of scope here** — the `skills/openviking-memory` skill instead teaches the model to recall at task start and persist durable facts via `remember`/`write` itself.
+
+**If your harness has a hook system, prefer the dedicated plugin** — hook-driven recall and capture cost no tool calls and don't depend on the model choosing to remember. One installer covers Claude Code, Codex, Cursor, TRAE / TRAE CN, ZCode, OpenCode, and pi; it prompts for language, harnesses, download source, and credentials, and is idempotent:
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
+# GitHub hard to reach? Same installer from the Volcengine TOS mirror:
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
+```
+
+- [claude-code-memory-plugin](../examples/claude-code-memory-plugin/) (Claude Code)
+- [codex-memory-plugin](../examples/codex-memory-plugin/) (Codex)
+- [opencode-plugin](../examples/opencode-plugin/) (OpenCode)
+- [cursor-memory-plugin](../examples/cursor-memory-plugin/), [trae-memory-hooks](../examples/trae-memory-hooks/), [zcode-memory-plugin](../examples/zcode-memory-plugin/), ...
+
+Use this Agent Plugins package for harnesses with no hooks, or when you want one package that loads across many clients.
+
+Per the spec, client-specific integrations may later be embedded in this package under reverse-domain namespaced directories (e.g. `com.example.client/`) or the manifest's `extensions` object without breaking other clients.
+
+## Development
+
+```bash
+node --test agent-plugins/plugin.test.mjs
+```
+
+`servers/shared/*.mjs` are generated, verbatim copies from `examples/memory-plugin-shared/lib` — do not edit them here. This directory is a target of the shared-lib sync script, so refresh them with:
+
+```bash
+node examples/memory-plugin-shared/sync.mjs
+```
+
+`examples/memory-plugin-shared/sync.test.mjs` fails if they drift. `servers/config.mjs`, `servers/debug-log.mjs`, and `servers/mcp-proxy.mjs` are adapted from `examples/claude-code-memory-plugin` (connection fields only — the hook-tuning knobs are dropped, since this spec has no hooks); when changing proxy behavior there, mirror it here.
+
+Both test files run in CI via `.github/workflows/pr.yml`.
diff --git a/agent-plugins/mcp.json b/agent-plugins/mcp.json
new file mode 100644
index 000000000..68421cc5b
--- /dev/null
+++ b/agent-plugins/mcp.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "mcpServers": {
+ "openviking": {
+ "type": "stdio",
+ "command": "node",
+ "args": ["${PLUGIN_ROOT}/servers/mcp-proxy.mjs"]
+ }
+ }
+}
diff --git a/agent-plugins/plugin.json b/agent-plugins/plugin.json
new file mode 100644
index 000000000..34f1878cf
--- /dev/null
+++ b/agent-plugins/plugin.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "openviking",
+ "version": "0.1.0",
+ "description": "Semantic long-term memory and context engine for coding agents. Recall prior knowledge with the find/search/read MCP tools and persist durable facts with remember/write, backed by an OpenViking server.",
+ "author": {
+ "name": "Volcano Engine",
+ "url": "https://github.com/volcengine"
+ },
+ "homepage": "https://github.com/volcengine/OpenViking",
+ "repository": "https://github.com/volcengine/OpenViking",
+ "license": "AGPL-3.0",
+ "keywords": [
+ "memory",
+ "long-term-memory",
+ "context-engine",
+ "semantic-search",
+ "mcp",
+ "openviking"
+ ]
+}
diff --git a/agent-plugins/plugin.test.mjs b/agent-plugins/plugin.test.mjs
new file mode 100644
index 000000000..12e6daeb6
--- /dev/null
+++ b/agent-plugins/plugin.test.mjs
@@ -0,0 +1,196 @@
+/**
+ * Conformance checks for the OpenViking Agent Plugins 1.0 package.
+ *
+ * Zero-dependency, runs with `node --test agent-plugins/plugin.test.mjs`.
+ * Validates the manifests against the Agent Plugins 1.0 spec
+ * (https://agent-plugins.org/specification), skill frontmatter against the
+ * Agent Skills spec, and that every referenced/vendored .mjs file exists and
+ * parses.
+ */
+
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
+import { dirname, join, resolve, sep } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const PLUGIN_ROOT = dirname(fileURLToPath(import.meta.url));
+
+const SPEC_VERSION = "1.0.0";
+const PLUGIN_SCHEMA_URL = `https://agent-plugins.org/schemas/${SPEC_VERSION}/plugin.schema.json`;
+const MCP_SCHEMA_URL = `https://agent-plugins.org/schemas/${SPEC_VERSION}/mcp.schema.json`;
+
+// plugin.json root is closed: only fields documented by the 1.0 spec.
+const PLUGIN_ALLOWED_KEYS = new Set([
+ "$schema",
+ "name",
+ "version",
+ "description",
+ "author",
+ "homepage",
+ "repository",
+ "license",
+ "keywords",
+ "extensions",
+]);
+const AUTHOR_ALLOWED_KEYS = new Set(["name", "email", "url"]);
+
+// name: 1-64 chars, lowercase alphanumeric plus hyphens and periods, no
+// consecutive hyphens or periods, starts and ends alphanumeric.
+const NAME_RE = /^[a-z0-9](?:[a-z0-9]|[-.](?=[a-z0-9])){0,63}$/;
+const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+function loadJson(relPath) {
+ return JSON.parse(readFileSync(join(PLUGIN_ROOT, relPath), "utf-8"));
+}
+
+function schemaSpecVersion(schemaUrl) {
+ const m = /^https:\/\/agent-plugins\.org\/schemas\/(\d+\.\d+\.\d+)\//.exec(String(schemaUrl));
+ return m ? m[1] : null;
+}
+
+function listMjsFiles(dir) {
+ const out = [];
+ for (const entry of readdirSync(dir)) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) out.push(...listMjsFiles(full));
+ else if (entry.endsWith(".mjs")) out.push(full);
+ }
+ return out;
+}
+
+test("plugin.json conforms to Agent Plugins 1.0", () => {
+ const manifest = loadJson("plugin.json");
+
+ assert.equal(manifest.$schema, PLUGIN_SCHEMA_URL);
+
+ assert.equal(typeof manifest.name, "string");
+ assert.ok(manifest.name.length >= 1 && manifest.name.length <= 64, "name must be 1-64 chars");
+ assert.match(manifest.name, NAME_RE, "name must be lowercase alphanumeric/hyphens/periods without consecutive separators");
+ assert.ok(!/--|\.\./.test(manifest.name), "name must not contain consecutive hyphens or periods");
+
+ for (const key of Object.keys(manifest)) {
+ assert.ok(PLUGIN_ALLOWED_KEYS.has(key), `plugin.json root field not in the 1.0 spec: ${key}`);
+ }
+
+ if (manifest.version !== undefined) {
+ assert.match(manifest.version, SEMVER_RE, "version must be semver");
+ }
+ if (manifest.author !== undefined) {
+ assert.equal(typeof manifest.author, "object");
+ for (const key of Object.keys(manifest.author)) {
+ assert.ok(AUTHOR_ALLOWED_KEYS.has(key), `author field not in the 1.0 spec: ${key}`);
+ }
+ assert.equal(typeof manifest.author.name, "string");
+ }
+ if (manifest.keywords !== undefined) {
+ assert.ok(Array.isArray(manifest.keywords));
+ for (const kw of manifest.keywords) assert.equal(typeof kw, "string");
+ }
+ assert.equal(typeof manifest.description, "string");
+ assert.equal(typeof manifest.license, "string");
+});
+
+test("mcp.json conforms and its spec version matches plugin.json", () => {
+ const manifest = loadJson("plugin.json");
+ const mcp = loadJson("mcp.json");
+
+ assert.equal(mcp.$schema, MCP_SCHEMA_URL);
+ assert.equal(
+ schemaSpecVersion(mcp.$schema),
+ schemaSpecVersion(manifest.$schema),
+ "mcp.json $schema spec version must match plugin.json's",
+ );
+
+ for (const key of Object.keys(mcp)) {
+ assert.ok(key === "$schema" || key === "mcpServers", `mcp.json root field not in the 1.0 spec: ${key}`);
+ }
+ assert.equal(typeof mcp.mcpServers, "object");
+ assert.ok(Object.keys(mcp.mcpServers).length > 0, "at least one MCP server expected");
+});
+
+test("mcp.json server entries are valid and reference files inside the plugin", () => {
+ const mcp = loadJson("mcp.json");
+
+ for (const [name, server] of Object.entries(mcp.mcpServers)) {
+ if (server.type === "streamable-http") {
+ assert.equal(typeof server.url, "string");
+ for (const header of Object.keys(server.headers || {})) {
+ assert.ok(
+ !/authorization|api[-_]?key|token|secret|cookie/i.test(header),
+ `server ${name}: headers must not carry credentials (${header})`,
+ );
+ }
+ continue;
+ }
+
+ assert.equal(server.type, "stdio", `server ${name}: type must be stdio or streamable-http`);
+ assert.equal(typeof server.command, "string");
+ // command is a single executable token: no shell strings, and placeholders
+ // like ${PLUGIN_ROOT} are only expanded in args/env/cwd, never in command.
+ assert.ok(!/\s/.test(server.command), `server ${name}: command must be a single token`);
+ assert.ok(!server.command.includes("${"), `server ${name}: placeholders are not expanded in command`);
+ if (server.command.startsWith("./")) {
+ assert.ok(existsSync(join(PLUGIN_ROOT, server.command)), `server ${name}: plugin-relative command missing`);
+ }
+
+ for (const arg of server.args || []) {
+ if (!String(arg).includes("${PLUGIN_ROOT}")) continue;
+ const expanded = resolve(String(arg).replaceAll("${PLUGIN_ROOT}", PLUGIN_ROOT));
+ assert.ok(
+ expanded === PLUGIN_ROOT || expanded.startsWith(PLUGIN_ROOT + sep),
+ `server ${name}: arg escapes the plugin root: ${arg}`,
+ );
+ assert.ok(existsSync(expanded), `server ${name}: referenced file missing: ${arg}`);
+ }
+ }
+});
+
+test("every skills/* child ships a SKILL.md with name + description frontmatter", () => {
+ const skillsDir = join(PLUGIN_ROOT, "skills");
+ const children = readdirSync(skillsDir).filter((entry) =>
+ statSync(join(skillsDir, entry)).isDirectory(),
+ );
+ assert.ok(children.length > 0, "at least one skill expected");
+
+ for (const child of children) {
+ const skillPath = join(skillsDir, child, "SKILL.md");
+ assert.ok(existsSync(skillPath), `missing ${skillPath}`);
+ const raw = readFileSync(skillPath, "utf-8");
+
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(raw);
+ assert.ok(fm, `${child}/SKILL.md must start with YAML frontmatter`);
+
+ const fields = {};
+ for (const line of fm[1].split(/\r?\n/)) {
+ const kv = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line);
+ if (kv) fields[kv[1]] = kv[2].trim();
+ }
+ assert.ok(fields.name, `${child}/SKILL.md frontmatter missing name`);
+ assert.ok(fields.description, `${child}/SKILL.md frontmatter missing description`);
+ assert.equal(fields.name, child, `${child}/SKILL.md name should match its directory`);
+ assert.match(fields.name, NAME_RE);
+ }
+});
+
+test("all .mjs files in the plugin pass node --check", () => {
+ const files = listMjsFiles(PLUGIN_ROOT);
+ assert.ok(files.length > 0, "expected vendored .mjs files");
+ for (const file of files) {
+ const result = spawnSync(process.execPath, ["--check", file], { encoding: "utf-8" });
+ assert.equal(result.status, 0, `node --check failed for ${file}: ${result.stderr}`);
+ }
+});
+
+test("vendored proxy chain resolves: mcp-proxy.mjs imports exist", () => {
+ const proxy = readFileSync(join(PLUGIN_ROOT, "servers", "mcp-proxy.mjs"), "utf-8");
+ const imports = [...proxy.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]);
+ assert.ok(imports.length > 0);
+ for (const rel of imports) {
+ assert.ok(
+ existsSync(join(PLUGIN_ROOT, "servers", rel)),
+ `mcp-proxy.mjs import missing: ${rel}`,
+ );
+ }
+});
diff --git a/agent-plugins/servers/config.mjs b/agent-plugins/servers/config.mjs
new file mode 100644
index 000000000..a381f6fd0
--- /dev/null
+++ b/agent-plugins/servers/config.mjs
@@ -0,0 +1,152 @@
+/**
+ * Connection config loader for the OpenViking Agent Plugins 1.0 package.
+ *
+ * VENDORED (adapted) from examples/claude-code-memory-plugin/scripts/config.mjs —
+ * keep the resolution semantics in sync with that file. This copy is trimmed to
+ * the fields consumed by servers/mcp-proxy.mjs: Agent Plugins 1.0 has no hooks,
+ * so all of the hook-tuning knobs (recall/capture/commit/profile) are dropped,
+ * as is the Claude-Code-specific `claude_code` section of ov.conf.
+ *
+ * Resolution priority (highest → lowest):
+ * 1. Environment variables (OPENVIKING_*)
+ * 2. ovcli.conf (CLI client config: url, api_key, account, user)
+ * 3. ov.conf `server` section (local server config; url/host/port/root_api_key)
+ * 4. Built-in defaults (http://127.0.0.1:1933)
+ *
+ * Env vars covered:
+ * Connection / identity:
+ * OPENVIKING_URL / OPENVIKING_BASE_URL, OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN,
+ * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID, OPENVIKING_WORKSPACE_PEER
+ * Config file overrides:
+ * OPENVIKING_CONFIG_FILE (ov.conf), OPENVIKING_CLI_CONFIG_FILE (ovcli.conf)
+ * Misc:
+ * OPENVIKING_TIMEOUT_MS, OPENVIKING_DEBUG, OPENVIKING_DEBUG_LOG
+ */
+
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { resolve as resolvePath, join } from "node:path";
+
+import { buildUserAgent, readManifestVersion } from "./shared/credentials.mjs";
+
+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
+const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
+const USER_AGENT = buildUserAgent(
+ "agent-plugins",
+ readManifestVersion(new URL("../plugin.json", import.meta.url)),
+);
+
+function num(val, fallback) {
+ if (typeof val === "number" && Number.isFinite(val)) return val;
+ if (typeof val === "string" && val.trim()) {
+ const n = Number(val);
+ if (Number.isFinite(n)) return n;
+ }
+ return fallback;
+}
+
+function str(val, fallback) {
+ if (typeof val === "string" && val.trim()) return val.trim();
+ return fallback;
+}
+
+function envBool(name) {
+ const v = process.env[name];
+ if (v == null || v === "") return undefined;
+ const lower = v.trim().toLowerCase();
+ if (lower === "0" || lower === "false" || lower === "no") return false;
+ if (lower === "1" || lower === "true" || lower === "yes") return true;
+ return undefined;
+}
+
+/**
+ * Try to load and parse a JSON config file. Returns { configPath, file } or null.
+ */
+function tryLoadJsonFile(envVar, defaultPath) {
+ const configPath = resolvePath(
+ (process.env[envVar] || defaultPath).replace(/^~/, homedir()),
+ );
+
+ let raw;
+ try {
+ raw = readFileSync(configPath, "utf-8");
+ } catch {
+ return null;
+ }
+
+ try {
+ return { configPath, file: JSON.parse(raw) };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Load the connection configuration for the stdio MCP proxy.
+ *
+ * Resolution: env vars → ovcli.conf → ov.conf → defaults.
+ */
+export function loadConfig() {
+ const ovConf = tryLoadJsonFile("OPENVIKING_CONFIG_FILE", DEFAULT_OV_CONF_PATH);
+ const cliConf = tryLoadJsonFile("OPENVIKING_CLI_CONFIG_FILE", DEFAULT_OVCLI_CONF_PATH);
+
+ const ovFile = ovConf?.file || {};
+ const cliFile = cliConf?.file || {};
+ const configPath = cliConf?.configPath || ovConf?.configPath || null;
+
+ const server = ovFile.server || {};
+
+ // baseUrl: env → ovcli.url → ov.server.url → http://{host}:{port}
+ const envUrl = str(process.env.OPENVIKING_URL, null) || str(process.env.OPENVIKING_BASE_URL, null);
+ let baseUrl;
+ if (envUrl) {
+ baseUrl = envUrl.replace(/\/+$/, "");
+ } else if (cliFile.url) {
+ baseUrl = str(cliFile.url, "").replace(/\/+$/, "");
+ } else if (server.url) {
+ baseUrl = str(server.url, "").replace(/\/+$/, "");
+ } else {
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Math.floor(num(server.port, 1933));
+ baseUrl = `http://${host}:${port}`;
+ }
+
+ // apiKey: env → ovcli.api_key → ov.server.root_api_key
+ // Accepts OPENVIKING_BEARER_TOKEN or OPENVIKING_API_KEY (sent as Bearer either way).
+ const apiKey = str(process.env.OPENVIKING_BEARER_TOKEN, null)
+ || str(process.env.OPENVIKING_API_KEY, null)
+ || str(cliFile.api_key, null)
+ || str(server.root_api_key, "");
+
+ const accountId = str(process.env.OPENVIKING_ACCOUNT, null)
+ || str(cliFile.account, "");
+
+ const userId = str(process.env.OPENVIKING_USER, null)
+ || str(cliFile.user, "");
+
+ const peerId = str(process.env.OPENVIKING_PEER_ID, "");
+ const workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? true;
+
+ const timeoutMs = Math.max(1000, Math.floor(num(
+ process.env.OPENVIKING_TIMEOUT_MS,
+ 15000,
+ )));
+
+ const debug = envBool("OPENVIKING_DEBUG") ?? false;
+ const defaultLogPath = join(homedir(), ".openviking", "logs", "agent-plugins.log");
+ const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);
+
+ return {
+ configPath,
+ baseUrl,
+ apiKey,
+ accountId,
+ userId,
+ peerId,
+ workspacePeer,
+ timeoutMs,
+ userAgent: USER_AGENT,
+ debug,
+ debugLogPath,
+ };
+}
diff --git a/agent-plugins/servers/debug-log.mjs b/agent-plugins/servers/debug-log.mjs
new file mode 100644
index 000000000..f6210e4d0
--- /dev/null
+++ b/agent-plugins/servers/debug-log.mjs
@@ -0,0 +1,31 @@
+/**
+ * Structured debug logger for the OpenViking Agent Plugins 1.0 package.
+ *
+ * VENDORED (adapted) from examples/claude-code-memory-plugin/scripts/debug-log.mjs —
+ * keep in sync with that file.
+ *
+ * Activation: OPENVIKING_DEBUG=1 env var.
+ * Log path: OPENVIKING_DEBUG_LOG env var OR ~/.openviking/logs/agent-plugins.log.
+ * Format: JSON Lines — { ts, hook, stage, data } | { ts, hook, stage, error }.
+ *
+ * When inactive, log() and logError() are zero-cost no-ops.
+ */
+
+import { loadConfig } from "./config.mjs";
+import { createLogger as createSharedLogger } from "./shared/debug-log.mjs";
+
+let _cfg;
+function cfg() {
+ if (!_cfg) _cfg = loadConfig();
+ return _cfg;
+}
+
+/**
+ * @param {string} hookName — e.g. "mcp-proxy"
+ * @param {{ debug?: boolean, debugLogPath?: string }} [overrideCfg]
+ * Pass a config object directly (avoids re-loading config in tests).
+ * @returns {{ log: (stage: string, data: any) => void, logError: (stage: string, err: any) => void }}
+ */
+export function createLogger(hookName, overrideCfg) {
+ return createSharedLogger(hookName, overrideCfg || cfg());
+}
diff --git a/agent-plugins/servers/mcp-proxy.mjs b/agent-plugins/servers/mcp-proxy.mjs
new file mode 100644
index 000000000..34d036dcf
--- /dev/null
+++ b/agent-plugins/servers/mcp-proxy.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+
+/**
+ * stdio -> streamable-HTTP MCP proxy for the OpenViking Agent Plugins 1.0 package.
+ *
+ * VENDORED (adapted) from examples/claude-code-memory-plugin/servers/mcp-proxy.mjs —
+ * keep in sync with that file. Only the import paths and doc comments differ;
+ * the proxy behavior is identical. The shared modules under ./shared/ are
+ * generated by `node examples/memory-plugin-shared/sync.mjs` (this directory is
+ * one of its TARGETS) — edit them in examples/memory-plugin-shared/lib, never here.
+ *
+ * A conforming Agent Plugins client starts this process as a local stdio MCP
+ * server (see ../mcp.json). The proxy reads the same OpenViking credential
+ * sources as the ov CLI (OPENVIKING_* env → ~/.openviking/ovcli.conf →
+ * ~/.openviking/ov.conf), forwards JSON-RPC requests to the server's /mcp
+ * endpoint, and keeps stdout protocol-clean.
+ */
+
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadConfig } from "./config.mjs";
+import { createLogger } from "./debug-log.mjs";
+import { createOpenVikingMcpProxy } from "./shared/mcp-proxy-core.mjs";
+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
+
+const DEFAULT_TIMEOUT_MS = 15000;
+
+function trimSlash(value) {
+ return String(value || "").replace(/\/+$/, "");
+}
+
+function normalizePath(value) {
+ const raw = String(value || "").trim();
+ if (!raw) return "";
+ if (raw === "~") return homedir();
+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
+ return resolvePath(raw);
+}
+
+function uniq(values) {
+ return [...new Set(values.filter(Boolean))];
+}
+
+function readProxyConfig() {
+ const cfg = loadConfig();
+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });
+ return {
+ mcpUrl: `${trimSlash(cfg.baseUrl)}/mcp`,
+ apiKey: cfg.apiKey || "",
+ account: cfg.accountId || "",
+ user: cfg.userId || "",
+ peerId: effectivePeer.peerId,
+ userAgent: cfg.userAgent || "",
+ timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),
+ debug: cfg.debug === true,
+ debugLogPath: cfg.debugLogPath,
+ credentialSource: cfg.configPath?.endsWith("ovcli.conf") ? "ovcli" : "auto",
+ credentialPath: cfg.configPath || "",
+ watchedPaths: uniq([
+ cfg.configPath,
+ normalizePath(process.env.OPENVIKING_CLI_CONFIG_FILE),
+ normalizePath(process.env.OPENVIKING_CONFIG_FILE),
+ join(homedir(), ".openviking", "ovcli.conf"),
+ join(homedir(), ".openviking", "ov.conf"),
+ ]),
+ };
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+ createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
+}
diff --git a/agent-plugins/servers/shared/credentials.mjs b/agent-plugins/servers/shared/credentials.mjs
new file mode 100644
index 000000000..30d5401f2
--- /dev/null
+++ b/agent-plugins/servers/shared/credentials.mjs
@@ -0,0 +1,228 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
+
+function str(val, fallback = "") {
+ if (typeof val === "string" && val.trim()) return val.trim();
+ return fallback;
+}
+
+function normalizePath(value) {
+ const raw = str(value, "");
+ if (!raw) return "";
+ if (raw === "~") return homedir();
+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
+ return resolvePath(raw);
+}
+
+function tryLoadJson(path) {
+ if (!path) return null;
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build the User-Agent every harness plugin sends on OpenViking-bound requests.
+ * Shape is `name/semver` so downstream stats layers can parse it as one token.
+ */
+export function buildUserAgent(harness, version) {
+ return `openviking-memory-${harness}/${str(version, "") || "0.0.0"}`;
+}
+
+/**
+ * Read a plugin manifest's `version` field. Accepts a path or a URL (so callers
+ * can resolve relative to import.meta.url). Returns "" when unreadable so the
+ * User-Agent falls back to 0.0.0 instead of throwing inside a short-lived hook.
+ */
+export function readManifestVersion(manifest) {
+ try {
+ return str(JSON.parse(readFileSync(manifest, "utf-8")).version, "");
+ } catch {
+ return "";
+ }
+}
+
+function looksLikeOvcli(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ if (obj.server && typeof obj.server === "object") return false;
+ return Boolean(
+ typeof obj.url === "string" ||
+ typeof obj.api_key === "string" ||
+ typeof obj.account === "string" ||
+ typeof obj.account_id === "string" ||
+ typeof obj.user === "string" ||
+ typeof obj.user_id === "string" ||
+ typeof obj.actor_peer_id === "string",
+ );
+}
+
+function hasCredentialFields(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ return [
+ "url",
+ "api_key",
+ "account",
+ "account_id",
+ "user",
+ "user_id",
+ "actor_peer_id",
+ "peer_id",
+ ].some((key) => typeof obj[key] === "string");
+}
+
+export function loadCredentialFiles(env = process.env) {
+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;
+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;
+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));
+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));
+
+ let cliFile = tryLoadJson(cliPathCandidate);
+ let cliPath = cliFile ? cliPathCandidate : "";
+ let ovFile = tryLoadJson(ovPathCandidate);
+ let ovPath = ovFile ? ovPathCandidate : "";
+
+ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for
+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.
+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {
+ cliFile = ovFile;
+ cliPath = ovPath;
+ ovFile = null;
+ ovPath = "";
+ }
+
+ return {
+ cliFile: cliFile || {},
+ cliPath,
+ cliPathCandidate,
+ ovFile: ovFile || {},
+ ovPath,
+ };
+}
+
+function sourceMode(env) {
+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
+ .toLowerCase();
+ if (raw === "env" || raw === "environment") return "env";
+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";
+ return "auto";
+}
+
+function hasEnvCredentialFields(env) {
+ return Boolean(
+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
+ str(env.OPENVIKING_MCP_URL, "") ||
+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(env.OPENVIKING_USER, "") ||
+ str(env.OPENVIKING_PEER_ID, ""),
+ );
+}
+
+function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const cliUrl = str(cliFile.url, "");
+
+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
+ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
+
+ const server = ovFile.server || {};
+ const ovUrl = str(server.url, "");
+ if (ovUrl) return ovUrl.replace(/\/+$/, "");
+
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
+export function resolveOpenVikingCredentials(env = process.env) {
+ const files = loadCredentialFiles(env);
+ const mode = sourceMode(env);
+ const envHasCredentials = hasEnvCredentialFields(env);
+ const useCli = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
+ const cx = files.ovFile.codex || {};
+ const server = files.ovFile.server || {};
+
+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+
+ const apiKey = useCli
+ ? str(files.cliFile.api_key, "")
+ : (
+ str(env.OPENVIKING_BEARER_TOKEN, "") ||
+ str(env.OPENVIKING_API_KEY, "") ||
+ str(files.cliFile.api_key, "") ||
+ str(cx.apiKey, "") ||
+ str(server.root_api_key, "")
+ );
+
+ const account = useCli
+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ : (
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ str(cx.accountId, "")
+ );
+
+ const user = useCli
+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ : (
+ str(env.OPENVIKING_USER, "") ||
+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ str(cx.userId, "")
+ );
+
+ const peerId = useCli
+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
+ : (
+ str(env.OPENVIKING_PEER_ID, "") ||
+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
+ str(cx.peerId, str(cx.peer_id, ""))
+ );
+
+ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
+
+ return {
+ ...files,
+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ baseUrl,
+ mcpUrl,
+ apiKey,
+ account,
+ user,
+ peerId,
+ hasApiKey: Boolean(apiKey),
+ };
+}
+
+function main() {
+ const cmd = process.argv[2] || "";
+ if (cmd === "mcp-url") {
+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
+ return;
+ }
+ if (cmd === "has-api-key") {
+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
+ return;
+ }
+ if (cmd === "has-peer-id") {
+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
+ return;
+ }
+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
+ process.exitCode = 2;
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+ main();
+}
diff --git a/agent-plugins/servers/shared/debug-log.mjs b/agent-plugins/servers/shared/debug-log.mjs
new file mode 100644
index 000000000..73855cf6d
--- /dev/null
+++ b/agent-plugins/servers/shared/debug-log.mjs
@@ -0,0 +1,58 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared structured debug logger for OpenViking memory plugin hook scripts.
+ *
+ * Harness-specific wrappers load config and pass {debug, debugLogPath}. This
+ * module stays path-agnostic so it can be vendored into each plugin snapshot.
+ */
+
+import { appendFileSync, mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+function ensureDir(filePath) {
+ try {
+ mkdirSync(dirname(filePath), { recursive: true });
+ } catch { /* best effort */ }
+}
+
+function writeLine(filePath, obj) {
+ try {
+ appendFileSync(filePath, JSON.stringify(obj) + "\n");
+ } catch { /* best effort */ }
+}
+
+function localISO() {
+ const d = new Date();
+ const off = d.getTimezoneOffset();
+ const sign = off <= 0 ? "+" : "-";
+ const abs = Math.abs(off);
+ const local = new Date(d.getTime() - off * 60000);
+ return local.toISOString().replace(
+ "Z",
+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`,
+ );
+}
+
+const noop = () => {};
+
+export function createLogger(hookName, overrideCfg) {
+ const c = overrideCfg || {};
+ if (!c.debug) return { log: noop, logError: noop };
+
+ const logPath = c.debugLogPath;
+ if (!logPath) return { log: noop, logError: noop };
+ ensureDir(logPath);
+
+ function log(stage, data) {
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });
+ }
+
+ function logError(stage, err) {
+ const error = err instanceof Error
+ ? { message: err.message, stack: err.stack }
+ : String(err);
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });
+ }
+
+ return { log, logError };
+}
diff --git a/agent-plugins/servers/shared/mcp-proxy-core.mjs b/agent-plugins/servers/shared/mcp-proxy-core.mjs
new file mode 100644
index 000000000..70b1a4539
--- /dev/null
+++ b/agent-plugins/servers/shared/mcp-proxy-core.mjs
@@ -0,0 +1,504 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared stdio -> streamable-HTTP MCP proxy core for OpenViking memory plugins.
+ *
+ * Harness-specific entrypoints provide credential/config loading; this module
+ * owns only transport, session retry, SSE parsing, and protocol-clean stdio.
+ */
+
+import { statSync } from "node:fs";
+import { createInterface } from "node:readline";
+
+const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
+const DELETE_TIMEOUT_MS = 2000;
+const MAX_CONCURRENT_REQUESTS = 16;
+
+class HttpStatusError extends Error {
+ constructor(status, statusText, bodyText, messages = []) {
+ super(`HTTP ${status}${statusText ? ` ${statusText}` : ""}`);
+ this.name = "HttpStatusError";
+ this.status = status;
+ this.statusText = statusText;
+ this.bodyText = bodyText;
+ this.messages = messages;
+ }
+}
+
+function snapshotPaths(paths) {
+ const out = new Map();
+ for (const path of paths || []) {
+ try {
+ const st = statSync(path);
+ out.set(path, `${st.mtimeMs}:${st.size}`);
+ } catch {
+ out.set(path, "missing");
+ }
+ }
+ return out;
+}
+
+function snapshotsDiffer(a, b) {
+ if (a.size !== b.size) return true;
+ for (const [key, value] of a.entries()) {
+ if (b.get(key) !== value) return true;
+ }
+ return false;
+}
+
+function createSemaphore(limit) {
+ let active = 0;
+ const queue = [];
+ return async function acquire() {
+ if (active >= limit) {
+ await new Promise((resolve) => queue.push(resolve));
+ }
+ active += 1;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ active -= 1;
+ const next = queue.shift();
+ if (next) next();
+ };
+ };
+}
+
+function isRequest(message) {
+ return Object.prototype.hasOwnProperty.call(message || {}, "id");
+}
+
+function messageId(message) {
+ return isRequest(message) ? message.id : undefined;
+}
+
+function errorResponse(id, code, message, data) {
+ const error = { code, message };
+ if (data !== undefined) error.data = data;
+ return { jsonrpc: "2.0", id: id ?? null, error };
+}
+
+function parseMaybeJson(text) {
+ const trimmed = String(text || "").trim();
+ if (!trimmed) return null;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return null;
+ }
+}
+
+function parseSseMessages(text) {
+ const messages = [];
+ let dataLines = [];
+
+ function flush() {
+ if (dataLines.length === 0) return;
+ const data = dataLines.join("\n").trim();
+ dataLines = [];
+ if (!data || data === "[DONE]") return;
+ messages.push(JSON.parse(data));
+ }
+
+ for (const rawLine of String(text || "").split(/\r?\n/)) {
+ if (rawLine === "") {
+ flush();
+ continue;
+ }
+ if (rawLine.startsWith(":")) continue;
+ const colon = rawLine.indexOf(":");
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
+ let value = colon === -1 ? "" : rawLine.slice(colon + 1);
+ if (value.startsWith(" ")) value = value.slice(1);
+ if (field === "data") dataLines.push(value);
+ }
+ flush();
+ return messages;
+}
+
+function parseHttpBody(contentType, text) {
+ const ctype = String(contentType || "").toLowerCase();
+ if (!String(text || "").trim()) return [];
+ if (ctype.includes("text/event-stream")) return parseSseMessages(text);
+ const json = parseMaybeJson(text);
+ return json == null ? [] : [json];
+}
+
+function serializeBodyForError(bodyText) {
+ const parsed = parseMaybeJson(bodyText);
+ if (parsed?.error?.message) return parsed.error.message;
+ if (parsed?.detail) return typeof parsed.detail === "string" ? parsed.detail : JSON.stringify(parsed.detail);
+ const compact = String(bodyText || "").replace(/\s+/g, " ").trim();
+ return compact.slice(0, 500);
+}
+
+function cloneMessage(message) {
+ return JSON.parse(JSON.stringify(message));
+}
+
+export function createOpenVikingMcpProxy({
+ stdin = process.stdin,
+ stdout = process.stdout,
+ readConfig,
+ loggerFactory,
+ fetchImpl = globalThis.fetch,
+ localToolProvider = null,
+} = {}) {
+ if (typeof fetchImpl !== "function") {
+ throw new Error("global fetch is required; use Node.js 18 or newer");
+ }
+ if (typeof readConfig !== "function") {
+ throw new Error("readConfig function is required");
+ }
+ if (typeof loggerFactory !== "function") {
+ throw new Error("loggerFactory function is required");
+ }
+
+ let proxyConfig = readConfig();
+ let logger = loggerFactory("mcp-proxy", proxyConfig);
+ let watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);
+ let sessionId = "";
+ let initializeRequest = null;
+ let initializedNotification = null;
+ let protocolVersion = DEFAULT_PROTOCOL_VERSION;
+ let initializeInFlight = null;
+ let reinitializeInFlight = null;
+ let stdoutChain = Promise.resolve();
+ let shuttingDown = false;
+ let reinitCounter = 0;
+ const acquire = createSemaphore(MAX_CONCURRENT_REQUESTS);
+
+ function log(stage, data) {
+ try {
+ logger.log(stage, data);
+ } catch { /* debug logging must never affect protocol IO */ }
+ }
+
+ function logError(stage, err) {
+ try {
+ logger.logError(stage, err);
+ } catch { /* debug logging must never affect protocol IO */ }
+ }
+
+ function localTools() {
+ if (!localToolProvider || typeof localToolProvider.listTools !== "function") return [];
+ const tools = localToolProvider.listTools();
+ return Array.isArray(tools) ? tools : [];
+ }
+
+ function appendLocalTools(message, outbound) {
+ if (message.method !== "tools/list" || !Array.isArray(outbound?.result?.tools)) {
+ return outbound;
+ }
+ const additions = localTools().filter((tool) => tool?.name);
+ if (additions.length === 0) return outbound;
+ const localNames = new Set(additions.map((tool) => tool.name));
+ const upstreamTools = outbound.result.tools.filter((tool) => !localNames.has(tool?.name));
+ return {
+ ...outbound,
+ result: {
+ ...outbound.result,
+ tools: [...upstreamTools, ...additions],
+ },
+ };
+ }
+
+ async function callLocalTool(message) {
+ if (
+ message.method !== "tools/call"
+ || !localToolProvider
+ || typeof localToolProvider.callTool !== "function"
+ ) {
+ return null;
+ }
+ const name = message.params?.name;
+ if (!localTools().some((tool) => tool?.name === name)) return null;
+ reloadIfCredentialFilesChanged("local_tool_call");
+ return localToolProvider.callTool(message.params, { config: proxyConfig });
+ }
+
+ function reloadConfig(reason) {
+ proxyConfig = readConfig();
+ logger = loggerFactory("mcp-proxy", proxyConfig);
+ watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);
+ log("credentials_reloaded", {
+ reason,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath,
+ mcpUrl: proxyConfig.mcpUrl,
+ hasApiKey: Boolean(proxyConfig.apiKey),
+ hasIdentity: Boolean(proxyConfig.account || proxyConfig.user),
+ hasPeer: Boolean(proxyConfig.peerId),
+ });
+ }
+
+ function reloadIfCredentialFilesChanged(reason) {
+ const next = snapshotPaths(proxyConfig.watchedPaths);
+ if (!snapshotsDiffer(watchedSnapshot, next)) return false;
+ reloadConfig(reason);
+ return true;
+ }
+
+ function headersForRequest(includeSession = true) {
+ const headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ // Always the proxy's current version (default, then server-negotiated) —
+ // never the client's un-negotiated ask, which strict upstreams reject
+ // with HTTP 400 before initialize negotiation can run.
+ "MCP-Protocol-Version": protocolVersion,
+ };
+ if (includeSession && sessionId) headers["Mcp-Session-Id"] = sessionId;
+ if (proxyConfig.apiKey) headers.Authorization = `Bearer ${proxyConfig.apiKey}`;
+ if (proxyConfig.account) headers["X-OpenViking-Account"] = proxyConfig.account;
+ if (proxyConfig.user) headers["X-OpenViking-User"] = proxyConfig.user;
+ if (proxyConfig.peerId) headers["X-OpenViking-Actor-Peer"] = proxyConfig.peerId;
+ if (proxyConfig.userAgent) headers["User-Agent"] = proxyConfig.userAgent;
+ return headers;
+ }
+
+ function writeMessage(obj) {
+ const line = `${JSON.stringify(obj)}\n`;
+ stdoutChain = stdoutChain
+ .then(() => new Promise((resolve) => stdout.write(line, resolve)))
+ .catch(() => {});
+ return stdoutChain;
+ }
+
+ function mapError(message, err) {
+ const id = messageId(message);
+ if (err instanceof HttpStatusError) {
+ if (err.status === 401 || err.status === 403) {
+ return errorResponse(
+ id,
+ -32001,
+ `OpenViking MCP authentication failed (HTTP ${err.status}). Check ~/.openviking/ovcli.conf or OPENVIKING_API_KEY, and verify the configured account/user for trusted mode.`,
+ {
+ status: err.status,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath || undefined,
+ serverMessage: serializeBodyForError(err.bodyText) || undefined,
+ },
+ );
+ }
+ return errorResponse(
+ id,
+ -32002,
+ `OpenViking MCP upstream returned HTTP ${err.status}.`,
+ {
+ status: err.status,
+ serverMessage: serializeBodyForError(err.bodyText) || undefined,
+ },
+ );
+ }
+ const msg = err instanceof Error ? err.message : String(err);
+ return errorResponse(
+ id,
+ -32001,
+ `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that 'ov serve' is running.`,
+ { cause: msg },
+ );
+ }
+
+ async function postToMcp(message, { includeSession = true, timeoutMs = proxyConfig.timeoutMs } = {}) {
+ const release = await acquire();
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetchImpl(proxyConfig.mcpUrl, {
+ method: "POST",
+ headers: headersForRequest(includeSession),
+ body: JSON.stringify(message),
+ signal: controller.signal,
+ });
+ const text = await res.text();
+ const messages = parseHttpBody(res.headers.get("content-type"), text);
+ const nextSessionId = res.headers.get("mcp-session-id");
+ if (nextSessionId) sessionId = nextSessionId;
+ if (message?.method === "initialize" && res.ok) {
+ const negotiated = messages.find((m) => typeof m?.result?.protocolVersion === "string")?.result.protocolVersion;
+ if (negotiated) protocolVersion = negotiated;
+ }
+ if (!res.ok) {
+ throw new HttpStatusError(res.status, res.statusText, text, messages);
+ }
+ return { status: res.status, messages };
+ } finally {
+ clearTimeout(timer);
+ release();
+ }
+ }
+
+ async function deleteSession() {
+ if (!sessionId || shuttingDown) return;
+ shuttingDown = true;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), DELETE_TIMEOUT_MS);
+ try {
+ await fetchImpl(proxyConfig.mcpUrl, {
+ method: "DELETE",
+ headers: headersForRequest(true),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ logError("delete_session_failed", err);
+ } finally {
+ clearTimeout(timer);
+ sessionId = "";
+ }
+ }
+
+ async function reinitialize(failedSessionId) {
+ if (!initializeRequest) {
+ throw new Error("MCP session expired before initialize parameters were cached");
+ }
+ if (reinitializeInFlight) return reinitializeInFlight;
+ reinitializeInFlight = (async () => {
+ if (failedSessionId && sessionId && sessionId !== failedSessionId) return;
+ const reinit = cloneMessage(initializeRequest);
+ reinit.id = `openviking-proxy-reinit-${Date.now()}-${++reinitCounter}`;
+ sessionId = "";
+ const result = await postToMcp(reinit, { includeSession: false });
+ if (initializedNotification) {
+ await postToMcp(cloneMessage(initializedNotification), { includeSession: true });
+ }
+ log("reinitialized", { mcpUrl: proxyConfig.mcpUrl, status: result.status, sessionId: Boolean(sessionId) });
+ })().finally(() => {
+ reinitializeInFlight = null;
+ });
+ return reinitializeInFlight;
+ }
+
+ async function sendWithRetry(message, { expectsResponse }) {
+ if (message.method !== "initialize" && initializeInFlight) {
+ await initializeInFlight.catch(() => {});
+ }
+
+ const failedSessionId = sessionId;
+ try {
+ return await postToMcp(message, { includeSession: message.method !== "initialize" });
+ } catch (err) {
+ if (err instanceof HttpStatusError && (err.status === 401 || err.status === 403)) {
+ if (reloadIfCredentialFilesChanged("auth_failure")) {
+ sessionId = "";
+ if (message.method !== "initialize" && initializeRequest) {
+ await reinitialize(failedSessionId);
+ }
+ return await postToMcp(message, { includeSession: message.method !== "initialize" });
+ }
+ }
+ if (
+ err instanceof HttpStatusError
+ && (err.status === 400 || err.status === 404)
+ && message.method !== "initialize"
+ && initializeRequest
+ ) {
+ await reinitialize(failedSessionId);
+ return await postToMcp(message, { includeSession: true });
+ }
+ if (!expectsResponse) {
+ logError("notification_failed", err);
+ }
+ throw err;
+ }
+ }
+
+ async function handleMessage(message) {
+ if (!message || typeof message !== "object" || message.jsonrpc !== "2.0") {
+ await writeMessage(errorResponse(null, -32600, "Invalid JSON-RPC message"));
+ return;
+ }
+
+ const expectsResponse = isRequest(message);
+ if (message.method === "initialize") {
+ initializeRequest = cloneMessage(message);
+ protocolVersion = DEFAULT_PROTOCOL_VERSION;
+ sessionId = "";
+ }
+ if (message.method === "notifications/initialized") {
+ initializedNotification = cloneMessage(message);
+ }
+
+ try {
+ const localResult = await callLocalTool(message);
+ if (localResult !== null) {
+ if (expectsResponse) {
+ await writeMessage({ jsonrpc: "2.0", id: message.id, result: localResult });
+ }
+ return;
+ }
+ const send = sendWithRetry(message, { expectsResponse });
+ if (message.method === "initialize") {
+ initializeInFlight = send
+ .catch(() => {})
+ .finally(() => {
+ initializeInFlight = null;
+ });
+ }
+ const result = await send;
+ if (!expectsResponse) return;
+ if (result.messages.length === 0) {
+ await writeMessage(errorResponse(message.id, -32003, "OpenViking MCP upstream returned an empty response"));
+ return;
+ }
+ for (const outbound of result.messages) {
+ await writeMessage(appendLocalTools(message, outbound));
+ }
+ } catch (err) {
+ if (expectsResponse) {
+ await writeMessage(mapError(message, err));
+ } else {
+ logError("notification_unhandled", err);
+ }
+ }
+ }
+
+ async function handleLine(line) {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let message;
+ try {
+ message = JSON.parse(trimmed);
+ } catch {
+ await writeMessage(errorResponse(null, -32700, "Parse error"));
+ return;
+ }
+ await handleMessage(message);
+ }
+
+ async function closeAndExit(code = 0) {
+ await deleteSession();
+ await stdoutChain;
+ process.exit(code);
+ }
+
+ async function closeSession() {
+ await deleteSession();
+ await stdoutChain;
+ }
+
+ function start() {
+ log("start", {
+ mcpUrl: proxyConfig.mcpUrl,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath,
+ hasApiKey: Boolean(proxyConfig.apiKey),
+ });
+ const rl = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
+ rl.on("line", (line) => {
+ void handleLine(line);
+ });
+ rl.on("close", () => {
+ void closeAndExit(0);
+ });
+ process.on("SIGINT", () => {
+ void closeAndExit(130);
+ });
+ process.on("SIGTERM", () => {
+ void closeAndExit(143);
+ });
+ return { close: () => closeAndExit(0) };
+ }
+
+ return { start, handleMessage, parseSseMessages, closeSession };
+}
diff --git a/agent-plugins/servers/shared/workspace-peer.mjs b/agent-plugins/servers/shared/workspace-peer.mjs
new file mode 100644
index 000000000..6b5cd45ec
--- /dev/null
+++ b/agent-plugins/servers/shared/workspace-peer.mjs
@@ -0,0 +1,16 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+export function deriveWorkspacePeerId(cwd) {
+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");
+}
+
+export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {
+ const explicit = String(cfg.peerId || "").trim();
+ if (explicit) return { peerId: explicit, source: "explicit" };
+
+ if (cfg.workspacePeer !== false) {
+ const peerId = deriveWorkspacePeerId(cwd);
+ if (peerId) return { peerId, source: "workspace" };
+ }
+
+ return { peerId: "", source: "none" };
+}
diff --git a/agent-plugins/skills/openviking-memory/SKILL.md b/agent-plugins/skills/openviking-memory/SKILL.md
new file mode 100644
index 000000000..9dbd2a51a
--- /dev/null
+++ b/agent-plugins/skills/openviking-memory/SKILL.md
@@ -0,0 +1,80 @@
+---
+name: openviking-memory
+description: Recall and persist long-term memory through the OpenViking MCP tools. Use at the start of any substantive task (coding, configuration, debugging, multi-step or tool-based work) to retrieve relevant prior knowledge with find/search/read, and during or after work to persist durable facts, preferences, decisions, and lessons with remember/write. Do not use for casual chat or simple factual questions the model can answer directly.
+---
+
+# OpenViking Memory
+
+OpenViking is a long-term semantic memory store addressed by `viking://` URIs.
+This client has no lifecycle hooks, so nothing is recalled or captured
+automatically — you drive both halves of the loop with the `openviking` MCP
+tools:
+
+- Recall: `find`, `search`, `recall`, `read`, `list`, `tree`, `grep`, `glob`
+- Persist: `remember`, `write`, `edit`, `add_resource`
+- Maintain: `forget`, `health`
+
+Use only the tools the session actually registered — the exact set depends on
+the server version, and `tree`, `write`, and `edit` are absent on older
+deployments. If no OpenViking tools are registered at all, continue without
+memory. Do not fabricate tool calls or fall back to raw HTTP.
+
+## Recall: at task start
+
+1. Decide whether the request warrants memory. Retrieve for executable or
+ multi-step work, anything touching a system you may have seen before, and
+ recovery from failures. Skip retrieval for small talk and one-off trivia.
+2. Build one concise query from the task goal, domain objects, intended
+ operation, and constraints. After a failure, include the failed operation
+ and the stable part of the error message.
+3. Call `find` (fast, ranked results with URI + abstract + score) with
+ `limit` around 5-10. Use `search` when deeper intent analysis helps, or
+ `recall` for a server-assembled, token-budgeted context block. Scope with
+ `target_uri` when you know where to look, e.g.
+ `viking://user/memories/experiences` for prior task experience.
+4. Judge results by task and environment fit, not title similarity. `read` the
+ one to three exact file URIs likely to change how you execute. Ignore
+ sidecar files such as `.abstract.md`, `.overview.md`, and
+ `.relations.json`.
+5. If nothing relevant comes back, proceed without memory. Make at most one
+ focused follow-up search when execution fails for a materially new reason.
+
+Treat retrieved memory as advisory. Priority order: system and developer
+instructions, the current user request, current environment and tool evidence,
+then memory. Verify commands, paths, and versions against the present task;
+prior success never authorizes a destructive action now.
+
+## Persist: during and after work
+
+Because capture is not automatic here, durable information is lost unless you
+store it. When you encounter something worth keeping, persist it in the same
+session:
+
+- `remember(messages)` — the default. Pass the key exchange or a short factual
+ summary as role-tagged messages; the server extracts and files memories
+ (preferences, entities, events, experience) on its own. Use it when the user
+ says "remember this", states a lasting preference or decision, or when a
+ hard-won lesson (root cause, working procedure, environment quirk) emerges.
+- `write(uri, content)` / `edit` — when you need an exact document at a known
+ location, such as curated notes under `viking://user/` or shared reference
+ material under `viking://resources/`. Prefer `edit` over rewriting whole
+ files. If neither tool is registered, fall back to `remember`.
+- `add_resource` — to import external documents or URLs as searchable
+ resources.
+
+What to persist: stable preferences and conventions, environment facts,
+decisions with their rationale, and reusable procedures or fixes. What not to
+persist: secrets and credentials, transient state, speculation, or bulk
+transcript dumps — store conclusions, not scrollback.
+
+## Example
+
+User asks to fix a failing deployment:
+
+1. `find` with query `deployment image pull failure private registry`,
+ `target_uri: "viking://user/memories/experiences"`.
+2. `read` the most relevant experience URI; check its assumptions against the
+ current cluster before applying its steps.
+3. Fix the issue, verify the live result.
+4. `remember` a short summary of the root cause and the working fix so the
+ next session can recall it.
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index fee05c9b8..a090be344 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -146,6 +146,7 @@ const agentIntegrationSidebar = {
text: 'General Integration',
items: [
['14-openviking-helper.md', 'OpenViking Helper'],
+ ['15-agent-plugins.md', 'Agent Plugins 1.0'],
['06-mcp-clients.md', 'MCP Clients'],
['09-log-ingestion.md', 'Local Log Import'],
['08-community-plugins.md', 'Community Integrations']
@@ -179,6 +180,7 @@ const agentIntegrationSidebar = {
text: '通用接入',
items: [
['14-openviking-helper.md', 'OpenViking Helper'],
+ ['15-agent-plugins.md', 'Agent Plugins 1.0'],
['06-mcp-clients.md', 'MCP 客户端'],
['09-log-ingestion.md', '本地日志导入'],
['08-community-plugins.md', '社区集成']
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index 27e99f82a..9983c1101 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -16,6 +16,7 @@ OpenViking can act as the long-term memory and context backend for many agent ru
| **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, and threshold commit |
| **LangChain / LangGraph** | [LangChain and LangGraph](./07-langchain-langgraph.md) — retriever, tools, context backend, store, and middleware |
| **Multiple local coding agents / a desktop UI** | [OpenViking Helper](./14-openviking-helper.md) — visual agent setup, session inspection, and memory management |
+| **Any Agent Plugins 1.0 client** | [Agent Plugins 1.0 Package](./15-agent-plugins.md) — one portable package: `openviking-memory` skill plus the OpenViking MCP tools |
| **Manus / Claude Desktop / ChatGPT / other MCP clients** | [MCP Clients](./06-mcp-clients.md) — point any MCP-compatible client at the built-in `/mcp` endpoint |
| **ZCode / AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |
diff --git a/docs/en/agent-integrations/15-agent-plugins.md b/docs/en/agent-integrations/15-agent-plugins.md
new file mode 100644
index 000000000..837b1ee88
--- /dev/null
+++ b/docs/en/agent-integrations/15-agent-plugins.md
@@ -0,0 +1,97 @@
+# Agent Plugins 1.0 Package
+
+[Agent Plugins 1.0](https://agent-plugins.org/specification) is a vendor-neutral packaging format for extending AI coding agents. A plugin is a plain directory with a `plugin.json` manifest, Agent Skills auto-discovered under `skills/`, and optional MCP server declarations in `mcp.json` — one package that every conforming client loads the same way, instead of one bespoke integration per client.
+
+OpenViking ships that package at [`agent-plugins/`](https://github.com/volcengine/OpenViking/tree/main/agent-plugins) in the repository.
+
+## What's inside
+
+```
+agent-plugins/
+├── plugin.json # Agent Plugins 1.0 manifest (name: openviking)
+├── mcp.json # one stdio MCP server: "openviking"
+├── servers/
+│ ├── mcp-proxy.mjs # stdio -> streamable-HTTP proxy to the server's /mcp
+│ ├── config.mjs, debug-log.mjs # credential / config resolution
+│ └── shared/ # generated from examples/memory-plugin-shared/lib
+├── skills/openviking-memory/SKILL.md # teaches the model the recall + persist loop
+└── plugin.test.mjs # node --test conformance checks
+```
+
+Zero npm dependencies — the proxy and the tests run on the Node.js standard library (Node 18+ for global `fetch`).
+
+## Install
+
+1. Have an OpenViking server reachable. If you don't, follow the [Quickstart](../getting-started/02-quickstart.md); the default local endpoint is `http://127.0.0.1:1933`.
+2. Point your Agent-Plugins-conforming client at the `agent-plugins/` directory. Each client has its own install command or plugin directory — consult its docs. On load the client will:
+ - register the `openviking` MCP server from `mcp.json`, running `node <plugin>/servers/mcp-proxy.mjs` over stdio;
+ - discover the `openviking-memory` skill from `skills/`.
+3. Configure credentials (below) and start a session. The model gains `find` / `search` / `recall` / `read` / `list` / `grep` / `glob` / `remember` / `add_resource` / `forget` / `health`, plus `tree` / `write` / `edit` on recent servers.
+
+## Why a stdio proxy instead of a `streamable-http` entry
+
+OpenViking already speaks streamable HTTP at `/mcp`, but a `streamable-http` entry in `mcp.json` cannot work portably: the server URL is per-deployment (localhost for one user, a remote endpoint for another), and the spec forbids credentials in the static `headers` map. The stdio proxy resolves both at runtime — it reads the URL and API key from the same local sources as the `ov` CLI, injects them per request, and forwards JSON-RPC over streamable HTTP unchanged.
+
+## Credential resolution
+
+Highest to lowest priority — the same chain as the `ov` CLI and the other OpenViking plugins:
+
+1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
+2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account`, `user`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
+3. `~/.openviking/ov.conf`, `server` section (`url`, or `host` / `port`, and `root_api_key`) — override the path with `OPENVIKING_CONFIG_FILE`
+4. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
+
+```json
+// ~/.openviking/ovcli.conf
+{
+ "url": "https://openviking.example.com",
+ "api_key": "your-api-key"
+}
+```
+
+Config file changes are picked up by the running proxy without a restart.
+
+Debugging: set `OPENVIKING_DEBUG=1` to write JSON lines to `~/.openviking/logs/agent-plugins.log` (override the path with `OPENVIKING_DEBUG_LOG`). Set `OPENVIKING_TIMEOUT_MS` to change the 15s per-request timeout.
+
+## Scope: hooks are intentionally absent
+
+Agent Plugins 1.0 covers skills and MCP servers only — hooks, commands, and agents are deliberately outside the version, because their semantics differ too much between clients. So this package is the **portable recall + write surface**, driven by the model rather than by lifecycle events: automatic conversation capture and automatic pre-prompt recall are out of scope here.
+
+The bundled `openviking-memory` skill compensates by teaching the model the full loop itself — recall at task start with `find` / `search` / `recall` + `read`, then persist durable facts with `remember` / `write` / `edit`, with priority and safety rules for using retrieved memory.
+
+**If your harness has its own hook system, prefer the dedicated plugin.** Hook-driven recall and capture happen without the model spending tool calls or deciding to remember, which is both cheaper and more reliable than the skill-driven loop. Use this Agent Plugins package for harnesses that have no hooks, or when you want one package that works across many clients.
+
+One installer covers Claude Code, Codex, Cursor, TRAE / TRAE CN, ZCode, OpenCode, and pi. It asks for your language, which harnesses to install, the download source, and your OpenViking credentials, and every step is idempotent:
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
+```
+
+In regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
+```
+
+| Harness | Dedicated integration |
+|---------|-----------------------|
+| Claude Code | [Claude Code Memory Plugin](./02-claude-code.md) |
+| Codex | [Codex Memory Plugin](./04-codex.md) |
+| OpenCode | [OpenCode Plugin](./10-opencode.md) |
+| Cursor | [Cursor Memory Integration](./12-cursor.md) |
+| TRAE / TRAE CN | [TRAE Memory Integration](./13-trae.md) |
+| pi | [pi Coding Agent Extension](./11-pi.md) |
+| OpenClaw | [OpenClaw Plugin](./03-openclaw.md) — separate install flow |
+| ZCode | [Community Integrations](./08-community-plugins.md) |
+
+Per the spec, client-specific integrations can later be embedded in this same package under reverse-domain namespaced directories (e.g. `com.example.client/`) or the manifest's `extensions` field, without breaking other clients.
+
+## Development
+
+```bash
+node --test agent-plugins/plugin.test.mjs
+```
+
+`plugin.test.mjs` checks manifest schema URLs and matching spec versions, the plugin name rules, the closed manifest root, semver, that every `skills/*` child ships a `SKILL.md` with `name` + `description` frontmatter matching its directory, that `mcp.json` entries reference files that exist and stay inside the plugin root, and that `node --check` passes on every `.mjs` in the package.
+
+`servers/shared/*.mjs` are generated copies of `examples/memory-plugin-shared/lib` — edit the shared lib and re-run `node examples/memory-plugin-shared/sync.mjs`; `examples/memory-plugin-shared/sync.test.mjs` fails if they drift. Both test files run in CI.
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 2d421a4a4..81f203b3a 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -16,6 +16,7 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
| **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获与阈值 commit |
| **LangChain / LangGraph** | [LangChain 和 LangGraph](./07-langchain-langgraph.md) — retriever、tools、context backend、store 和 middleware |
| **多个本地开发 Agent / 希望使用桌面界面** | [OpenViking Helper](./14-openviking-helper.md) — 可视化完成 Agent 接入、会话分析和记忆管理 |
+| **任意支持 Agent Plugins 1.0 的客户端** | [Agent Plugins 1.0 插件包](./15-agent-plugins.md) — 一个可移植的包:`openviking-memory` 技能 + OpenViking MCP 工具 |
| **Manus / Claude Desktop / ChatGPT / 其他 MCP 客户端** | [MCP 客户端](./06-mcp-clients.md) — 任何兼容 MCP 的客户端直接对接内置 `/mcp` 端点 |
| **ZCode / AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |
diff --git a/docs/zh/agent-integrations/15-agent-plugins.md b/docs/zh/agent-integrations/15-agent-plugins.md
new file mode 100644
index 000000000..94bbed7c0
--- /dev/null
+++ b/docs/zh/agent-integrations/15-agent-plugins.md
@@ -0,0 +1,97 @@
+# Agent Plugins 1.0 插件包
+
+[Agent Plugins 1.0](https://agent-plugins.org/specification) 是一套与厂商无关的 AI 编码 Agent 插件打包规范。一个插件就是一个普通目录:`plugin.json` 清单、`skills/` 下自动发现的 Agent Skills,以及可选的 `mcp.json` MCP 服务声明。所有符合规范的客户端都以同样的方式加载它 —— 不再需要为每个客户端各写一套接入。
+
+OpenViking 的这个插件包位于仓库的 [`agent-plugins/`](https://github.com/volcengine/OpenViking/tree/main/agent-plugins) 目录。
+
+## 目录结构
+
+```
+agent-plugins/
+├── plugin.json # Agent Plugins 1.0 清单(name: openviking)
+├── mcp.json # 一个 stdio MCP server:"openviking"
+├── servers/
+│ ├── mcp-proxy.mjs # stdio -> streamable-HTTP 代理,转发到服务端 /mcp
+│ ├── config.mjs, debug-log.mjs # 凭据 / 配置解析
+│ └── shared/ # 由 examples/memory-plugin-shared/lib 生成
+├── skills/openviking-memory/SKILL.md # 教模型完成「召回 + 沉淀」闭环
+└── plugin.test.mjs # node --test 规范一致性校验
+```
+
+零 npm 依赖 —— 代理和测试只用 Node.js 标准库(需要 Node 18+ 以获得全局 `fetch`)。
+
+## 安装
+
+1. 准备一个可访问的 OpenViking 服务。还没有的话,先按 [快速开始](../getting-started/02-quickstart.md) 部署;本地默认端点是 `http://127.0.0.1:1933`。
+2. 让你的 Agent Plugins 客户端指向 `agent-plugins/` 目录。各客户端的安装命令或插件目录不同,请查阅其文档。加载时客户端会:
+ - 按 `mcp.json` 注册名为 `openviking` 的 MCP server,以 stdio 方式运行 `node <plugin>/servers/mcp-proxy.mjs`;
+ - 从 `skills/` 发现 `openviking-memory` 技能。
+3. 配置凭据(见下节)后开始会话。模型即可使用 `find` / `search` / `recall` / `read` / `list` / `grep` / `glob` / `remember` / `add_resource` / `forget` / `health`,较新的服务端还提供 `tree` / `write` / `edit`。
+
+## 为什么用 stdio 代理,而不是 `streamable-http`
+
+OpenViking 服务端本身在 `/mcp` 上就是 streamable HTTP,但 `mcp.json` 里直接写 `streamable-http` 条目无法做到可移植:服务地址因部署而异(有人是 localhost,有人是远端),而规范禁止把凭据写进静态 `headers`。stdio 代理同时解决这两点 —— 它在运行时从与 `ov` CLI 相同的本地来源解析 URL 和 API Key,逐请求注入,再把 JSON-RPC 原样通过 streamable HTTP 转发。
+
+## 凭据解析顺序
+
+从高到低 —— 与 `ov` CLI 及其他 OpenViking 插件完全一致:
+
+1. 环境变量:`OPENVIKING_URL`(或 `OPENVIKING_BASE_URL`)、`OPENVIKING_API_KEY`(或 `OPENVIKING_BEARER_TOKEN`)、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`
+2. `~/.openviking/ovcli.conf`(`url`、`api_key`、`account`、`user`)—— 可用 `OPENVIKING_CLI_CONFIG_FILE` 覆盖路径
+3. `~/.openviking/ov.conf` 的 `server` 段(`url`,或 `host` / `port`,以及 `root_api_key`)—— 可用 `OPENVIKING_CONFIG_FILE` 覆盖路径
+4. 默认值:`http://127.0.0.1:1933`,不鉴权(本地模式)
+
+```json
+// ~/.openviking/ovcli.conf
+{
+ "url": "https://openviking.example.com",
+ "api_key": "your-api-key"
+}
+```
+
+配置文件的改动会被运行中的代理自动读取,无需重启。
+
+调试:设置 `OPENVIKING_DEBUG=1`,日志以 JSON Lines 写入 `~/.openviking/logs/agent-plugins.log`(路径可用 `OPENVIKING_DEBUG_LOG` 覆盖)。`OPENVIKING_TIMEOUT_MS` 可调整默认 15s 的单请求超时。
+
+## 能力边界:规范不含 hooks
+
+Agent Plugins 1.0 只覆盖 skills 和 MCP servers;hooks、commands、agents 被有意排除在本版本之外,因为它们在各客户端之间语义差异太大。因此这个包提供的是**可移植的召回 + 写入能力面**,由模型驱动而非生命周期事件驱动:**自动会话捕获和 prompt 前自动召回不在此范围内**。
+
+作为补偿,内置的 `openviking-memory` 技能直接把这套闭环教给模型 —— 任务开始时用 `find` / `search` / `recall` + `read` 召回,过程中和结束后用 `remember` / `write` / `edit` 沉淀,并给出使用召回内容时的优先级与安全规则。
+
+**如果你的 harness 支持 hooks 机制,推荐使用专属插件。** hook 驱动的召回与捕获不需要模型花费工具调用、也不依赖模型「想起来要记」,比技能驱动的闭环更省 token、也更可靠。本 Agent Plugins 包适用于没有 hooks 的 harness,或你希望用同一个包覆盖多个客户端的场景。
+
+Claude Code、Codex、Cursor、TRAE / TRAE CN、ZCode、OpenCode、pi 共用同一个安装脚本。它会依次询问界面语言、要安装的 harness、下载源和 OpenViking 凭据,所有步骤幂等,重复运行安全:
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
+```
+
+GitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个脚本:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
+```
+
+| Harness | 专属集成 |
+|---------|----------|
+| Claude Code | [Claude Code 记忆插件](./02-claude-code.md) |
+| Codex | [Codex 记忆插件](./04-codex.md) |
+| OpenCode | [OpenCode 插件](./10-opencode.md) |
+| Cursor | [Cursor 记忆集成](./12-cursor.md) |
+| TRAE / TRAE CN | [TRAE 记忆集成](./13-trae.md) |
+| pi | [pi Coding Agent 扩展](./11-pi.md) |
+| OpenClaw | [OpenClaw 插件](./03-openclaw.md) — 独立安装流程 |
+| ZCode | [社区集成](./08-community-plugins.md) |
+
+按规范,客户端专属的集成后续也可以放进同一个包里 —— 使用反向域名命名的目录(如 `com.example.client/`)或清单的 `extensions` 字段 —— 且不会影响其他客户端。
+
+## 开发
+
+```bash
+node --test agent-plugins/plugin.test.mjs
+```
+
+`plugin.test.mjs` 会校验:清单的 schema URL 及两个清单的规范版本一致、插件 name 规则、清单根字段闭集、semver、每个 `skills/*` 子目录都有带 `name` + `description` frontmatter 且 `name` 与目录同名的 `SKILL.md`、`mcp.json` 引用的文件存在且不逃逸插件根目录,以及包内所有 `.mjs` 都能通过 `node --check`。
+
+`servers/shared/*.mjs` 是 `examples/memory-plugin-shared/lib` 的生成副本 —— 请改共享库后重新执行 `node examples/memory-plugin-shared/sync.mjs`;一旦漂移,`examples/memory-plugin-shared/sync.test.mjs` 会失败。两个测试文件都已接入 CI。
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index 09718e9b0..2f6c05d48 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -22,12 +22,19 @@ const HARNESS_SHARED_FILES = [
"uri-guard.mjs",
];
const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs", "async-writer.mjs", "batch-send.mjs"];
+const AGENT_PLUGINS_SHARED_FILES = [
+ "credentials.mjs",
+ "debug-log.mjs",
+ "mcp-proxy-core.mjs",
+ "workspace-peer.mjs",
+];
const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
+ { dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjs
index 91363016e..59126b630 100644
--- a/examples/memory-plugin-shared/sync.test.mjs
+++ b/examples/memory-plugin-shared/sync.test.mjs
@@ -19,12 +19,19 @@ const HARNESS_SHARED_FILES = [
"uri-guard.mjs",
];
const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs", "async-writer.mjs", "batch-send.mjs"];
+const AGENT_PLUGINS_SHARED_FILES = [
+ "credentials.mjs",
+ "debug-log.mjs",
+ "mcp-proxy-core.mjs",
+ "workspace-peer.mjs",
+];
const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
+ { dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";