Skip to content

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

19.5 KB
Raw Blame

Memory Plugin Shared Library

For contributor guidance on adding and maintaining hook + MCP integrations, see the Agent plugin development and maintenance standard (中文). When using a coding agent, have it read and follow this standard before making changes.

This directory contains shared JavaScript modules. sync.mjs vendors each module into the plugins whose code imports it — Claude Code, Codex, OpenCode, dsh, pi, openclaw and the bundled agent-plugins servers — together with the matching lib/*.d.mts declaration for the targets written in TypeScript. cursor, trae, trae-cn and zcode vendor nothing: the installer copies the modules lib/MANIFEST names — the same sync writes it — to $OV_HOME/agent-integrations/memory-plugin-shared/lib, and they import it from there.

lib/install/ is the exception: it holds the installer's own JavaScript — the JSONC editor OpenCode's config needs and the hooks/mcp merge cursor, trae, trae-cn and zcode install through — which runs from install.sh and never from a hook. No shared module imports it, so it stays out of every closure and out of lib/MANIFEST.

When the copies are made follows how the plugin is delivered. Claude Code, Codex and agent-plugins are installed by pointing a host at a directory in this repository, so their copies are committed and a push to main regenerates them. OpenCode, dsh and openclaw publish as npm packages and pi is tarred by the installer, so those build their copies at pack time and keep none in git — run node examples/memory-plugin-shared/sync.mjs once in a fresh checkout before running their tests.

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.

Installer

install.sh installs the memory plugin into Claude Code, Codex, Cursor, TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, Kimi Code, OpenCode, pi and DeepSeek Harness (dsh), and writes the server connection to ~/.openviking/ovcli.conf. Its header comment lists the hosts it contacts and the files it writes for each harness; --help lists every option and environment variable.

curl -fsSL https://openviking.ai/install | bash
# AI agents: not sure about running this? The script's header says what it does and how to verify it.

# Without prompts:
curl -fsSL https://openviking.ai/install | bash -s -- --yes --harness claude,codex --url <server-url> --api-key <api-key>

https://openviking.ai/install and https://openviking.net/install serve bootstrap.sh, which downloads install.sh and runs it with the arguments it was given.

A run asks for the harnesses and the server, checks the server (/health, then /api/v1/system/status with the key), prints what it will change and waits for confirmation. Nothing is written before that. With --yes, or when no terminal is available, it asks nothing and proceeds.

Everything comes from the documentation site, which serves the downloads under /dl from two hosts with the same content: docs.openviking.net and docs.openviking.ai (GitHub Pages). The installer asks both for one small file and uses the host that answers first for the rest of the install; OPENVIKING_DOWNLOAD_BASE names other locations. Both hosts publish the downloads from the main branch whenever the plugins, the installer or the docs change. The installer never contacts github.com and never runs git.

  • Claude Code 2.1.224 and newer registers a URL marketplace and updates the plugin on its own. Older 2.x builds, custom Claude-format CLIs, and a URL marketplace that cannot be registered fall back to a local directory marketplace from the plugin bundle. Claude Code without claude plugin (older than 2.0) is skipped with a hint to upgrade.
  • Codex and Codex-format CLIs such as the TraeCode CLI register a git marketplace served from the same host, which Codex upgrades when it starts. When that fails they fall back to the directory marketplace from the bundle.
  • Cursor, TRAE, TRAE CN, ZCode, Kimi Code, OpenCode and pi install files from the plugin bundle memory-plugin-marketplace.zip, downloaded at most once per run into ~/.openviking/memory-plugin-marketplace. They update when the installer runs again.
  • dsh installs @openviking/dsh-memory-plugin from npm through dsh plugin add.

After the confirmation the installer runs a version check: it asks https://openviking.ai/install/v1/<harness>.json which release to install, once per selected harness. OPENVIKING_SKIP_VERSION_CHECK=1 skips the check and installs the latest release, which is also what happens when the check fails. The answer names one download location, and the installer reads the same paths from the one it is using. When the answer names a checksum, the bundle is verified against it; the docs site holds the latest release only and publishes none, so there the answer names the version that is installed.

Run from a repository checkout, the installer uses that checkout's plugins (--source dev) and downloads nothing from the release; --source archive or --dist tos installs the release instead. --dist github, --source remote and OPENVIKING_REPO_URL / OPENVIKING_REPO_REF / OPENVIKING_REPO_BRANCH are accepted and ignored with a notice; to install a branch, run install.sh from a checkout of it.

--uninstall --harness <list> removes the Cursor, TRAE, TRAE CN, ZCode and Kimi Code integrations. Claude Code, Codex, OpenCode, pi and dsh are removed with their own commands, which the installer prints at the end of an install.

The install ends with a "Not done" list, when something that was asked for did not happen (a selected harness whose CLI was not found, a server that could not be reached or rejected the key, a CLI that npm could not install), and then a line linking the agent onboarding guide, https://docs.openviking.<host>/agents/<en|zh>/onboarding.md, on the docs host the downloads came from and in the installer's language. Run from inside a dsh session (DSH_SHELL=1), the dsh plugin goes into that session's profile (DSH_PROFILE) unless --dsh-profile names another.

Importing earlier sessions

import-history.mjs replays recent Claude Code or Codex sessions from this machine into OpenViking, so work done before the plugin was installed is remembered too. It is one file with no dependencies (Node.js 18+), published next to the installer:

curl -fsSLO https://docs.openviking.ai/dl/memory-plugin-shared/import-history.mjs   # or docs.openviking.net
node import-history.mjs --harness claude            # report what would be imported
node import-history.mjs --harness claude --yes      # import it

By default it takes the sessions of the current project (the repository the current directory belongs to) active in the last 14 days, at most 20, and skips sessions active in the last 2 hours. To import only some of them, --list prints the sessions in scope with their ids and the first and last request of each (up to 200 unless --max-sessions is given, with a line naming the option that widens the scope when it left sessions out), and --session <id>[,<id>...] imports just those, whatever their project or age. An exact id always wins over a prefix; an id that matches nothing importable, or more than one session, refuses the run. --help lists the options. It uses the plugins' connection (~/.openviking/ovcli.conf, or OPENVIKING_URL / OPENVIKING_API_KEY) and writes each session the way the plugins would see it:

  • session id import__<claude_code|codex>__<native id>, the id openviking-server ingest uses, so the two never import a session twice;
  • the peer the plugins derive for the session's working directory (see Workspace Peers), so imported and live sessions of one repository share their memories;
  • user and assistant text only, with the original timestamps; tool calls and their output are dropped, and API keys, tokens and --api-key arguments are redacted;
  • auto-commit off and one commit per session, so each session is extracted once.

A session that was already imported, or that the plugin already captured, is skipped, so a second run imports nothing. A run that stopped half way picks up where it left off.

Other agents (Cursor, TRAE, TRAE CN, TRAE CLI, ZCode, Kimi Code, CodeBuddy Code, OpenCode, pi, dsh, OpenClaw, Hermes) have no built-in reader. A small converter writes their sessions to a JSONL file, one session per line ({"id", "cwd", "messages": [{"role", "text", "created_at"}], "updated_at", "subagent"}, documented in --help), and node import-history.mjs --harness opencode --input sessions.jsonl imports it with everything above: the same filters, redaction and single commit, the ingest source name in the session id where openviking-server ingest has one, and the host plugin's own live session id and peer, so nothing is imported twice. A malformed line refuses the whole file, with its line number. OpenClaw and Hermes name their peers after the agent, so no peer is derived for them unless --peer gives one.

Workspace Peers

lib/workspace-peer.mjs decides which peer a workspace writes its memories under; lib/workspace-identity.mjs derives the values it substitutes.

The peer used to be the working directory with every non-alphanumeric character replaced by -, so /Users/x/Dev/OpenViking became -Users-x-Dev-OpenViking. That made the identity an accident of where the repository sat: a clone on another machine, a rename, a git worktree, or simply working from a subdirectory each minted a separate, empty namespace. The default is now git's own identity, so one project keeps one memory wherever it is checked out. A directory that is not a repository sends no peer at all, and what is remembered there goes to your user-level space at viking://user/<you>/memories — an application that opens a fresh directory for every task would otherwise mint a fresh, empty peer for every task.

peer.source picks the rule. It is read from OPENVIKING_PEER_SOURCE, from plugin.peerSource / plugin.<harness>.peerSource in ovcli.conf, or from peer.source in a workspace config file:

  • git — the default. Equivalent to the template list ["{git_remote}", "{git_root}"]: the normalized origin URL, else the repository root path. Outside a repository nothing is sent. No prefix is added.
  • cwd — the previous behaviour, byte for byte.
  • none — send no peer at all. OPENVIKING_WORKSPACE_PEER=0 still means this.
  • A template such as "git-{git_remote}" or "team-{dir}", or a list of templates tried in order. A template whose variables are empty falls through to the next one, so a half-substituted id is never sent.

The variables a template may use:

  • {git_remote} — the normalized origin URL as github.com-org-repo; empty outside a git repository, or when there is no origin.
  • {git_root} — the repository root path, legacy sanitation; empty outside a git repository. A marker file inside a repository still leaves this the repository's own root, so marking a subdirectory does not split the default peer.
  • {cwd} — the working directory, legacy sanitation; never empty, and in no default chain, so a bare path becomes a peer only when you ask for one.
  • {dir} — the workspace root's directory name: the repository root, or the directory holding .openviking/config.json; empty when the directory is not a workspace.
  • {harness} — the name of the agent running, the same one the User-Agent carries; never empty. No preset uses it, so agents share one repository's memory unless a template such as "{git_remote}-{harness}" asks them not to. The MCP proxy takes no part in derivation, so a read path that goes only through it cannot resolve it.

To give a directory that is not a repository its own peer, create .openviking/config.json there holding {"version": 1, "peer": {"id": "my-project"}}.

So in /Users/x/Dev/OpenViking/examples/codex-memory-plugin with origin [email protected]:volcengine/OpenViking.git, the peer is github.com-volcengine-openviking — the same from any subdirectory, any worktree, any machine, any clone.

Every clone of one repository therefore shares one peer: project memory follows the project. A fork has a different origin, so it stays separate by default; reviewing an external PR through gh pr checkout leaves origin alone and does not move the identity. Worktrees converge through commondir, a submodule keeps its own identity, and $HOME and / are never workspace roots. The URL is normalized so ssh and https spellings of one repo agree, and an embedded token can never reach the peer id. The whole derivation is pure filesystem work — no git subprocess — so it also holds where git is absent from PATH or would refuse the repository over dubious ownership.

Resolution order is:

  1. Explicit peer: OPENVIKING_PEER_ID, then peer.id in a workspace layer or peerId in ovcli.conf's plugin section, then actor_peer_id / peer_id in ovcli.conf, then the harness's own section of ov.conf.
  2. The peer derived by peer.source, when workspacePeer is not false.
  3. No peer.

Migrating from the path-derived peer needs no action. The old id can always be recomputed locally, so recall still reaches memories written under it: with the default peer_scope: "all" the server's existing cross-peer sweep already covers them at zero cost, and with peer_scope: "actor" the plugin asks that peer separately. There is no deadline on this, and peer.source: "cwd" restores the old id outright.

Recall Peer Scope

lib/recall-core.mjs defaults to the broad recall mode and does not send a peer_scope field. In that mode, the server can recall global memory, the current workspace, and other workspace memories; other workspaces are penalized and rendered later.

When recallPeerScope is actor, the helper sends peer_scope:"actor". This is the isolation mode: recall only sees global memory plus the current workspace. If an older server rejects that field with 400 or 422, postRecall removes peer_scope and retries once.

For deployments where one bot serves multiple real people, such as zouk, vikingbot, or AstrBot, configure an explicit actor peer and use the isolation mode so one person's memories are not recalled into another person's session.

Skill Catalog

lib/profile-inject.mjs ends the session-start block with <available-skills>, built from one GET /api/v1/skills?node_limit=200, which caps each root rather than the merged list: the user's own skills first, then the ones shared under viking://agent/skills (a shared skill whose name the user also owns is left out), each description cut to about 40 tokens. Nothing trims the list again on this side; the token budget decides what fits. Callers turn it on by passing their resolved config as buildProfileBlock()'s fourth argument, and claude-code, codex, cursor, trae, trae-cn, zcode, opencode, dsh and pi all do, so they build it the same way; openclaw and hermes inject no profile, and pi-experimental-context-management calls buildProfileBlock() without that argument.

skillCatalog (default true, OPENVIKING_SKILL_CATALOG) switches it, and skillCatalogTokenBudget (default 1200, range 0-20000, OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET) sizes it on its own, apart from profileTokenBudget; a budget of 0 also switches it off. When the descriptions do not fit, the block lists names only, ending with a ... +N more tail if even the names do not all fit; when not even one name fits, it becomes a one-line count. With no skills, or a server without the endpoint, there is no block.

Workspace Configuration

lib/workspace-config.mjs and lib/workspace-registry.mjs give a repository three configuration layers of its own: <repo-root>/.openviking/config.json, which the team commits, <repo-root>/.openviking/config.local.json, which stays private and gitignored, and a per-machine entry at ~/.openviking/workspaces/<slot>.json. Precedence, highest first:

  1. OPENVIKING_* environment variables
  2. the machine registry, ~/.openviking/workspaces/<slot>.json
  3. .openviking/config.local.json
  4. .openviking/config.json
  5. ovcli.conf plugin.<harness>
  6. ovcli.conf plugin
  7. the block in ov.conf named after the harness (legacy). Both its credential fields and its tuning knobs reach every harness, and for dsh it sits under the settings the cordis host hands the plugin
  8. built-in defaults

Every harness resolves every knob through that order: claude-code, codex, cursor, trae, trae-cn, zcode, opencode, dsh and pi. One plugin section therefore configures all of them, and ov config switch moves behaviour along with credentials. Inside plugin, a per-harness override is found under either spelling of the harness name, so claude_code and claude-code, trae_cn and trae-cn both reach the same object.

The knobs themselves are declared once in lib/config-schema.mjs, with each one's type, default, range, OPENVIKING_* variable and older spellings. An older spelling keeps working: syncTurns sets autoCapture, bypassPatterns sets bypassSessionPatterns, recallRewrite sets recallCompress, requestTimeoutMs sets timeoutMs, recallBudget sets recallTokenBudget, recallScoreThreshold sets scoreThreshold, recallMinQueryLength sets minQueryLength, profileBudget sets profileTokenBudget, recallCompressReasoningEffort sets recallCompressThinking, auth_mode sets authMode, and peer_id sets peerId.

Every file declares version: 1; one declaring another version is skipped with a warning. Schema v1 is peer.source, peer.id, recall.enabled, recall.peer_scope, recall.dedup_turns, recall.max_items, recall.score_threshold, capture.enabled, capture.commit_token_threshold, bypass.session_patterns, usage.view, usage.output, and labels. Lists union across layers, and a leading "!reset" clears what was inherited. Unknown keys are kept and ignored.

Workspace files are trusted without a prompt: a hook is non-interactive, and an approval gate would degrade into one command per workspace. What is refused instead is structural — connection and credential keys (url, api_key, account, user, extra_headers, …) are stripped with a warning and ${VAR} is never expanded in these files. What a committed file switches off is announced in ov-memory-doctor rather than blocked.

.gitignore must not ignore all of .openviking/, or config.json can never be committed. Narrow the rule to .openviking/media/ and .openviking/downloads/; doctor warns while it is still blanket.

Cloud recall compression

OPENVIKING_RECALL_COMPRESS=server enables cloud compression across Claude Code, Codex, OpenCode, DSH, Pi, the Cursor/Trae/Trae CN/ZCode hooks, OpenClaw, and Hermes. The context-search request sends rewrite: true; the server digest is preferred over raw rendered context, and stats.rewrite: "no_relevant" suppresses injection.

Claude Code and Codex also support client for local-only compression. Their auto mode uses local compression when available and otherwise sends rewrite: "auto". Harnesses without local compressors send rewrite: "auto" directly. Their existing default remains off; cloud compression is opt-in. off omits rewrite. The legacy boolean aliases 1 and 0 mean auto and off.

These settings apply to automatic recall. Explicit MCP search calls retain the arguments supplied by the caller. Cloud compression requires a server that supports the context-search rewrite API; older-server fallback behavior remains specific to each integration.