Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(plugins): stdio MCP proxy, remote marketplace install, and type-quota recall for memory plugins (#3039)
t0sakif90556253456
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 000000000..ed9ae6c1c--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,20 @@+{+ "name": "openviking",+ "description": "OpenViking plugins for Claude Code.",+ "owner": {+ "name": "OpenViking"+ },+ "plugins": [+ {+ "name": "openviking-memory",+ "description": "Long-term semantic memory for Claude Code, powered by OpenViking",+ "source": {+ "source": "git-subdir",+ "url": "https://github.com/volcengine/OpenViking.git",+ "path": "examples/claude-code-memory-plugin",+ "ref": "main"+ },+ "category": "productivity"+ }+ ]+}diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex e84e98990..79e064e9a 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -18,6 +18,37 @@ on:- '.editorconfig'jobs:+ plugin-tests:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v6++ - uses: actions/setup-node@v6+ with:+ node-version: '20'++ - name: Run memory plugin tests+ run: |+ node --test \+ examples/codex-memory-plugin/servers/mcp-proxy.test.mjs \+ examples/codex-memory-plugin/scripts/auto-capture.test.mjs \+ examples/codex-memory-plugin/scripts/marketplace.test.mjs \+ examples/codex-memory-plugin/scripts/ov-credentials.test.mjs \+ examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjs \+ examples/codex-memory-plugin/scripts/auto-recall.test.mjs \+ examples/claude-code-memory-plugin/scripts/marketplace.test.mjs \+ examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs \+ examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs \+ examples/memory-plugin-shared/sync.test.mjs++ - name: Check installer scripts parse+ run: |+ bash -n examples/memory-plugin-shared/install.sh+ bash -n examples/claude-code-memory-plugin/setup-helper/install.sh+ bash -n examples/claude-code-memory-plugin/setup-helper/tos-install.sh+ bash -n examples/codex-memory-plugin/setup-helper/install.sh+ bash -n examples/codex-memory-plugin/setup-helper/tos-install.sh+check-deps:runs-on: ubuntu-24.04outputs:diff --git a/.github/workflows/release-tos.yml b/.github/workflows/release-tos.ymlindex c48900568..2f16056df 100644--- a/.github/workflows/release-tos.yml+++ b/.github/workflows/release-tos.yml@@ -73,6 +73,40 @@ jobs:git archive --format=zip --prefix="OpenViking-${RELEASE_TAG}/" \-o "/tmp/openviking-${RELEASE_TAG}-source.zip" HEAD+ - name: Build marketplace archive+ if: steps.tos_config.outputs.configured == 'true'+ run: |+ # Slim archive with just the memory plugins + marketplace manifests.+ # The shared installer registers the unzipped directory as a local+ # marketplace for both Claude Code and Codex (GitHub-free path).+ STAGE=/tmp/memory-plugin-marketplace+ rm -rf "${STAGE}"+ mkdir -p "${STAGE}"+ cp -R examples/.claude-plugin examples/.agents \+ examples/claude-code-memory-plugin examples/codex-memory-plugin \+ examples/memory-plugin-shared "${STAGE}/"+ (cd /tmp && zip -rq "memory-plugin-marketplace-${RELEASE_TAG}.zip" memory-plugin-marketplace)++ - name: Build marketplace git repo (dumb HTTP)+ if: steps.tos_config.outputs.configured == 'true'+ run: |+ # Slim single-commit bare repo served via git's dumb HTTP protocol+ # from TOS static hosting. Codex clones it directly and keeps remote+ # update support (`codex plugin marketplace upgrade`). Claude Code+ # cannot consume it (its shallow clones are rejected by dumb HTTP)+ # and uses the zip archive above instead.+ SRC=/tmp/memory-plugins-src+ rm -rf "${SRC}" /tmp/memory-plugins.git+ cp -R /tmp/memory-plugin-marketplace "${SRC}"+ git -C "${SRC}" init -q -b main+ git -C "${SRC}" add -A+ git -C "${SRC}" -c [email protected] -c user.name="OpenViking Release" \+ commit -qm "release ${RELEASE_TAG}"+ git clone -q --bare "${SRC}" /tmp/memory-plugins.git+ git -C /tmp/memory-plugins.git repack -adq+ git -C /tmp/memory-plugins.git update-server-info+ du -sh /tmp/memory-plugins.git+- name: Upload release artifacts to TOSif: steps.tos_config.outputs.configured == 'true'env:@@ -125,7 +159,22 @@ jobs:UPLOADED_KEYS="${UPLOADED_KEYS}- \`${key}\`"$'\n'}+ upload_dir() { # upload_dir <src-dir> <key-prefix>+ # Everything no-cache: the repo is tiny and git refs/packed-refs+ # must never be served stale after a release. --delete drops packs+ # from previous releases.+ aws s3 sync "${1}" "s3://${TOS_BUCKET}/${2}" \+ --endpoint-url "https://${TOS_S3_ENDPOINT}" \+ --delete \+ --cache-control "${NO_CACHE_CONTROL}" \+ --only-show-errors+ echo "Uploaded ${2}/"+ UPLOADED_KEYS="${UPLOADED_KEYS}- \`${2}/\`"$'\n'+ }+SOURCE_ZIP="/tmp/openviking-${RELEASE_TAG}-source.zip"+ MARKETPLACE_ZIP="/tmp/memory-plugin-marketplace-${RELEASE_TAG}.zip"+ SHARED_INSTALL="examples/memory-plugin-shared/install.sh"CLAUDE_INSTALL="examples/claude-code-memory-plugin/setup-helper/install.sh"CODEX_INSTALL="examples/codex-memory-plugin/setup-helper/install.sh"CLAUDE_TOS_INSTALL="examples/claude-code-memory-plugin/setup-helper/tos-install.sh"@@ -133,15 +182,21 @@ jobs:# Versioned, immutable copiesupload "${SOURCE_ZIP}" "releases/${RELEASE_TAG}/openviking-${RELEASE_TAG}-source.zip" "${ZIP_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"+ upload "${MARKETPLACE_ZIP}" "releases/${RELEASE_TAG}/memory-plugin-marketplace.zip" "${ZIP_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"+ upload_dir "/tmp/memory-plugins.git" "releases/${RELEASE_TAG}/memory-plugins.git"+ upload "${SHARED_INSTALL}" "releases/${RELEASE_TAG}/memory-plugin-shared/install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"upload "${CLAUDE_INSTALL}" "releases/${RELEASE_TAG}/claude-code-memory-plugin/install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"upload "${CODEX_INSTALL}" "releases/${RELEASE_TAG}/codex-memory-plugin/install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"upload "${CLAUDE_TOS_INSTALL}" "releases/${RELEASE_TAG}/claude-code-memory-plugin/tos-install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"upload "${CODEX_TOS_INSTALL}" "releases/${RELEASE_TAG}/codex-memory-plugin/tos-install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"- # Stable paths, overwritten on every release. The zip is copied- # server-side from the versioned key instead of re-transferring it.+ # Stable paths, overwritten on every release. The zips are copied+ # server-side from the versioned keys instead of re-transferring them.if [ "${UPDATE_LATEST}" = "true" ]; thenupload "s3://${TOS_BUCKET}/releases/${RELEASE_TAG}/openviking-${RELEASE_TAG}-source.zip" "releases/latest/openviking-source.zip" "${ZIP_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"+ upload "s3://${TOS_BUCKET}/releases/${RELEASE_TAG}/memory-plugin-marketplace.zip" "releases/latest/memory-plugin-marketplace.zip" "${ZIP_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"+ upload_dir "/tmp/memory-plugins.git" "plugins/memory-plugins.git"+ upload "${SHARED_INSTALL}" "memory-plugin-shared/install.sh" "${SHELL_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"upload "${CLAUDE_INSTALL}" "claude-code-memory-plugin/install.sh" "${SHELL_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"upload "${CODEX_INSTALL}" "codex-memory-plugin/install.sh" "${SHELL_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"upload "${CLAUDE_TOS_INSTALL}" "claude-code-memory-plugin/tos-install.sh" "${SHELL_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"diff --git a/.gitignore b/.gitignoreindex 12d855a48..bef692e50 100644--- a/.gitignore+++ b/.gitignore@@ -13,6 +13,8 @@ downloads/eggs/.eggs/lib/+# Shared memory-plugin JS source — not a Python build artifact.+!examples/memory-plugin-shared/lib/lib64/parts/sdist/diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.mdindex c9221dac4..55fff7fc7 100644--- a/docs/en/agent-integrations/02-claude-code.md+++ b/docs/en/agent-integrations/02-claude-code.md@@ -6,25 +6,21 @@ Source: [examples/claude-code-memory-plugin](https://github.com/volcengine/OpenV## Install-```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/claude-code-memory-plugin/setup-helper/install.sh)-```--The installer checks dependencies, configures your OpenViking connection, and installs the plugin. Every step is idempotent—re-running it is entirely safe.--In regions where GitHub is hard to reach, use the equivalent command below:+Claude Code and Codex share one installer. It asks for your language (English/中文), which harnesses to install, the download source, and your OpenViking credentials; every step is idempotent—re-running it is entirely safe.```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/claude-code-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)```-After installation, activate the `claude` wrapper in your current terminal (or simply open a new terminal window):+In regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror (or pick "TOS mirror" at the download-source prompt):```bash-source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-helper/wrapper.sh+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos```-> Launch Claude Code through a custom command? A wrapper script like `cc-custom`, or a multi-word launcher (a base command plus a sub-command) — list it at the installer's "Extra launch commands" step (or pass `OPENVIKING_CC_WRAP_EXTRA='cc-custom'`) to inject credentials there too.+> **TOS caveat for Claude Code**: the TOS channel registers a local directory marketplace, which cannot auto-update — re-run the installer to update. (Codex on TOS installs from a TOS-hosted git repo and keeps remote updates.)++No shell wrapper is needed anymore: the plugin ships a stdio MCP proxy that reads `~/.openviking/ovcli.conf` (or `OPENVIKING_*` env vars) at runtime, same as the hooks.After using it for a while, try starting a new conversation and asking about something you mentioned earlier—it will remember.@@ -33,41 +29,30 @@ After using it for a while, try starting a new conversation and asking about somIf you prefer to set it up manually:-1. **Wrap `claude`**: Add these two lines to the end of your `~/.zshrc` (for zsh) or `~/.bashrc` (for bash), replacing `<repo-path>` with the absolute path to your local repository. This ensures each `claude` invocation injects `OPENVIKING_URL` and `OPENVIKING_API_KEY` from `~/.openviking/ovcli.conf`, keeping the API key scoped to the `claude` process tree:-- ```bash- _ov_wrapper="<repo-path>/examples/claude-code-memory-plugin/setup-helper/wrapper.sh"- [ -f "$_ov_wrapper" ] && source "$_ov_wrapper"- ```-- For details on the function implementation and why a global `export` is not used, see the [plugin README → Configuring MCP](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuring-mcp).+1. **Configure the connection** — write `~/.openviking/ovcli.conf` (`url`, `api_key`, optional `account`/`user`), or run the bundled wizard `node <plugin-dir>/scripts/setup.mjs` after installing.-2. **Install the plugin** from the OpenViking repository root:+2. **Install the plugin** from the remote marketplace (no clone needed):```bash- claude plugin marketplace add "$(pwd)/examples"- claude plugin install claude-code-memory-plugin@openviking-plugins-local+ claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+ claude plugin install openviking-memory@openviking```-3. **Start Claude Code** and run `/mcp` to verify that the OpenViking entry displays your server URL.+ Or, for development, register a local checkout: `claude plugin marketplace add "<repo>/examples"` then install the same plugin id.++3. **Start Claude Code** and run `/mcp` to verify that the OpenViking entry is connected.> Don't have `ovcli.conf` yet? See the [Deployment Guide → CLI](../guides/03-deployment.md#cli).>> Using pure local mode (`http://127.0.0.1:1933`, no authentication)? Skip step 1—the plugin automatically defaults to the local setup.>-> Running Claude Code < 2.0? See the [Legacy mode section in the plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#legacy-mode-claude-code--20).+> Running Claude Code < 2.0? The installer detects it and falls back to `claude mcp add` + a hooks merge automatically; see the [Legacy mode section in the plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#legacy-mode-claude-code--20).</details>## Verify-```bash-type claude # expect: claude is a shell function-```--> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching `claude`, otherwise it silently connects to `127.0.0.1` with no auth.--Launch `claude` from the terminal where `type claude` reports a shell function, then:+Launch `claude`, then:- `/plugins` → Verify that **openviking-memory** is listed under "Installed", with the **openviking** MCP connected below it.- `/mcp` → Ensure the OpenViking entry displays your server URL along with valid authentication.@@ -117,9 +102,8 @@ The plugin renders an OpenViking status indicator beneath your Claude Code input|---------|-------|-----|| Plugin is not activating | Missing `ov.conf` or `ovcli.conf` | Run the [installer](#install), or set `OPENVIKING_MEMORY_ENABLED=1` along with the URL/API_KEY environment variables || Hooks fire but recall is empty | Server is not running or the URL is incorrect | Check server health: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| MCP tools hit `127.0.0.1` instead of the remote server | Missing function wrapper | Ensure `type claude` outputs "shell function"; see [Manual setup](#install) |-| `type claude` shows a path instead of a shell function (wrapper inactive) | The rc wasn't `source`d after install, or you launched from a terminal that didn't load it | Run `source ~/.zshrc` (or `~/.bashrc` on bash), or open a new terminal |-| Launching via an alias (e.g. `cc`) injects no credentials | The alias *name* was listed in `OPENVIKING_CC_WRAP_EXTRA` (alias names are skipped), or the alias's target command isn't wrapped | Wrap the command the alias points to, not the alias: `alias cc=claude` needs nothing; for `alias cc=claude-custom`, add `claude-custom` |+| MCP tools hit `127.0.0.1` instead of the remote server | `~/.openviking/ovcli.conf` has no `url` (the proxy falls back to the local default) | Fix `ovcli.conf` (or run `node <plugin-dir>/scripts/setup.mjs`), then restart Claude Code |+| MCP tool calls fail with an auth error | The active ovcli config has no valid `api_key` for an authenticated server | Update the `api_key` in `ovcli.conf`; the stdio proxy re-reads it after auth failures || Remote auth 401 / 403 | Incorrect API key or missing tenant headers | Verify `OPENVIKING_API_KEY`; for multi-tenant setups, also check `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |## See alsodiff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.mdindex d1d144df7..5fe03a878 100644--- a/docs/en/agent-integrations/04-codex.md+++ b/docs/en/agent-integrations/04-codex.md@@ -6,49 +6,45 @@ Source: [examples/codex-memory-plugin](https://github.com/volcengine/OpenViking/## Install+Claude Code and Codex share one installer. It asks for your language (English/中文), which harnesses to install, the download source, and your OpenViking credentials; every step is idempotent.+```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/codex-memory-plugin/setup-helper/install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)```-The installer checks dependencies, configures the OpenViking connection, and registers the plugin. Every step is idempotent.--In regions where GitHub is hard to reach, use the equivalent command below:+In regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror (or pick "TOS mirror" at the download-source prompt). Codex installs from a TOS-hosted git repo and keeps remote update support:```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos```-After installation, activate the `codex` wrapper in your current terminal (or open a new terminal window):+No shell wrapper is needed anymore — the plugin ships a stdio MCP proxy that reads `~/.openviking/ovcli.conf` (or `OPENVIKING_*` env vars) at runtime, same as the hooks. After installing:```bash-source ~/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.shcodex # First run: approve hooks once when prompted via /hooks```-> Launch Codex through a custom command? A wrapper script like `codex-custom`, or a multi-word launcher (a base command plus a sub-command) — list it at the installer's "Extra launch commands" step (or pass `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'`) to inject credentials there too.-<details><summary><b>Manual setup</b></summary>-Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature enabled.+Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `plugin_hooks` feature enabled.++1. **Configure the connection** — write `~/.openviking/ovcli.conf` (`url`, `api_key`, optional `account`/`user`), or run the bundled wizard `node <plugin-dir>/scripts/setup.mjs` after installing.-1. **Shell function wrapper** — Source the plugin wrapper from your shell profile (e.g., `.bashrc` or `.zshrc`) so Codex receives the active `ovcli.conf` credentials, MCP is re-rendered, and stale inherited credential env vars are stripped. See the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) for the snippet.+2. **Install the plugin** from the remote marketplace:-2. **Plugin installation** — Register a local marketplace and enable the plugin. See `setup-helper/install.sh` for the exact commands.+ ```bash+ codex plugin marketplace add volcengine/OpenViking+ codex plugin add openviking-memory@openviking+ ```-3. **Placeholder rendering** — The provided `.mcp.json` and `hooks.json` files contain placeholders that must be substituted when copied to Codex's plugin cache. The automated installer handles this for you.+ Then enable plugin hooks in `~/.codex/config.toml` if your build doesn't already: `[features]` → `plugin_hooks = true`. Update later with `codex plugin marketplace upgrade openviking`.</details>## Verify-```bash-type codex # Expectation: codex is a shell function-```--> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching, otherwise Codex may start without the credentials needed by MCP.--Once inside Codex, the plugin should seamlessly recall memories on every prompt. Set `OPENVIKING_DEBUG=1` to write events to `~/.openviking/logs/codex-hooks.log`.+Launch `codex`; the plugin should seamlessly recall memories on every prompt. Set `OPENVIKING_DEBUG=1` to write events to `~/.openviking/logs/codex-hooks.log`.## How it works@@ -59,7 +55,7 @@ The plugin integrates with Codex's lifecycle by hooking into key events. It sear<details><summary><b>Configuration</b></summary>-Credential source: active `ovcli.conf` wins by default (`OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`), so `ov config switch <name>` changes hooks, MCP, and child `ov` commands together on the next launch. Set `OPENVIKING_CREDENTIAL_SOURCE=env` only when you intentionally want env vars to override the CLI config; the wrapper then writes a mode-0600 runtime ovcli config under `~/.openviking/codex-plugin-state/` so child `ov` commands still match. Without an ovcli config, env vars then `ov.conf` then built-in defaults are used.+Credential source: active `ovcli.conf` wins by default (`OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`), so `ov config switch <name>` changes hooks, MCP proxy, and child `ov` commands together on the next launch. Set `OPENVIKING_CREDENTIAL_SOURCE=env` only when you intentionally want env vars to override the CLI config. Without an ovcli config, env vars then `ov.conf` then built-in defaults are used.| Env Var | Default | Description ||---------|---------|-------------|@@ -79,13 +75,11 @@ Additional tuning options (e.g., `OPENVIKING_RECALL_LIMIT`, `OPENVIKING_CAPTURE_| Symptom | Cause | Fix ||---------|-------|-----|-| `MCP server is not logged in` | Credentials were not injected at Codex launch, or the active ovcli config has no `api_key` for an authenticated server | Ensure the `codex()` shell function is sourced and `ovcli.conf` contains a valid `api_key`. |-| `type codex` shows a path instead of a shell function (wrapper inactive) | The rc wasn't `source`d after install, or you launched from a terminal that didn't load it | Run `source ~/.zshrc` (or `~/.bashrc` on bash), or open a new terminal |-| Launching via an alias (e.g. `cx`) injects no credentials | The alias *name* was listed in `OPENVIKING_CODEX_WRAP_EXTRA` (alias names are skipped), or the alias's target command isn't wrapped | Wrap the command the alias points to, not the alias: `alias cx=codex` needs nothing; for `alias cx=codex-custom`, add `codex-custom` |+| MCP tool calls fail with an auth error | The active ovcli config has no valid `api_key` for an authenticated server | Fix `~/.openviking/ovcli.conf` (or run `node <plugin-dir>/scripts/setup.mjs`) and restart Codex; the stdio proxy re-reads it on launch and after auth failures. |+| MCP tool calls fail with a connection error | Server unreachable or the URL is wrong | Check the endpoint: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` || `4 hooks need review` | Security review on first launch | Run `/hooks` within Codex and approve the hooks. |-| `hook (failed) exited with code 1` | Stale placeholders in the plugin cache | Re-run the one-line installer. |-| Recall returns nothing | Server is unreachable or the URL is incorrect | Check the endpoint: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| Hook 401 but MCP works (or vice versa) | Cached MCP config or launch env is stale | Restart Codex through the wrapper. If you intentionally use env credentials, set `OPENVIKING_CREDENTIAL_SOURCE=env`; otherwise use `ov config switch <name>` or `OPENVIKING_CLI_CONFIG_FILE`. |+| Plugin still targets an old server after `ov config switch` | Codex keeps the proxy process from the previous session | Restart Codex; the proxy resolves credentials at startup. |+| Hooks use one server, MCP another | `OPENVIKING_CREDENTIAL_SOURCE=env` set with stale env vars in one context | Unset it (ovcli.conf then drives both), or make the env vars consistent. |## See alsodiff --git a/docs/images/agents/en/claude-code.md b/docs/images/agents/en/claude-code.mdindex d27cee32b..382a3773c 100644--- a/docs/images/agents/en/claude-code.md+++ b/docs/images/agents/en/claude-code.md@@ -5,18 +5,12 @@ Source: [examples/claude-code-memory-plugin](https://github.com/volcengine/OpenV## Step 1: Install```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/claude-code-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness claude --dist tos```-The installer checks dependencies, configures the OpenViking connection, and installs the plugin. Each step is idempotent, so it is safe to rerun.+Claude Code and Codex share this one installer. It asks for your language (English/中文) and OpenViking credentials; each step is idempotent, so it is safe to rerun. No shell wrapper is needed anymore — the plugin ships a stdio MCP proxy that reads `~/.openviking/ovcli.conf` at runtime.-After installation, activate the `claude` wrapper in your current terminal, or simply open a new terminal window:--```bash-source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-helper/wrapper.sh-```--> Launch Claude Code through a custom command? A wrapper script like `cc-custom`, or a multi-word launcher (a base command plus a sub-command) — list it at the installer's "Extra launch commands" step (or pass `OPENVIKING_CC_WRAP_EXTRA='cc-custom'`) to inject credentials there too.+> The TOS channel registers a local directory marketplace, which cannot auto-update — re-run the command above to update.After using it for a while, start a new conversation and ask about something you mentioned earlier. It should remember.@@ -25,41 +19,28 @@ After using it for a while, start a new conversation and ask about something youIf you prefer to install manually:-1. **Wrap `claude`** - Add these two lines to the end of `~/.zshrc` (for zsh) or `~/.bashrc` (for bash), replacing `<repo-path>` with the absolute path to your local checkout. Each `claude` invocation then injects `OPENVIKING_URL` and `OPENVIKING_API_KEY` from `~/.openviking/ovcli.conf`, keeping the API key scoped to the `claude` process tree:-- ```bash- _ov_wrapper="<repo-path>/examples/claude-code-memory-plugin/setup-helper/wrapper.sh"- [ -f "$_ov_wrapper" ] && source "$_ov_wrapper"- ```-- For the function implementation and why a global `export` is not used, see the [plugin README -> Configuring MCP](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuring-mcp).+1. **Configure the connection** - write `~/.openviking/ovcli.conf` (`url`, `api_key`, optional `account`/`user`), or run the bundled wizard `node <plugin-dir>/scripts/setup.mjs` after installing.-2. **Install the plugin** from the OpenViking repository root:+2. **Install the plugin** from the remote marketplace (needs GitHub access):```bash- claude plugin marketplace add "$(pwd)/examples"- claude plugin install claude-code-memory-plugin@openviking-plugins-local+ claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+ claude plugin install openviking-memory@openviking```-3. **Start Claude Code** and run `/mcp` to confirm the OpenViking entry shows your server URL.+3. **Start Claude Code** and run `/mcp` to confirm the OpenViking entry is connected.> No `ovcli.conf` yet? Create it first via Deployment Guide -> CLI.>> Pure local mode (`http://127.0.0.1:1933`, no auth)? Skip step 1. The plugin uses the local defaults.>-> Claude Code < 2.0? See the [compatibility mode section](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#legacy-mode-claude-code--20) in the plugin README.+> Claude Code < 2.0? The installer detects it and falls back to compatibility mode automatically; see the [compatibility mode section](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#legacy-mode-claude-code--20) in the plugin README.</details>## Step 2: Verify-```bash-type claude # Expected: claude is a shell function-```--> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching `claude`, otherwise it silently connects to `127.0.0.1` with no auth.--Launch `claude` from the terminal where `type claude` reports a shell function, then:+Launch `claude`, then:- `/plugins` -> Find **openviking-memory** under Installed. Its **openviking** MCP entry should be connected.- `/mcp` -> The OpenViking entry should show your server URL and valid authentication.diff --git a/docs/images/agents/en/codex.md b/docs/images/agents/en/codex.mdindex 49e6177b8..5fa1c809b 100644--- a/docs/images/agents/en/codex.md+++ b/docs/images/agents/en/codex.md@@ -5,42 +5,38 @@ Source: [examples/codex-memory-plugin](https://github.com/volcengine/OpenViking/## Step 1: Install```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness codex --dist tos```-The installer checks dependencies, configures the OpenViking connection, and registers the plugin. Each step is idempotent, meaning it is safe to rerun the script at any time.+Claude Code and Codex share this one installer. It asks for your language (English/中文) and OpenViking credentials; each step is idempotent, so it is safe to rerun. On the TOS channel Codex installs from a TOS-hosted git repo and can update later with `codex plugin marketplace upgrade openviking`.-After installation, activate the `codex` wrapper in your current terminal (or simply open a new terminal window):+No shell wrapper is needed anymore — the plugin ships a stdio MCP proxy that reads `~/.openviking/ovcli.conf` at runtime. After installing:```bash-source ~/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.shcodex # approve hooks once via /hooks on first launch```-> Launch Codex through a custom command? A wrapper script like `codex-custom`, or a multi-word launcher (a base command plus a sub-command) — list it at the installer's "Extra launch commands" step (or pass `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'`) to inject credentials there too.-<details><summary><b>Manual installation</b></summary>-Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature enabled.+Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `plugin_hooks` feature enabled.++1. **Configure the connection** - write `~/.openviking/ovcli.conf` (`url`, `api_key`, optional `account`/`user`), or run the bundled wizard `node <plugin-dir>/scripts/setup.mjs` after installing.-1. **Shell function wrapper** - Append a `codex()` function to your shell configuration file (e.g., `.bashrc` or `.zshrc`). Each invocation injects OpenViking environment variables from `ovcli.conf`. Refer to the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) for the complete function.+2. **Install the plugin** from the remote marketplace (needs GitHub access):-2. **Install the plugin** - Register the local marketplace and enable the plugin. See `setup-helper/install.sh` for the exact commands required.+ ```bash+ codex plugin marketplace add volcengine/OpenViking+ codex plugin add openviking-memory@openviking+ ```-3. **Render placeholders** - Placeholders in `.mcp.json` and `hooks.json` must be replaced with absolute paths or values when copied into the Codex cache. The automated installer handles this for you.+ Then enable plugin hooks in `~/.codex/config.toml` if your build doesn't already: `[features]` → `plugin_hooks = true`.</details>## Step 2: Verify-```bash-type codex # Expected: codex is a shell function-```--> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching, otherwise codex starts without `OPENVIKING_API_KEY` and reports `MCP server is not logged in`.--Inside Codex, the plugin will now recall memory before every prompt. You can set `OPENVIKING_DEBUG=1` to log events to `~/.openviking/logs/codex-hooks.log`.+Launch `codex`; the plugin will now recall memory before every prompt. You can set `OPENVIKING_DEBUG=1` to log events to `~/.openviking/logs/codex-hooks.log`.## How it works@@ -69,13 +65,10 @@ For tuning options such as `OPENVIKING_RECALL_LIMIT` and `OPENVIKING_CAPTURE_ASS| Symptom | Cause | Fix ||---------|-------|-----|-| `MCP server is not logged in` | `OPENVIKING_API_KEY` is missing from the startup environment | Confirm the `codex()` function has been sourced and `ovcli.conf` contains an `api_key` |-| `type codex` shows a path instead of a shell function (wrapper inactive) | The rc wasn't `source`d after install, or you launched from a terminal that didn't load it | Run `source ~/.zshrc` (or `~/.bashrc` on bash), or open a new terminal |-| Launching via an alias (e.g. `cx`) injects no credentials | The alias *name* was listed in `OPENVIKING_CODEX_WRAP_EXTRA` (alias names are skipped), or the alias's target command isn't wrapped | Wrap the command the alias points to, not the alias: `alias cx=codex` needs nothing; for `alias cx=codex-custom`, add `codex-custom` |+| MCP tool calls fail with an auth error | `ovcli.conf` has no valid `api_key` for an authenticated server | Fix `ovcli.conf` (or run `node <plugin-dir>/scripts/setup.mjs`) and restart Codex |+| MCP tool calls fail with a connection error | Server is unreachable or the URL is incorrect | Run `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` to test the connection || `4 hooks need review` | First-launch security approval is required | Type `/hooks` in Codex and approve them |-| `hook (failed) exited with code 1` after approval | Placeholders in the cache were not properly rendered | Rerun the one-line install script |-| Recall is empty | Server is unreachable or the URL is incorrect | Run `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` to test the connection |-| Hooks get 401 while MCP works, or vice versa | Environment variables and `ovcli.conf` are out of sync | Hooks re-read `ovcli.conf` each time; MCP reads the environment at startup. Restart Codex after making changes. |+| Plugin still targets an old server after `ov config switch` | Codex keeps the proxy process from the previous session | Restart Codex; the stdio proxy resolves credentials at startup |## Reference docsdiff --git a/docs/images/agents/zh/claude-code.md b/docs/images/agents/zh/claude-code.mdindex c38ebb48d..42277005d 100644--- a/docs/images/agents/zh/claude-code.md+++ b/docs/images/agents/zh/claude-code.md@@ -5,18 +5,12 @@## 步骤 1:安装```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/claude-code-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness claude --dist tos```-该脚本将自动检查依赖项、配置 OpenViking 连接并完成插件安装,支持重复运行(幂等操作)。+Claude Code 和 Codex 共用这一个安装脚本。它会依次询问界面语言(English/中文)和 OpenViking 凭据;所有步骤幂等,支持重复运行。不再需要任何 shell wrapper——插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`。-安装完成后,需在当前终端激活 `claude` 的封装函数(wrapper),或者直接打开一个新的终端窗口:--```bash-source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-helper/wrapper.sh-```--> 通过自定义命令启动 Claude Code?例如包装脚本 `cc-custom`,或“基础命令 + 子命令”形式的多词启动器——在安装时的“Extra launch commands”一步填入(或运行脚本时传入 `OPENVIKING_CC_WRAP_EXTRA='cc-custom'`),即可让它们一并注入凭据。+> TOS 渠道注册的是本地目录 marketplace,无法自动更新——更新请重跑上面的安装命令。使用一段时间后,即便在全新的对话中提及过往的话题,Claude Code 也能准确回忆起来。@@ -25,42 +19,29 @@ source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-he如果您倾向于手动安装:-1. **封装 `claude` 命令** — 在 `~/.zshrc`(zsh)或 `~/.bashrc`(bash)文件末尾追加以下代码,并将 `<仓库路径>` 替换为您本地克隆仓库的绝对路径。此操作可确保每次调用 `claude` 时,系统都会从 `~/.openviking/ovcli.conf` 动态注入 `OPENVIKING_URL` 和 `OPENVIKING_API_KEY`,且 API Key 仅在 `claude` 的进程树内有效:-- ```bash- _ov_wrapper="<仓库路径>/examples/claude-code-memory-plugin/setup-helper/wrapper.sh"- [ -f "$_ov_wrapper" ] && source "$_ov_wrapper"- ```-- 关于该函数的具体实现以及“为何不使用全局 `export`”的详细说明,请参阅 [插件 README → Configuring MCP](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuring-mcp)。+1. **配置连接** — 手写 `~/.openviking/ovcli.conf`(`url`、`api_key`,可选 `account`/`user`),或装完后运行插件自带向导 `node <插件目录>/scripts/setup.mjs`。-2. **安装插件** — 在 OpenViking 仓库根目录下执行:+2. **安装插件** — 从远程 marketplace(需可访问 GitHub):```bash- claude plugin marketplace add "$(pwd)/examples"- claude plugin install claude-code-memory-plugin@openviking-plugins-local+ claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+ claude plugin install openviking-memory@openviking```-3. **启动 Claude Code** — 运行后输入 `/mcp` 命令,确认 OpenViking 对应的服务器 URL 配置正确。+3. **启动 Claude Code** — 运行后输入 `/mcp` 命令,确认 OpenViking 条目已连接。> 尚未创建 `ovcli.conf`?请先按照部署指南 → CLI 的说明进行配置。>> 使用纯本地模式(`http://127.0.0.1:1933`,无鉴权)?您可以跳过第 1 步,插件将直接使用本地默认值。>-> 使用 Claude Code < 2.0 版本?请参考 [插件 README 的兼容模式章节](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#兼容模式claude-code--20)。+> 使用 Claude Code < 2.0 版本?安装脚本会自动识别并回退到兼容模式;详见 [插件 README 的兼容模式章节](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#兼容模式claude-code--20)。</details>## 步骤 2:验证-```bash-type claude # 期望输出:claude is a shell function-```--> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 `claude` 会静默连到本地 `127.0.0.1` 且不带鉴权。--在 `type claude` 显示为 shell function 的终端中运行 `claude` 启动,随后:+启动 `claude`,随后:- 输入 `/plugins` → 在 Installed 列表中应能找到 **openviking-memory**(其子项 **openviking** MCP 应显示为已连接状态)。- 输入 `/mcp` → OpenViking 对应的条目应显示您的服务器 URL 及有效的认证信息。@@ -113,9 +94,7 @@ type claude # 期望输出:claude is a shell function|------|------|------|| 插件未激活 | 未找到 `ov.conf` 或 `ovcli.conf` 配置文件 | 运行 [步骤 1:安装](#步骤-1安装),或手动设置 `OPENVIKING_MEMORY_ENABLED=1` 配合 URL/API_KEY 使用。 || Hook 已触发但召回结果为空 | 服务器未启动或 URL 配置错误 | 执行命令测试连通性:`curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| MCP 工具连接到了 `127.0.0.1` 而非远程服务器 | 缺少 `claude` 函数封装 | 检查 `type claude` 的输出是否包含 "shell function";详情见 [步骤 1:安装](#步骤-1安装) |-| `type claude` 显示的是路径而非 shell function(wrapper 未生效) | 安装后未 `source` rc,或在未加载该 rc 的终端里启动 | 执行 `source ~/.zshrc`(bash 用 `~/.bashrc`),或新开一个终端窗口 |-| 通过别名(如 `cc`)启动,凭据未注入 | 把别名名填进了 `OPENVIKING_CC_WRAP_EXTRA`(别名会被跳过),或别名指向的命令未被封装 | 封装别名指向的真实命令而非别名本身:`alias cc=claude` 无需配置;`alias cc=claude-custom` 则把 `claude-custom` 填入 |+| MCP 工具连接到了 `127.0.0.1` 而非远程服务器 | `~/.openviking/ovcli.conf` 中没有 `url`(代理回退到本地默认值) | 修正 `ovcli.conf`(或运行 `node <插件目录>/scripts/setup.mjs`)后重启 Claude Code || 远程认证失败 (401 / 403) | API Key 错误或缺少租户 Header | 检查 `OPENVIKING_API_KEY` 是否正确;多租户环境下还需核对 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |diff --git a/docs/images/agents/zh/codex.md b/docs/images/agents/zh/codex.mdindex 11f202a71..8cf858559 100644--- a/docs/images/agents/zh/codex.md+++ b/docs/images/agents/zh/codex.md@@ -5,43 +5,39 @@## 步骤 1:安装```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness codex --dist tos```-该脚本会自动检查依赖、配置 OpenViking 连接并注册插件。所有步骤均具有幂等性,可安全地重复执行。+Claude Code 和 Codex 共用这一个安装脚本。它会依次询问界面语言(English/中文)和 OpenViking 凭据;所有步骤幂等,可安全地重复执行。Codex 走 TOS 时安装自 TOS 托管的 git 仓库,之后可用 `codex plugin marketplace upgrade openviking` 远程更新。-安装完成后,在当前终端激活 `codex` 封装函数(或重新打开一个终端窗口):+不再需要任何 shell wrapper——插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`。安装完成后:```bash-source ~/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.shcodex # 首次启动需执行 /hooks 进行一次安全审批```-> 通过自定义命令启动 Codex?例如包装脚本 `codex-custom`,或“基础命令 + 子命令”形式的多词启动器——在安装时的“Extra launch commands”一步填入(或运行脚本时传入 `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'`),即可让它们一并注入凭据。-<details><summary><b>手动安装</b></summary>-前置条件:Node.js >= 22、Codex >= 0.130.0,且已启用 `codex_hooks` 特性。+前置条件:Node.js >= 22、Codex >= 0.130.0,且已启用 `plugin_hooks` 特性。++1. **配置连接** — 手写 `~/.openviking/ovcli.conf`(`url`、`api_key`,可选 `account`/`user`),或装完后运行插件自带向导 `node <插件目录>/scripts/setup.mjs`。-1. **Shell 函数包装** — 在 shell 的配置文件(如 `.bashrc` 或 `.zshrc`)中追加一个 `codex()` 函数,以便在每次调用时从 `ovcli.conf` 注入 OpenViking 环境变量。完整函数代码请见 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md)。+2. **从远程 marketplace 安装插件**(需可访问 GitHub):-2. **插件安装** — 注册本地 marketplace 并启用该插件。具体命令请参考 `setup-helper/install.sh`。+ ```bash+ codex plugin marketplace add volcengine/OpenViking+ codex plugin add openviking-memory@openviking+ ```-3. **占位符渲染** — `.mcp.json` 和 `hooks.json` 中的占位符在拷贝至 Codex 缓存时需替换为绝对路径。安装程序会自动完成此操作。+ 若你的 Codex 版本未默认启用 plugin hooks,在 `~/.codex/config.toml` 中加上 `[features]` → `plugin_hooks = true`。</details>## 步骤 2:验证-```bash-type codex # 期望输出:codex is a shell function-```--> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 codex 启动时拿不到 `OPENVIKING_API_KEY`,会报 `MCP server is not logged in`。--进入 Codex 后,插件将在每次输入前自动召回记忆。将环境变量 `OPENVIKING_DEBUG` 设置为 `1`,可将事件日志输出至 `~/.openviking/logs/codex-hooks.log`。+启动 `codex` 后,插件将在每次输入前自动召回记忆。将环境变量 `OPENVIKING_DEBUG` 设置为 `1`,可将事件日志输出至 `~/.openviking/logs/codex-hooks.log`。## 工作原理@@ -72,13 +68,10 @@ type codex # 期望输出:codex is a shell function| 现象 | 原因 | 解决方案 ||------|------|------|-| `MCP server is not logged in` | 启动时 `OPENVIKING_API_KEY` 未注入环境变量 | 确认 `codex()` 函数已被 `source` 激活,且 `ovcli.conf` 中包含 `api_key` |-| `type codex` 显示的是路径而非 shell function(wrapper 未生效) | 安装后未 `source` rc,或在未加载该 rc 的终端里启动 | 执行 `source ~/.zshrc`(bash 用 `~/.bashrc`),或新开一个终端窗口 |-| 通过别名(如 `cx`)启动,凭据未注入 | 把别名名填进了 `OPENVIKING_CODEX_WRAP_EXTRA`(别名会被跳过),或别名指向的命令未被封装 | 封装别名指向的真实命令而非别名本身:`alias cx=codex` 无需配置;`alias cx=codex-custom` 则把 `codex-custom` 填入 |+| MCP 工具调用报认证错误 | `ovcli.conf` 中没有 authenticated server 所需的有效 `api_key` | 修正 `ovcli.conf`(或运行 `node <插件目录>/scripts/setup.mjs`)后重启 Codex |+| MCP 工具调用报连接错误 | 服务器不可达或 URL 配置错误 | 运行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查连接状态 || `4 hooks need review` | 首次启动触发的安全审批 | 在 Codex 中输入 `/hooks` 完成审批 |-| 审批后仍提示 `hook (failed) exited with code 1` | 缓存中的占位符未被正确替换 | 重新运行一次单行安装脚本 |-| 召回为空 | 服务器不可达或 URL 配置错误 | 运行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查连接状态 |-| Hook 返回 401 但 MCP 可用,或反之 | 环境变量与 `ovcli.conf` 配置不一致 | Hook 每次执行都会重新读取 `ovcli.conf`,而 MCP 仅在启动时读取环境变量。修改配置后请重启 Codex。 |+| `ov config switch` 后插件仍指向旧服务器 | 上个会话的代理进程仍在运行 | 重启 Codex;stdio 代理在启动时解析凭据 |## 参考文档diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.mdindex d2ebc6cf9..c7de094fd 100644--- a/docs/zh/agent-integrations/02-claude-code.md+++ b/docs/zh/agent-integrations/02-claude-code.md@@ -6,25 +6,21 @@## 安装-```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/claude-code-memory-plugin/setup-helper/install.sh)-```--该脚本将自动检查依赖项、配置 OpenViking 连接并完成插件安装,支持重复运行(幂等操作)。--GitHub 访问受限的地区,可改用以下等价命令:+Claude Code 和 Codex 共用同一个安装脚本。它会依次询问界面语言(English/中文)、要安装的 harness、下载源和 OpenViking 凭据;所有步骤幂等,重复运行安全。```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/claude-code-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)```-安装完成后,需在当前终端激活 `claude` 的封装函数(wrapper),或者直接打开一个新的终端窗口:+GitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个安装脚本(或在下载源提问时选择「TOS 镜像」):```bash-source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-helper/wrapper.sh+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos```-> 通过自定义命令启动 Claude Code?例如包装脚本 `cc-custom`,或“基础命令 + 子命令”形式的多词启动器——在安装时的“Extra launch commands”一步填入(或运行脚本时传入 `OPENVIKING_CC_WRAP_EXTRA='cc-custom'`),即可让它们一并注入凭据。+> **Claude Code 走 TOS 的注意事项**:TOS 渠道注册的是本地目录 marketplace,**无法自动更新**——更新请重跑安装脚本。(Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力。)++现在不再需要任何 shell wrapper:插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`(或 `OPENVIKING_*` 环境变量),与 hooks 使用同一套配置链。使用一段时间后,即便在全新的对话中提及过往的话题,Claude Code 也能准确回忆起来。@@ -33,41 +29,30 @@ source ~/.openviking/openviking-repo/examples/claude-code-memory-plugin/setup-he如果您倾向于手动安装:-1. **封装 `claude` 命令** — 在 `~/.zshrc`(zsh)或 `~/.bashrc`(bash)文件末尾追加以下代码,并将 `<仓库路径>` 替换为您本地克隆仓库的绝对路径。此操作可确保每次调用 `claude` 时,系统都会从 `~/.openviking/ovcli.conf` 动态注入 `OPENVIKING_URL` 和 `OPENVIKING_API_KEY`,且 API Key 仅在 `claude` 的进程树内有效:-- ```bash- _ov_wrapper="<仓库路径>/examples/claude-code-memory-plugin/setup-helper/wrapper.sh"- [ -f "$_ov_wrapper" ] && source "$_ov_wrapper"- ```-- 关于该函数的具体实现以及“为何不使用全局 `export`”的详细说明,请参阅 [插件 README → Configuring MCP](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuring-mcp)。+1. **配置连接** — 手写 `~/.openviking/ovcli.conf`(`url`、`api_key`,可选 `account`/`user`),或装完后运行插件自带向导 `node <插件目录>/scripts/setup.mjs`。-2. **安装插件** — 在 OpenViking 仓库根目录下执行:+2. **从远程 marketplace 安装插件**(无需 clone 仓库):```bash- claude plugin marketplace add "$(pwd)/examples"- claude plugin install claude-code-memory-plugin@openviking-plugins-local+ claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+ claude plugin install openviking-memory@openviking```-3. **启动 Claude Code** — 运行后输入 `/mcp` 命令,确认 OpenViking 对应的服务器 URL 配置正确。+ 开发场景也可注册本地 checkout:`claude plugin marketplace add "<仓库路径>/examples"`,插件 id 相同。++3. **启动 Claude Code** — 运行后输入 `/mcp` 命令,确认 OpenViking 条目已连接。> 尚未创建 `ovcli.conf`?请先按照 [部署指南 → CLI](../guides/03-deployment.md#cli) 的说明进行配置。>> 使用纯本地模式(`http://127.0.0.1:1933`,无鉴权)?您可以跳过第 1 步,插件将直接使用本地默认值。>-> 使用 Claude Code < 2.0 版本?请参考 [插件 README 的兼容模式章节](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#兼容模式claude-code--20)。+> 使用 Claude Code < 2.0 版本?安装脚本会自动识别并回退到 `claude mcp add` + hooks 合并;详见 [插件 README 的兼容模式章节](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#兼容模式claude-code--20)。</details>## 验证-```bash-type claude # 期望输出:claude is a shell function-```--> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 `claude` 会静默连到本地 `127.0.0.1` 且不带鉴权。--在 `type claude` 显示为 shell function 的终端中运行 `claude` 启动,随后:+启动 `claude`,随后:- 输入 `/plugins` → 在 Installed 列表中应能找到 **openviking-memory**(其子项 **openviking** MCP 应显示为已连接状态)。- 输入 `/mcp` → OpenViking 对应的条目应显示您的服务器 URL 及有效的认证信息。@@ -117,9 +102,8 @@ type claude # 期望输出:claude is a shell function|------|------|------|| 插件未激活 | 未找到 `ov.conf` 或 `ovcli.conf` 配置文件 | 运行 [安装脚本](#安装),或手动设置 `OPENVIKING_MEMORY_ENABLED=1` 配合 URL/API_KEY 使用。 || Hook 已触发但召回结果为空 | 服务器未启动或 URL 配置错误 | 执行命令测试连通性:`curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| MCP 工具连接到了 `127.0.0.1` 而非远程服务器 | 缺少 `claude` 函数封装 | 检查 `type claude` 的输出是否包含 "shell function";详情见 [手动安装](#安装) |-| `type claude` 显示的是路径而非 shell function(wrapper 未生效) | 安装后未 `source` rc,或在未加载该 rc 的终端里启动 | 执行 `source ~/.zshrc`(bash 用 `~/.bashrc`),或新开一个终端窗口 |-| 通过别名(如 `cc`)启动,凭据未注入 | 把别名名填进了 `OPENVIKING_CC_WRAP_EXTRA`(别名会被跳过),或别名指向的命令未被封装 | 封装别名指向的真实命令而非别名本身:`alias cc=claude` 无需配置;`alias cc=claude-custom` 则把 `claude-custom` 填入 |+| MCP 工具连接到了 `127.0.0.1` 而非远程服务器 | `~/.openviking/ovcli.conf` 中没有 `url`(代理回退到本地默认值) | 修正 `ovcli.conf`(或运行 `node <插件目录>/scripts/setup.mjs`)后重启 Claude Code |+| MCP 工具调用报认证错误 | 当前 ovcli 配置没有 authenticated server 所需的有效 `api_key` | 更新 `ovcli.conf` 中的 `api_key`;stdio 代理在认证失败后会重新读取配置 || 远程认证失败 (401 / 403) | API Key 错误或缺少租户 Header | 检查 `OPENVIKING_API_KEY` 是否正确;多租户环境下还需核对 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |## 参见diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.mdindex fe0baf2f6..237dab0c3 100644--- a/docs/zh/agent-integrations/04-codex.md+++ b/docs/zh/agent-integrations/04-codex.md@@ -6,49 +6,45 @@## 安装+Claude Code 和 Codex 共用同一个安装脚本。它会依次询问界面语言(English/中文)、要安装的 harness、下载源和 OpenViking 凭据;所有步骤幂等,可安全地重复执行。+```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/codex-memory-plugin/setup-helper/install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)```-脚本将自动检查依赖项、配置 OpenViking 连接并注册插件。安装过程的每一步均支持幂等操作,可安全地重复执行。--GitHub 访问受限的地区,可改用以下等价命令:+GitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个安装脚本(或在下载源提问时选择「TOS 镜像」)。Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力:```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos```-安装完成后,请在当前终端激活 `codex` 的封装函数(或新开一个终端窗口):+现在不再需要任何 shell wrapper——插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`(或 `OPENVIKING_*` 环境变量),与 hooks 使用同一套配置链。安装完成后:```bash-source ~/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.shcodex # 首次启动需进入 /hooks 完成一次审批```-> 通过自定义命令启动 Codex?例如包装脚本 `codex-custom`,或“基础命令 + 子命令”形式的多词启动器——在安装时的“Extra launch commands”一步填入(或运行脚本时传入 `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'`),即可让它们一并注入凭据。-<details><summary><b>手动安装</b></summary>-前置条件:需安装 Node.js >= 22、Codex >= 0.130.0,并启用 `codex_hooks` 特性。+前置条件:需安装 Node.js >= 22、Codex >= 0.130.0,并启用 `plugin_hooks` 特性。++1. **配置连接** — 手写 `~/.openviking/ovcli.conf`(`url`、`api_key`,可选 `account`/`user`),或装完后运行插件自带向导 `node <插件目录>/scripts/setup.mjs`。-1. **Shell 函数封装** — 在 shell 的配置文件(如 rc 文件)中 source 插件 wrapper,确保 Codex 使用当前激活的 `ovcli.conf` 凭据,同时刷新 MCP 配置并清掉继承来的过期凭据环境变量。代码片段请参考 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md)。+2. **从远程 marketplace 安装插件**:-2. **插件安装** — 注册本地 marketplace 并启用插件。具体执行命令请参见 `setup-helper/install.sh`。+ ```bash+ codex plugin marketplace add volcengine/OpenViking+ codex plugin add openviking-memory@openviking+ ```-3. **占位符渲染** — 在将 `.mcp.json` 和 `hooks.json` 复制到 Codex 缓存目录时,需将其中的占位符替换为绝对路径或具体数值。自动化安装脚本会自动完成此操作。+ 若你的 Codex 版本未默认启用 plugin hooks,在 `~/.codex/config.toml` 中加上 `[features]` → `plugin_hooks = true`。之后可用 `codex plugin marketplace upgrade openviking` 更新。</details>## 验证-```bash-type codex # 期望输出:codex is a shell function-```--> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 Codex 可能拿不到 MCP 所需凭据。--进入 Codex 后,插件将在每次用户输入前自动召回记忆。若设置环境变量 `OPENVIKING_DEBUG=1`,则会将相关事件日志写入 `~/.openviking/logs/codex-hooks.log`。+启动 `codex` 后,插件将在每次用户输入前自动召回记忆。若设置环境变量 `OPENVIKING_DEBUG=1`,则会将相关事件日志写入 `~/.openviking/logs/codex-hooks.log`。## 工作原理@@ -59,7 +55,7 @@ type codex # 期望输出:codex is a shell function<details><summary><b>配置</b></summary>-凭据来源:默认使用当前激活的 `ovcli.conf`(`OPENVIKING_CLI_CONFIG_FILE` 或 `~/.openviking/ovcli.conf`),因此 `ov config switch <name>` 会在下次启动时同时影响 hook、MCP 和 Codex 内部运行的 `ov` 命令。只有明确希望环境变量覆盖 CLI 配置时,才设置 `OPENVIKING_CREDENTIAL_SOURCE=env`;此时 wrapper 会在 `~/.openviking/codex-plugin-state/` 下写入 mode 0600 的运行时 ovcli 配置,让内部 `ov` 命令仍然使用同一套凭据。若没有 ovcli 配置,则依次回退到环境变量、`ov.conf` 和内置默认值。+凭据来源:默认使用当前激活的 `ovcli.conf`(`OPENVIKING_CLI_CONFIG_FILE` 或 `~/.openviking/ovcli.conf`),因此 `ov config switch <name>` 会在下次启动时同时影响 hook、MCP 代理和 Codex 内部运行的 `ov` 命令。只有明确希望环境变量覆盖 CLI 配置时,才设置 `OPENVIKING_CREDENTIAL_SOURCE=env`。若没有 ovcli 配置,则依次回退到环境变量、`ov.conf` 和内置默认值。| 环境变量 | 默认值 | 说明 ||---------|--------|------|@@ -79,13 +75,11 @@ type codex # 期望输出:codex is a shell function| 现象 | 可能原因 | 修复方法 ||------|------|------|-| `MCP server is not logged in` | Codex 启动时未注入凭据,或当前 ovcli 配置没有 authenticated server 所需的 `api_key` | 确认已 source `codex()` 函数,且 `ovcli.conf` 中配置了 `api_key` |-| `type codex` 显示的是路径而非 shell function(wrapper 未生效) | 安装后未 `source` rc,或在未加载该 rc 的终端里启动 | 执行 `source ~/.zshrc`(bash 用 `~/.bashrc`),或新开一个终端窗口 |-| 通过别名(如 `cx`)启动,凭据未注入 | 把别名名填进了 `OPENVIKING_CODEX_WRAP_EXTRA`(别名会被跳过),或别名指向的命令未被封装 | 封装别名指向的真实命令而非别名本身:`alias cx=codex` 无需配置;`alias cx=codex-custom` 则把 `codex-custom` 填入 |+| MCP 工具调用报认证错误 | 当前 ovcli 配置没有 authenticated server 所需的有效 `api_key` | 修正 `~/.openviking/ovcli.conf`(或运行 `node <插件目录>/scripts/setup.mjs`)后重启 Codex;stdio 代理会在启动时和认证失败后重新读取配置 |+| MCP 工具调用报连接错误 | 服务器不可达或 URL 配置错误 | 执行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查服务器状态 || `4 hooks need review` | 首次启动需要进行安全审批 | 在 Codex 终端内输入 `/hooks` 完成审批 |-| 审批后仍提示 `hook (failed) exited with code 1` | 缓存文件中的占位符未被正确渲染 | 重新执行一次一键安装脚本 |-| 召回结果为空 | 服务器不可达或 URL 配置错误 | 执行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查服务器状态 |-| Hook 报 401 但 MCP 正常可用,或反之 | MCP 缓存配置或启动环境已过期 | 通过 wrapper 重启 Codex。若确实要使用环境变量凭据,设置 `OPENVIKING_CREDENTIAL_SOURCE=env`;否则使用 `ov config switch <name>` 或 `OPENVIKING_CLI_CONFIG_FILE`。 |+| `ov config switch` 后插件仍指向旧服务器 | 上个会话的代理进程仍在运行 | 重启 Codex;代理在启动时解析凭据 |+| Hook 与 MCP 指向不同服务器 | 某一侧设置了 `OPENVIKING_CREDENTIAL_SOURCE=env` 且环境变量过期 | 取消该设置(让 ovcli.conf 同时驱动两者),或保证环境变量一致 |## 参见diff --git a/examples/.agents/plugins/marketplace.json b/examples/.agents/plugins/marketplace.jsonnew file mode 100644index 000000000..438b07c52--- /dev/null+++ b/examples/.agents/plugins/marketplace.json@@ -0,0 +1,21 @@+{+ "name": "openviking",+ "description": "OpenViking plugins for OpenAI Codex (local directory / archive install).",+ "interface": {+ "displayName": "OpenViking"+ },+ "plugins": [+ {+ "name": "openviking-memory",+ "source": {+ "source": "local",+ "path": "./codex-memory-plugin"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_USE"+ },+ "category": "Productivity"+ }+ ]+}diff --git a/examples/.claude-plugin/marketplace.json b/examples/.claude-plugin/marketplace.jsonindex 4fce8226b..b18d02293 100644--- a/examples/.claude-plugin/marketplace.json+++ b/examples/.claude-plugin/marketplace.json@@ -1,12 +1,12 @@{- "name": "openviking-plugins-local",- "description": "OpenViking plugins (local development)",+ "name": "openviking",+ "description": "OpenViking plugins for Claude Code (local directory / archive install).","owner": {"name": "OpenViking"},"plugins": [{- "name": "claude-code-memory-plugin",+ "name": "openviking-memory","description": "Long-term semantic memory for Claude Code, powered by OpenViking","source": "./claude-code-memory-plugin","category": "productivity"diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonindex 3bea5240d..45ba3bad9 100644--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openviking-memory",- "version": "0.2.2",+ "version": "0.3.0","description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.","author": {"name": "OpenViking",diff --git a/examples/claude-code-memory-plugin/.gitignore b/examples/claude-code-memory-plugin/.gitignoreindex a7150ebee..72b98d5e1 100644--- a/examples/claude-code-memory-plugin/.gitignore+++ b/examples/claude-code-memory-plugin/.gitignore@@ -1,7 +1,4 @@node_modules/-servers/*.mjs-servers/*.js-!servers/memory-server.js*.tsbuildinfo# Top-level .gitignore excludes lib/ (Python setuptools convention); the# plugin's scripts/lib/ is a JS module directory and must be tracked.diff --git a/examples/claude-code-memory-plugin/.mcp.json b/examples/claude-code-memory-plugin/.mcp.jsonindex bf7c60ca7..6b569c39c 100644--- a/examples/claude-code-memory-plugin/.mcp.json+++ b/examples/claude-code-memory-plugin/.mcp.json@@ -1,11 +1,8 @@{"openviking": {- "type": "http",- "url": "${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp",- "headers": {- "Authorization": "Bearer ${OPENVIKING_API_KEY:-}",- "X-OpenViking-Account": "${OPENVIKING_ACCOUNT:-}",- "X-OpenViking-User": "${OPENVIKING_USER:-}"- }+ "command": "node",+ "args": [+ "${CLAUDE_PLUGIN_ROOT}/servers/mcp-proxy.mjs"+ ]}}diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex 037eaa9ed..7b513a5f3 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -2,17 +2,17 @@Long-term semantic memory for Claude Code, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens automatically after every turn — no MCP tool calls required from the model.-> A public Claude Code plugin marketplace listing is planned but not yet published. For now, install from local source (see below).+> Installable straight from the repo's marketplace catalog — no separate distribution repo. See [Manual setup](#manual-setup) for the two-command remote install.## Quick Start### One-line installer (recommended)```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/claude-code-memory-plugin/setup-helper/install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude```-macOS / Linux only. The script verifies dependencies, asks whether you'll connect to a **self-hosted** server or to **Volcengine OpenViking Cloud** (`https://api.vikingdb.cn-beijing.volces.com/openviking`), sets up `~/.openviking/ovcli.conf` (prompts only if absent), clones the repo to `~/.openviking/openviking-repo`, adds the `claude` shell-function wrapper to your rc, and runs `claude plugin install`. Re-running is safe.+macOS / Linux only. Claude Code and Codex share this installer (drop `--harness claude` to pick interactively): it asks for your language (English/中文), the download source (GitHub, or a TOS mirror for GitHub-blocked regions — pass `--dist tos`), and your OpenViking credentials, then installs `openviking-memory` via the remote marketplace. The stdio MCP proxy reads `ovcli.conf` at runtime, so no shell wrapper or `.mcp.json` rendering is needed. Re-running is safe.If you'd rather do it by hand, follow the four steps below.@@ -47,16 +47,27 @@ If `ov.conf` is what you already maintain, the plugin reads it too — see [Conf#### 3. Install the plugin-The repo's `examples/.claude-plugin/marketplace.json` exposes the plugin as a local marketplace entry. From the OpenViking repo root:+**Remote marketplace (recommended)** — no clone needed. The repo root ships a `.claude-plugin/marketplace.json` whose entry fetches this plugin via `git-subdir`:++```bash+claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+claude plugin install openviking-memory@openviking+```++(`claude plugin marketplace add volcengine/OpenViking` works too, but clones the whole repo as the marketplace.)++If you skipped step 2, configure the connection afterwards: write `~/.openviking/ovcli.conf` by hand, run `node <plugin-dir>/scripts/setup.mjs` (an interactive wizard bundled with the plugin), or just run the one-line installer.++**Local directory (development)** — registers this checkout so edits to `scripts/` and `hooks/` take effect on the next hook invocation without reinstalling. From the OpenViking repo root:```bashclaude plugin marketplace add "$(pwd)/examples"-claude plugin install claude-code-memory-plugin@openviking-plugins-local+claude plugin install openviking-memory@openviking```-> Both commands install at user scope by default — the plugin is active from any directory. We don't pass `--scope user` explicitly because older Claude Code 2.0.x builds (e.g. 2.0.76) reject the flag. On newer builds that do accept `--scope`, you can lift a local-scoped install to user scope with `claude plugin enable claude-code-memory-plugin@openviking-plugins-local --scope user`.+> Both commands install at user scope by default — the plugin is active from any directory. We don't pass `--scope user` explicitly because older Claude Code 2.0.x builds (e.g. 2.0.76) reject the flag. On newer builds that do accept `--scope`, you can lift a local-scoped install to user scope with `claude plugin enable openviking-memory@openviking --scope user`.>-> The marketplace entry points Claude Code at the source directory. Edits to `scripts/`, `hooks/`, and config files take effect on the next hook invocation — no reinstall. But moving / renaming / deleting the source dir, or `git checkout`-ing to a branch without these files, breaks the plugin. A public marketplace listing for one-click install will follow.+> Directory-mode caveat: moving / renaming / deleting the source dir, or `git checkout`-ing to a branch without these files, breaks the plugin. Both modes register a marketplace named `openviking`, so the plugin id is always `openviking-memory@openviking`; switch modes by removing the marketplace and re-adding the other source (the installer does this automatically).##### Legacy mode (Claude Code < 2.0)@@ -65,12 +76,9 @@ claude plugin install claude-code-memory-plugin@openviking-plugins-local```bashPLUGIN_DIR="$(pwd)/examples/claude-code-memory-plugin"+# stdio MCP proxy — reads ovcli.conf / OPENVIKING_* itself, no header wiring needed.claude mcp remove openviking -s user 2>/dev/null-claude mcp add --scope user --transport http openviking \- '${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \- --header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \- --header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}'+claude mcp add --scope user openviking -- node "$PLUGIN_DIR/servers/mcp-proxy.mjs"# Merge plugin hooks into ~/.claude/settings.json (with backup).mkdir -p ~/.claude && [ -f ~/.claude/settings.json ] || echo '{}' > ~/.claude/settings.json@@ -82,7 +90,7 @@ jq -e . /tmp/ov-settings.json >/dev/null && mv /tmp/ov-settings.json ~/.claude/srm -f /tmp/ov-hooks.json```-The single-quoted `${VAR}` literals in `claude mcp add` are intentional — Claude Code expands them at MCP launch time using whatever the shell wrapper injects. Don't switch to double quotes; your shell would expand them to empty strings before the command runs. The one-line installer does all of this for you and prompts before touching `~/.claude/settings.json`.+The one-line installer automates exactly this when it detects a pre-2.0 build (it keeps a source checkout under `~/.openviking/openviking-repo` for the absolute paths above).#### 4. Start Claude Code@@ -94,51 +102,11 @@ If it doesn't seem to fire, set `OPENVIKING_DEBUG=1` and check `~/.openviking/lo## Configuring MCP-The plugin's hooks read `ovcli.conf` / `ov.conf` automatically. The bundled **MCP server entry does not** — Claude Code parses `.mcp.json` itself and supports **only `${VAR}` substitution**, so the plugin can't transparently feed config-file values into the MCP server URL or auth headers.+The plugin's hooks and MCP entry now use the same configuration chain. The checked-in `.mcp.json` starts `servers/mcp-proxy.mjs` as a local stdio MCP server; that proxy reads `OPENVIKING_*`, `~/.openviking/ovcli.conf`, and `~/.openviking/ov.conf`, then forwards JSON-RPC to the OpenViking server's native `/mcp` endpoint with the right auth and identity headers.-**Decision tree — do you need to do anything?**+For normal plugin installs, there is nothing extra to export and no `.mcp.json` value to render. Update `ovcli.conf` or the relevant `OPENVIKING_*` env vars and restart Claude Code; the proxy will use the same target as the hook scripts.-```-Where is your OpenViking server?-├─ Local (127.0.0.1, no auth)-│ └─ ✅ Nothing to do — the bundled .mcp.json already works.-└─ Remote- └─ ✅ Add the function-wrapper below to your shell rc.-```--**Recommended path — wrap `claude` to inject env from `ovcli.conf` on each invocation:**--```bash-# ~/.zshrc or ~/.bashrc-claude() {- local _ov_conf="${OPENVIKING_CLI_CONFIG_FILE:-$HOME/.openviking/ovcli.conf}"- if [ -f "$_ov_conf" ] && command -v jq >/dev/null 2>&1; then- local _ov_url _ov_key- _ov_url=$(jq -r '.url // empty' "$_ov_conf" 2>/dev/null)- _ov_key=$(jq -r '.api_key // empty' "$_ov_conf" 2>/dev/null)- OPENVIKING_URL="${OPENVIKING_URL:-$_ov_url}" \- OPENVIKING_API_KEY="${OPENVIKING_API_KEY:-$_ov_key}" \- command claude "$@"- else- command claude "$@"- fi-}-```--Re-source your rc (`source ~/.zshrc`, or `source ~/.bashrc` on bash) and restart `claude` — `/mcp` should then show your remote URL with valid auth.--**Wrapping extra launch commands.** If you start Claude Code through a different command — a custom wrapper like `cc-custom`, or a multi-word launcher (a base command plus a sub-command) — the installer can wrap those too. Answer its "Extra launch commands" prompt, or pass `OPENVIKING_CC_WRAP_EXTRA='cc-custom'` when running it. The list is stored in the same rc marker block (read by the wrapper as `$OPENVIKING_CC_WRAP_EXTRA`); for a multi-word entry, only invocations whose leading args match the sub-command get credentials injected, so every *other* use of that command passes through untouched. List the *real* launch command, never a shell alias of it: an alias expands to its target before the wrapper runs, so wrap what it points at — `alias cc=claude` already rides the base `claude` wrapper (add nothing), while `alias cc=claude-custom` is covered by listing `claude-custom`. Alias names are skipped if listed.--> **Why a function instead of `export`?** A globally exported API key leaks into every child process spawned from your shell — npm scripts, build tools, crash dumps, `/proc/<pid>/environ`. The function wrapper limits the secret to the `claude` process tree only.->-> Don't have `ovcli.conf` yet? See the [Deployment Guide → CLI](../../docs/en/guides/03-deployment.md#cli) to set one up.--**Other options if the function wrapper isn't viable:**--- **Edit the plugin's `.mcp.json` directly** with hardcoded values. Future plugin updates may overwrite it.-- **Add a separate MCP entry** to your project `.mcp.json` or `~/.claude.json`. See the [MCP integration guide](../../docs/en/guides/06-mcp-integration.md).--**Symptom of misconfiguration**: hooks (auto-recall, auto-capture) work fine because they read config files via Node, but the on-demand MCP tools (`search`, `read`, `store`, …) silently connect to `http://127.0.0.1:1933` with empty auth headers, and `/mcp` shows the wrong URL.+The proxy requires Node.js 18+ and writes debug logs only when `OPENVIKING_DEBUG=1` or `claude_code.debug=true` is configured. stdout is reserved for MCP protocol bytes.## Configuration@@ -151,11 +119,11 @@ Every plugin field follows this chain (highest → lowest):3. **`ov.conf`** — server config (`~/.openviking/ov.conf` or `OPENVIKING_CONFIG_FILE`); the plugin reads `server.url`, `server.root_api_key`, and a legacy `claude_code` block if present (see [Legacy `claude_code` block](#legacy-claude_code-block-in-ovconf))4. **Built-in defaults** (`http://127.0.0.1:1933`, no auth)-> ⚠️ **Hooks only.** This chain is implemented in `scripts/config.mjs` and consumed by hook scripts. It does **not** apply to MCP server registration — see [Configuring MCP](#configuring-mcp).+The same connection and identity fields are also used by the stdio MCP proxy.### Environment variables-All plugin behavior can be set via env vars. Connection / identity vars affect both hooks and (when exported in your shell rc) the MCP server; tuning vars only affect hooks.+All plugin behavior can be set via env vars. Connection / identity vars affect both hooks and the MCP proxy; tuning vars only affect hooks.#### Connection / identity@@ -267,14 +235,16 @@ The plugin renders a one-line status of OpenViking under your Claude Code inputExamples:```text-OV ✓ │ ↩ 6 mem (0.92) · 50ms last turn injected 6 memories, top score 0.92+OV ✓ │ Fable 5 · ctx 42% │ ↩ 6 mem (0.92) · 50ms 6 memories injected; model + context usageOV ⚠ slow probe missed the 1 s budget (server may be lagging)OV ✗ offline server unreachable-OV ⚡ bypass OPENVIKING_BYPASS_SESSION* matched+OV ⚡ bypass │ Fable 5 · ctx 42% OPENVIKING_BYPASS_SESSION* matchedOV ✓ │ ✎ 573/20k · 2 arch pending capture, two archives produced this sessionOV ✓ │ 🔗 resumed │ +3 today session re-hydrated; 3 archives committed today```+The `ctx` percentage reproduces Claude Code's native context indicator (a custom statusLine replaces it), with the native color thresholds: `<70%` dim, `70–89%` yellow, `≥90%` red. Hide it with `OPENVIKING_STATUSLINE_CTX=off`.+For the full segment glossary and personalization recipes (hide segments, recolor, compose with another statusline, add a custom segment), see [`STATUSLINE.md`](./STATUSLINE.md).Data flow:@@ -305,7 +275,7 @@ Set `claude_code.debug: true` in `ov.conf` or `OPENVIKING_DEBUG=1` to write hook| Plugin not activating | No `ov.conf` / `ovcli.conf` found | Create one, or set `OPENVIKING_MEMORY_ENABLED=1` plus the URL/API_KEY env vars || Hooks fire but recall is empty | OpenViking server not running, or wrong URL | `curl http://localhost:1933/health` (or your remote URL) || Auto-capture extracts 0 memories | Wrong embedding/extraction model in `ov.conf` | Check `embedding` / `vlm` config; review server logs |-| MCP tools hit `127.0.0.1` instead of remote| `.mcp.json` only resolves `${VAR}`, no ovcli.conf integration | See [Configuring MCP](#configuring-mcp) — export env vars or edit `.mcp.json` |+| MCP tools hit the wrong server | stale `ovcli.conf` / env vars, or Claude Code not restarted after config change | See [Configuring MCP](#configuring-mcp), verify `~/.openviking/ovcli.conf`, then restart Claude Code || Remote auth 401 / 403 | API key / account / user header mismatch | Verify `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER` (or their `ov.conf` counterparts) || `Stop` hook times out | Server slow + sync write path | Leave `writePathAsync: true` (default), or raise the `Stop` timeout in `hooks/hooks.json` || Old context keeps re-appearing in OV | Pre-fix versions captured the recall block back into OV | Update to current version — `auto-capture` now strips `<openviking-context>` before pushing |@@ -343,14 +313,14 @@ Claude Code has a built-in `MEMORY.md` file system. This plugin **complements**│ └───────────────────────┘ │ │ │ Server ││ │ │ │ (Python) ││ ┌────────────▼───────────▼───►│ │- │ │ MCP tools (HTTP /mcp) │ │+ │ │ MCP tools (stdio proxy → /mcp) ││ │ search / read / store / … │ │└─────────────────►│ │ │OV session └─────────────────────────────► │context inject └──────────────┘```-There is no bundled MCP server, no TypeScript build step, and no runtime npm bootstrap. Hooks are plain `.mjs` files that talk to OpenViking over HTTP; MCP comes from the OpenViking server's `/mcp` endpoint.+There is no TypeScript build step and no runtime npm bootstrap. Hooks are plain `.mjs` files that talk to OpenViking over HTTP; MCP uses `servers/mcp-proxy.mjs` as a zero-dependency stdio bridge to the OpenViking server's `/mcp` endpoint.A persistent OpenViking session is created on first contact and reused for the entire Claude Code session. The OV session ID is `cc-<sha256(cc_session_id)>`, so resume / compact / multi-hook events all target the same session, and OV's `auto_commit_threshold` drives archival + memory extraction naturally.@@ -378,7 +348,7 @@ Disable with `claude_code.writePathAsync: false` if you need deterministic order### MCP tools available from the server-The plugin's `.mcp.json` connects to the OpenViking server's native HTTP MCP endpoint at `/mcp`. The server exposes 9 tools that Claude can call on demand:+The plugin's `.mcp.json` starts a local stdio proxy, which connects to the OpenViking server's native HTTP MCP endpoint at `/mcp`. The server exposes 9 tools that Claude can call on demand:| Tool | Description ||----------------|-------------------------------------------------------------|@@ -402,6 +372,8 @@ claude-code-memory-plugin/│ └── plugin.json # plugin manifest├── hooks/│ └── hooks.json # 7 hook registrations+├── servers/+│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge├── scripts/│ ├── config.mjs # shared config loader (env > ovcli.conf > ov.conf)│ ├── debug-log.mjs # log helper for ~/.openviking/logs/cc-hooks.log@@ -417,7 +389,7 @@ claude-code-memory-plugin/│ └── lib/│ ├── ov-session.mjs # OV HTTP client + session helpers + bypass check│ └── async-writer.mjs # detached-worker helper for write-path hooks-├── .mcp.json # MCP server config (HTTP /mcp on OpenViking)+├── .mcp.json # MCP server config (local stdio proxy)├── package.json # type:module marker only — no runtime deps└── README.md```diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex bc987f8d2..64306d5ef 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -2,17 +2,17 @@为 Claude Code 提供长期语义记忆,由 [OpenViking](https://github.com/volcengine/OpenViking) 驱动。每次用户输入前自动召回相关记忆,每轮对话结束后自动捕获上下文——模型不需要主动调用任何 MCP 工具。-> 公开的 Claude Code 插件 marketplace 正在规划,暂未上线。当前请从本地源码安装(见下文)。+> 插件可直接从仓库自带的 marketplace catalog 安装,无需单独的分发仓库。两条命令的远程安装方式见下文[手动安装](#手动安装)。## 快速开始### 一行安装(推荐)```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/claude-code-memory-plugin/setup-helper/install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude```-仅支持 macOS 和 Linux。脚本会校验依赖、询问你接入**自托管**服务器还是**火山引擎 OpenViking Cloud**(`https://api.vikingdb.cn-beijing.volces.com/openviking`)、按需配置 `~/.openviking/ovcli.conf`(已存在则复用)、把仓库 clone 到 `~/.openviking/openviking-repo`、把 `claude` shell function 包装写进 rc,最后跑 `claude plugin install`。重复执行安全。+仅支持 macOS 和 Linux。Claude Code 和 Codex 共用这一个安装脚本(去掉 `--harness claude` 可交互勾选):它会依次询问界面语言(English/中文)、下载源(GitHub,或 GitHub 受限地区用 TOS 镜像——传 `--dist tos`)和 OpenViking 凭据,然后从远程 marketplace 安装 `openviking-memory`。stdio MCP 代理运行时读取 `ovcli.conf`,不再需要 shell wrapper 或 `.mcp.json` 渲染。重复执行安全。如果你更喜欢手动操作,按下面四步走。@@ -47,16 +47,27 @@ curl http://localhost:1933/health # 或者你的远程 URL#### 3. 安装插件-仓库的 `examples/.claude-plugin/marketplace.json` 把本插件暴露为一个本地 marketplace 条目。在 OpenViking 仓库根目录:+**远程 marketplace(推荐)** —— 无需 clone 仓库。仓库根目录自带 `.claude-plugin/marketplace.json`,其条目通过 `git-subdir` 拉取本插件:++```bash+claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json+claude plugin install openviking-memory@openviking+```++(`claude plugin marketplace add volcengine/OpenViking` 也可以,但会把整个仓库 clone 下来作为 marketplace。)++如果跳过了第 2 步,装完后再配置连接:手写 `~/.openviking/ovcli.conf`、运行插件自带的交互向导 `node <插件目录>/scripts/setup.mjs`,或直接跑一行安装脚本。++**本地目录(开发用)** —— 注册当前 checkout,`scripts/`、`hooks/` 的修改下次 hook 触发即生效、无需重装。在 OpenViking 仓库根目录:```bashclaude plugin marketplace add "$(pwd)/examples"-claude plugin install claude-code-memory-plugin@openviking-plugins-local+claude plugin install openviking-memory@openviking```-> 两条命令默认都装在 user scope —— 插件在任何目录下都生效。这里**不显式传 `--scope user`**,因为老的 Claude Code 2.0.x(比如 2.0.76)不识别这个 flag 会直接报错。在支持 `--scope` 的新版本上,如果装完发现落到了 local scope,可以跑一次 `claude plugin enable claude-code-memory-plugin@openviking-plugins-local --scope user` 提升到 user scope。+> 两条命令默认都装在 user scope —— 插件在任何目录下都生效。这里**不显式传 `--scope user`**,因为老的 Claude Code 2.0.x(比如 2.0.76)不识别这个 flag 会直接报错。在支持 `--scope` 的新版本上,如果装完发现落到了 local scope,可以跑一次 `claude plugin enable openviking-memory@openviking --scope user` 提升到 user scope。>-> marketplace 条目让 Claude Code 直接引用源码目录,对 `scripts/`、`hooks/`、配置文件的修改下次 hook 触发即生效,无需重装。但移动 / 重命名 / 删除源码目录,或 `git checkout` 到不含这些文件的分支,会立刻让插件失效。后续会发布公开 marketplace 以支持一键安装。+> 目录模式注意:移动 / 重命名 / 删除源码目录,或 `git checkout` 到不含这些文件的分支,会立刻让插件失效。两种模式注册的 marketplace 都叫 `openviking`,插件 id 恒为 `openviking-memory@openviking`;切换模式时先移除 marketplace 再添加另一个来源(安装脚本会自动处理)。##### 兼容模式(Claude Code < 2.0)@@ -65,12 +76,9 @@ claude plugin install claude-code-memory-plugin@openviking-plugins-local```bashPLUGIN_DIR="$(pwd)/examples/claude-code-memory-plugin"+# stdio MCP 代理 —— 自己读 ovcli.conf / OPENVIKING_*,不再需要拼 header。claude mcp remove openviking -s user 2>/dev/null-claude mcp add --scope user --transport http openviking \- '${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \- --header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \- --header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}'+claude mcp add --scope user openviking -- node "$PLUGIN_DIR/servers/mcp-proxy.mjs"# 把插件 hooks 合并进 ~/.claude/settings.json(自动备份)mkdir -p ~/.claude && [ -f ~/.claude/settings.json ] || echo '{}' > ~/.claude/settings.json@@ -82,7 +90,7 @@ jq -e . /tmp/ov-settings.json >/dev/null && mv /tmp/ov-settings.json ~/.claude/srm -f /tmp/ov-hooks.json```-`claude mcp add` 的所有参数**必须用单引号**保留 `${VAR}` 字面量 —— Claude Code 在启动 MCP server 时才展开它们,用的就是 shell wrapper 注入的环境变量。换成双引号 shell 会提前把它们展开成空串,配置就废了。一键安装脚本会自动做这一切,并在改 `~/.claude/settings.json` 前提示你。+一行安装脚本在检测到 2.0 之前的版本时会自动执行以上流程(并在 `~/.openviking/openviking-repo` 保留一份源码 checkout 供上面的绝对路径引用)。#### 4. 启动 Claude Code@@ -94,51 +102,11 @@ claude## 配置 MCP-插件的 hook 会自动读 `ovcli.conf` / `ov.conf`,但**自带的 MCP 服务器条目不会**——Claude Code 自己解析 `.mcp.json` 且只支持 `${VAR}` 替换,所以插件无法把配置文件里的值透明地注入 MCP URL 和认证头。+插件的 hook 和 MCP 条目现在使用同一条配置链。仓库里的 `.mcp.json` 会把 `servers/mcp-proxy.mjs` 作为本地 stdio MCP server 启动;这个代理读取 `OPENVIKING_*`、`~/.openviking/ovcli.conf` 和 `~/.openviking/ov.conf`,再把 JSON-RPC 转发到 OpenViking 服务端原生 `/mcp` endpoint,并补齐认证与身份头。-**判断树——你需要做点什么吗?**+正常插件安装不需要额外 export,也不需要渲染 `.mcp.json`。更新 `ovcli.conf` 或相关 `OPENVIKING_*` 环境变量后重启 Claude Code,代理会和 hook 脚本命中同一个 OpenViking 目标。-```-你的 OpenViking 服务器在哪?-├─ 本地 (127.0.0.1, 无鉴权)-│ └─ ✅ 什么都不用做——自带 .mcp.json 已经能跑。-└─ 远程- └─ ✅ 在 shell rc 里加下面这段 function 包装。-```--**推荐路径——用 function 包装 `claude`,调用时从 `ovcli.conf` 注入 env:**--```bash-# ~/.zshrc 或 ~/.bashrc-claude() {- local _ov_conf="${OPENVIKING_CLI_CONFIG_FILE:-$HOME/.openviking/ovcli.conf}"- if [ -f "$_ov_conf" ] && command -v jq >/dev/null 2>&1; then- local _ov_url _ov_key- _ov_url=$(jq -r '.url // empty' "$_ov_conf" 2>/dev/null)- _ov_key=$(jq -r '.api_key // empty' "$_ov_conf" 2>/dev/null)- OPENVIKING_URL="${OPENVIKING_URL:-$_ov_url}" \- OPENVIKING_API_KEY="${OPENVIKING_API_KEY:-$_ov_key}" \- command claude "$@"- else- command claude "$@"- fi-}-```--重新 source rc(`source ~/.zshrc`,bash 用户改成 `source ~/.bashrc`)后重启 `claude`——`/mcp` 应该显示远程 URL 且认证有效。--**封装其他启动命令。** 如果你通过别的命令启动 Claude Code——比如自定义包装脚本 `cc-custom`,或“基础命令 + 子命令”形式的多词启动器——安装脚本也能一并封装:在它的“Extra launch commands”提示里填写,或运行时传入 `OPENVIKING_CC_WRAP_EXTRA='cc-custom'`。该列表存在同一段 rc 标记块里(wrapper 读取为 `$OPENVIKING_CC_WRAP_EXTRA`);对多词条目,只有前导参数匹配该子命令的调用才会注入凭据,该命令的其他用法原样放行。**填的是真实命令名,绝不是它的 shell 别名**:别名会在 wrapper 运行前先展开成目标命令,所以封装它指向的那个——`alias cc=claude` 本就走 base `claude` 封装(无需配置),而 `alias cc=claude-custom` 则把 `claude-custom` 填进去即可;别名名若被填入会被跳过。--> **为什么用 function 而不是 `export`?** 全局 export 的 API Key 会被该 shell 派生的所有子进程继承——npm 脚本、构建工具、崩溃 dump、`/proc/<pid>/environ` 都会带上。函数包装把秘钥限定在 `claude` 进程树内。->-> 还没有 `ovcli.conf`?先按 [部署指南 → CLI 章节](../../docs/zh/guides/03-deployment.md#cli) 创建一份。--**如果 function 包装不方便:**--- **直接编辑插件的 `.mcp.json`**,把值硬编码进去。插件未来更新可能覆盖。-- **在项目 `.mcp.json` 或 `~/.claude.json` 里另起一个 MCP 条目**。参考 [MCP 集成指南](../../docs/zh/guides/06-mcp-integration.md)。--**配错的症状**:hook(auto-recall、auto-capture)正常工作,因为它们直接通过 Node 读配置文件;但按需 MCP 工具(`search`、`read`、`store`…)会静默连到 `http://127.0.0.1:1933`、认证头为空,且 `/mcp` 显示错误的 URL。+代理要求 Node.js 18+。只有在 `OPENVIKING_DEBUG=1` 或 `claude_code.debug=true` 时才写 debug log;stdout 严格保留给 MCP 协议输出。## 配置@@ -151,11 +119,11 @@ claude() {3. **`ov.conf`** — 服务器配置(`~/.openviking/ov.conf` 或 `OPENVIKING_CONFIG_FILE`);插件读 `server.url`、`server.root_api_key`,以及可选的遗留 `claude_code` 块(见 [遗留 `claude_code` 块](#遗留-claude_code-块在-ovconf-里))4. **内置默认值**(`http://127.0.0.1:1933`,无鉴权)-> ⚠️ **仅适用于 hooks。** 这条优先级链由 `scripts/config.mjs` 实现,hook 脚本消费。它**不适用**于 MCP 服务器注册——见 [配置 MCP](#配置-mcp)。+同一组连接与身份字段也会被 stdio MCP 代理使用。### 环境变量-插件全部行为均可通过 env vars 配置。连接 / 身份变量同时影响 hook 和(通过 shell rc)MCP 服务器;调优变量仅影响 hook。+插件全部行为均可通过 env vars 配置。连接 / 身份变量同时影响 hook 和 MCP 代理;调优变量仅影响 hook。#### 连接 / 身份@@ -267,14 +235,16 @@ bypass 命中时所有 hook 直接放行,不联系 OpenViking。示例:```text-OV ✓ │ ↩ 6 mem (0.92) · 50ms 本轮注入 6 条记忆,最高分 0.92+OV ✓ │ Fable 5 · ctx 42% │ ↩ 6 mem (0.92) · 50ms 注入 6 条记忆;模型 + 上下文占比OV ⚠ slow 探针超过 1s 预算(服务器可能在抽风)OV ✗ offline 服务器不可达-OV ⚡ bypass 命中 OPENVIKING_BYPASS_SESSION*+OV ⚡ bypass │ Fable 5 · ctx 42% 命中 OPENVIKING_BYPASS_SESSION*OV ✓ │ ✎ 573/20k · 2 arch 待提交进度 + 本 session 已归档 2 次OV ✓ │ 🔗 resumed │ +3 today session 已恢复上下文;今日累计归档 3 次```+`ctx` 百分比复刻 Claude Code 原生上下文指示器(自定义 statusLine 会替换掉原生那条),配色阈值与原生一致:`<70%` 灰、`70–89%` 黄、`≥90%` 红。不想显示可设 `OPENVIKING_STATUSLINE_CTX=off`。+完整段位说明 + 个性化 recipe(隐藏段位、改色、与已有 statusline 组合、自定义段位),见 [`STATUSLINE.md`](./STATUSLINE.md)。数据来源:@@ -343,14 +313,14 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:│ └───────────────────────┘ │ │ │ Server ││ │ │ │ (Python) ││ ┌────────────▼───────────▼───►│ │- │ │ MCP tools (HTTP /mcp) │ │+ │ │ MCP tools (stdio proxy→/mcp) ││ │ search / read / store / … │ │└─────────────────►│ │ │OV session └─────────────────────────────► │context inject └──────────────┘```-没有内置 MCP server,没有 TypeScript 编译步骤,也没有运行时 npm 引导。Hook 都是直接走 HTTP 调 OpenViking 的 `.mjs` 文件;MCP 来自 OpenViking 服务器自身的 `/mcp` endpoint。+没有 TypeScript 编译步骤,也没有运行时 npm 引导。Hook 都是直接走 HTTP 调 OpenViking 的 `.mjs` 文件;MCP 使用 `servers/mcp-proxy.mjs` 作为零依赖 stdio 桥接,转发到 OpenViking 服务器自身的 `/mcp` endpoint。首次接触时创建一个持久化的 OpenViking session,整个 Claude Code 会话期间复用。OV session ID 是 `cc-<sha256(cc_session_id)>`,所以 resume / compact / 多 hook 事件都打到同一个 session,OV 的 `auto_commit_threshold` 自然驱动归档与记忆抽取。@@ -378,7 +348,7 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:### 服务器暴露的 MCP 工具-插件的 `.mcp.json` 连到 OpenViking 服务器原生 HTTP MCP endpoint `/mcp`,服务器暴露 9 个 Claude 可按需调用的工具:+插件的 `.mcp.json` 启动本地 stdio 代理,代理再连到 OpenViking 服务器原生 HTTP MCP endpoint `/mcp`。服务器暴露 9 个 Claude 可按需调用的工具:| 工具 | 说明 ||----------------|----------------------------------------------------|@@ -402,6 +372,8 @@ claude-code-memory-plugin/│ └── plugin.json # plugin manifest├── hooks/│ └── hooks.json # 7 个 hook 注册+├── servers/+│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp 桥接├── scripts/│ ├── config.mjs # 共享配置加载(env > ovcli.conf > ov.conf)│ ├── debug-log.mjs # 写 ~/.openviking/logs/cc-hooks.log@@ -417,7 +389,7 @@ claude-code-memory-plugin/│ └── lib/│ ├── ov-session.mjs # OV HTTP 客户端 + session 帮助 + bypass 检查│ └── async-writer.mjs # 写路径 detach-worker 帮助-├── .mcp.json # MCP 配置(HTTP /mcp on OpenViking)+├── .mcp.json # MCP 配置(本地 stdio 代理)├── package.json # 仅 type:module 标记,无运行时依赖└── README.md```diff --git a/examples/claude-code-memory-plugin/STATUSLINE.md b/examples/claude-code-memory-plugin/STATUSLINE.mdindex fcd5ad96b..41e7f75f3 100644--- a/examples/claude-code-memory-plugin/STATUSLINE.md+++ b/examples/claude-code-memory-plugin/STATUSLINE.md@@ -41,6 +41,7 @@ The default composition runs left to right, joined by ` │ `. Segments are cond| | `OV ⚠ slow` | yellow | probe timed out (>1 s) — server may be alive but lagging || | `OV ✗ offline` | red | probe errored (refused, DNS fail, network down) || | `OV ⚡ bypass` | yellow | session matched `OPENVIKING_BYPASS_SESSION` or `*_PATTERNS` |+| Model · ctx | `Fable 5 · ctx 42%` | dim / by usage | always, when CC's statusline payload carries `model` / `context_window`. Registering a custom statusLine replaces CC's native context indicator, so this reproduces it: `<70%` dim, `70–89%` yellow, `≥90%` red (native thresholds). Hide with `OPENVIKING_STATUSLINE_CTX=off`. Shows in bypass mode too — it describes the CC conversation, not OV || Recall | `↩ 6 mem (0.92) · 50ms` | dim | last user prompt actually injected memories. `(0.92)` is the top similarity score among picked items; latency is the recall round-trip || Capture | `✎ 573/20k · 2 arch` | dim | tokens pending toward the next archive (sawtooth — resets on commit), `2 arch` = archives produced this session || | `✎ committed · 2 arch` | dim | the turn that just finished produced an archive |@@ -57,7 +58,9 @@ When a segment is **missing** but you'd expect it, the most common reasons are:- **`+N today`** — no archives committed yet today, or `daily-stats.json` is missing entirely.- **`↩` recall** — last prompt produced no usable memories (too-short query, score under threshold, or all results filtered out). The hook ran; it just had nothing worth showing.-The whole line is hard-capped at 80 visible chars and trailing-truncated with `…` if it overflows.+- **`ctx` percentage** — the CC build doesn't send `context_window` in the statusline payload (older versions), or `OPENVIKING_STATUSLINE_CTX=off` is set.++The whole line is hard-capped at 100 visible chars and trailing-truncated with `…` if it overflows.---diff --git a/examples/claude-code-memory-plugin/hooks/hooks.json b/examples/claude-code-memory-plugin/hooks/hooks.jsonindex 80dc7b7d0..5d6d5ad7a 100644--- a/examples/claude-code-memory-plugin/hooks/hooks.json+++ b/examples/claude-code-memory-plugin/hooks/hooks.json@@ -23,6 +23,18 @@]}],+ "PostToolUse": [+ {+ "matcher": "Read",+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/skill-experience.mjs",+ "timeout": 5+ }+ ]+ }+ ],"Stop": [{"matcher": "",diff --git a/examples/claude-code-memory-plugin/package-lock.json b/examples/claude-code-memory-plugin/package-lock.jsonindex 6bd1b8fba..1b07ebfd4 100644--- a/examples/claude-code-memory-plugin/package-lock.json+++ b/examples/claude-code-memory-plugin/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-code-openviking-memory",- "version": "0.2.2",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-code-openviking-memory",- "version": "0.2.2",+ "version": "0.3.0","dependencies": {"@modelcontextprotocol/sdk": "^1.12.1","zod": "^4.3.6"diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.jsonindex 3a27b290d..0035de0af 100644--- a/examples/claude-code-memory-plugin/package.json+++ b/examples/claude-code-memory-plugin/package.json@@ -1,6 +1,6 @@{"name": "claude-code-openviking-memory",- "version": "0.2.2",+ "version": "0.3.0","description": "OpenViking memory plugin for Claude Code — semantic long-term memory","type": "module","scripts": {diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex f62446de9..bb54f30ff 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -634,10 +634,17 @@ async function main() {totalMessageCount = Number(meta?.total_message_count || 0);log("pending_tokens", { ovSessionId, pending: pendingTokens, threshold: cfg.commitTokenThreshold });if (pendingTokens >= cfg.commitTokenThreshold) {- const commitRes = await commitSession(fetchJSON, ovSessionId);+ const commitRes = await commitSession(fetchJSON, ovSessionId, {+ keep_recent_count: cfg.commitKeepRecentCount,+ });committed = commitRes.ok;if (committed) commitCount += 1;- log("commit", { ovSessionId, ok: commitRes.ok, pending: pendingTokens });+ log("commit", {+ ovSessionId,+ ok: commitRes.ok,+ pending: pendingTokens,+ keepRecentCount: cfg.commitKeepRecentCount,+ });}}diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsindex 9fd9876a4..dcb64fee8 100644--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -291,6 +291,36 @@ async function buildInjectionBlock(items) {return { block: lines.join("\n"), contentCount, hintCount, budgetUsed };}+async function recallViaTypeQuotaEndpoint(query) {+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify({+ query,+ quotas: {+ events: Math.max(cfg.recallLimit, 1),+ entities: Math.max(cfg.recallLimit, 1),+ preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(cfg.recallMaxContentChars * Math.max(cfg.recallLimit, 1), 1000),+ min_score: cfg.scoreThreshold,+ render: true,+ }),+ }, { actorPeerId: cfg.peerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}+// ---------------------------------------------------------------------------// Main// ---------------------------------------------------------------------------@@ -361,6 +391,28 @@ async function main() {return;}+ const endpointBlock = await recallViaTypeQuotaEndpoint(userPrompt);+ if (endpointBlock !== null) {+ if (!endpointBlock) {+ log("skip", { reason: "recall_endpoint_no_results" });+ writeRecallState({ count: 0, reason: "no_results", cc_session_id: sessionId });+ approve();+ return;+ }+ writeRecallState({+ count: 1,+ content_items: 1,+ hint_items: 0,+ tokens_used: estimateTokens(endpointBlock),+ tokens_budget: cfg.recallTokenBudget,+ top_score: 0,+ cc_session_id: sessionId,+ reason: "ok",+ });+ approve(endpointBlock);+ return;+ }+const perSourceLimit = Math.max(cfg.recallLimit * 2, 8);const raw = await searchAllSources(userPrompt, perSourceLimit);if (raw.length === 0) {diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjsindex 416bbfcab..788aadb75 100644--- a/examples/claude-code-memory-plugin/scripts/config.mjs+++ b/examples/claude-code-memory-plugin/scripts/config.mjs@@ -30,6 +30,8 @@* OPENVIKING_BYPASS_SESSION, OPENVIKING_BYPASS_SESSION_PATTERNS (CSV)* Profile injection (session_start):* OPENVIKING_NO_AUTO_INJECT, OPENVIKING_PROFILE_TOKEN_BUDGET+ * Skill experience injection (PostToolUse Read):+ * OPENVIKING_SKILL_EXPERIENCE, OPENVIKING_SKILL_EXPERIENCE_LIMIT* Misc:* OPENVIKING_MEMORY_ENABLED, OPENVIKING_DEBUG, OPENVIKING_DEBUG_LOG,* OPENVIKING_CONFIG_FILE, OPENVIKING_CLI_CONFIG_FILE@@ -255,6 +257,10 @@ export function loadConfig() {process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD,num(cc.commitTokenThreshold, 20000),))),+ commitKeepRecentCount: Math.max(0, Math.floor(num(+ process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT,+ num(cc.commitKeepRecentCount, 10),+ ))),// P0-3b: token budget for session-start archive-overview fetchresumeContextBudget: Math.max(1024, Math.floor(num(@@ -272,6 +278,12 @@ export function loadConfig() {num(cc.profileTokenBudget, 10000),))),+ skillExperience: envBool("OPENVIKING_SKILL_EXPERIENCE") ?? (cc.skillExperience === true),+ skillExperienceLimit: Math.max(1, Math.floor(num(+ process.env.OPENVIKING_SKILL_EXPERIENCE_LIMIT,+ num(cc.skillExperienceLimit, 3),+ ))),+// P1-15: bypass patterns (glob) — when the CC session_id or cwd matches,// skip capture/recall entirely. Useful for one-off scratch sessions that// should not contaminate OV.diff --git a/examples/claude-code-memory-plugin/scripts/debug-log.mjs b/examples/claude-code-memory-plugin/scripts/debug-log.mjsindex 452b27635..0da71583a 100644--- a/examples/claude-code-memory-plugin/scripts/debug-log.mjs+++ b/examples/claude-code-memory-plugin/scripts/debug-log.mjs@@ -8,9 +8,8 @@* When inactive, log() and logError() are zero-cost no-ops.*/-import { appendFileSync, mkdirSync } from "node:fs";-import { dirname } from "node:path";import { loadConfig } from "./config.mjs";+import { createLogger as createSharedLogger } from "./shared/debug-log.mjs";let _cfg;function cfg() {@@ -18,30 +17,6 @@ function cfg() {return _cfg;}-function ensureDir(filePath) {- try {- mkdirSync(dirname(filePath), { recursive: true });- } catch { /* already exists or no permission — will fail on write */ }-}--function writeLine(filePath, obj) {- try {- appendFileSync(filePath, JSON.stringify(obj) + "\n");- } catch { /* best effort — never crash the hook */ }-}--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 = () => {};-/*** @param {string} hookName — e.g. "auto-recall" or "auto-capture"* @param {{ debug?: boolean, debugLogPath?: string }} [overrideCfg]@@ -49,22 +24,5 @@ const noop = () => {};* @returns {{ log: (stage: string, data: any) => void, logError: (stage: string, err: any) => void }}*/export function createLogger(hookName, overrideCfg) {- const c = overrideCfg || cfg();- if (!c.debug) return { log: noop, logError: noop };-- const logPath = c.debugLogPath;- 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 };+ return createSharedLogger(hookName, overrideCfg || cfg());}diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjsindex eb9da03be..e090f7ad1 100644--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs@@ -20,45 +20,16 @@* - GET /api/v1/sessions/{id}/context?token_budget=N*/-const OV_SESSION_PREFIX = "cc-";--/**- * Glob → RegExp. Minimal implementation: supports `*` (any chars except /),- * `**` (any chars including /), and literal text. Sufficient for the few- * bypass patterns users are likely to configure.- */-function globToRe(glob) {- let re = "^";- for (let i = 0; i < glob.length; i++) {- const c = glob[i];- if (c === "*") {- if (glob[i + 1] === "*") { re += ".*"; i++; }- else re += "[^/]*";- } else if (/[.+?^${}()|[\]\\]/.test(c)) {- re += "\\" + c;- } else {- re += c;- }- }- re += "$";- return new RegExp(re);-}+import {+ deriveHarnessSessionId,+ isBypassed,+} from "../shared/session-model.mjs";/*** Check whether a CC session_id or cwd matches any bypass pattern.* Also honours OPENVIKING_BYPASS_SESSION env var (via cfg.bypassSession).*/-export function isBypassed(cfg, { sessionId, cwd } = {}) {- if (cfg.bypassSession) return true;- const patterns = cfg.bypassSessionPatterns || [];- if (patterns.length === 0) return false;- const haystacks = [sessionId, cwd].filter(Boolean);- for (const pat of patterns) {- const re = globToRe(pat);- if (haystacks.some((h) => re.test(h))) return true;- }- return false;-}+export { isBypassed };/*** Derive a stable OV session ID from a CC session_id.@@ -68,13 +39,7 @@ export function isBypassed(cfg, { sessionId, cwd } = {}) {* characters outside [A-Za-z0-9._-] become `-`. Result: `cc-<uuid>__<suffix>`.*/export function deriveOvSessionId(ccSessionId, suffix = "") {- if (!ccSessionId || typeof ccSessionId !== "string") {- throw new Error("deriveOvSessionId requires a non-empty ccSessionId");- }- const base = `${OV_SESSION_PREFIX}${ccSessionId}`;- if (!suffix) return base;- const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");- return `${base}__${normalized}`;+ return deriveHarnessSessionId("cc-", ccSessionId, suffix);}/**@@ -161,10 +126,10 @@ export async function addMessage(fetchJSON, sessionId, payload) {* Commit the persistent OV session (archive + background extract). Safe to* call repeatedly: if there are no pending messages the server is a no-op.*/-export async function commitSession(fetchJSON, sessionId) {+export async function commitSession(fetchJSON, sessionId, payload = {}) {const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {method: "POST",- body: JSON.stringify({}),+ body: JSON.stringify(payload || {}),});if (!res.ok) {if (isRetryableFailure(res)) {diff --git a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjsindex bae9a1981..4fe419601 100644--- a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.mjs@@ -1,438 +1 @@-/**- * Local pending queue for offline resilience.- *- * When the OpenViking server is temporarily unreachable, write operations- * (addMessage, commitSession) serialize their payloads to- * `~/.openviking/pending/` as JSON files. On the next session-start, the- * queue is replayed in small batches. This is a session-start-triggered retry- * path with maxRetries/TTL, not a long-running background worker.- *- * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }- *- * Config (env vars):- * OPENVIKING_PENDING_DIR pending queue directory- * (default: ~/.openviking/pending)- * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)- * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup- * (default: 7)- * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start- * (default: 50)- */--import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";-import { createHash } from "node:crypto";-import { join } from "node:path";-import { homedir } from "node:os";--const DEFAULT_MAX_RETRIES = 3;-const DEFAULT_TTL_DAYS = 7;-const DEFAULT_REPLAY_LIMIT = 50;-const PROCESSING_STALE_MS = 10 * 60 * 1000;-const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");--// Pending queue files may contain raw memory payload / transcript content.-// Use restrictive permissions explicitly so we don't depend on umask.-// - dir: 0o700 (owner: rwx; group/other: none)-// - file: 0o600 (owner: rw; group/other: none)-const PENDING_DIR_MODE = 0o700;-const PENDING_FILE_MODE = 0o600;--/**- * Ensure the pending directory exists with 0o700 permissions. If the- * directory was created by a previous version of this code (or by hand)- * with looser permissions, best-effort chmod it on first use.- */-async function ensurePendingDir(dir) {- await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });- try {- await chmod(dir, PENDING_DIR_MODE);- } catch {- // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.- }-}--function getPendingDir() {- return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();-}--function getMaxRetries() {- const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);- return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;-}--function getTTLDays() {- const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);- return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;-}--function getReplayLimit() {- const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);- return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;-}--function stableStringify(value) {- if (value === null || typeof value !== "object") return JSON.stringify(value);- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;- const keys = Object.keys(value).sort();- return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;-}--function makeDedupKey(type, sessionId, payload) {- return createHash("sha256")- .update(type)- .update("\n")- .update(sessionId)- .update("\n")- .update(stableStringify(payload))- .digest("hex");-}--function pendingFilename(dedupKey, retries = 0) {- return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;-}--function retryFilename(filename, retries) {- const bare = filename.replace(/\.(json|processing)$/, "");- const nextBare = /_\d+$/.test(bare)- ? bare.replace(/_\d+$/, `_${retries}`)- : `${bare}_${retries}`;- return `${nextBare}.json`;-}--function processingFilename(filename) {- return filename.replace(/\.json$/, ".processing");-}--function pendingFromProcessingFilename(filename) {- return filename.replace(/\.processing$/, ".json");-}--function isRetryableReplayFailure(res) {- if (!res || res.ok) return false;- const status = Number(res.status || 0);- return !status || status >= 500 || status === 408 || status === 429;-}--async function readEntry(dir, filename) {- const raw = await readFile(join(dir, filename), "utf-8");- return JSON.parse(raw);-}--async function findExistingByDedupKey(dir, dedupKey) {- let files;- try {- files = await readdir(dir);- } catch {- return null;- }-- // Fast path: filenames are `${dedupKey}_${retries}.json` (or- // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey- // (no underscores), so `${dedupKey}_` is a unique prefix per key.- // Filter on prefix BEFORE opening the file to avoid readFile +- // JSON.parse on every entry in the directory on every enqueue call —- // the previous implementation was O(n²) in queue size. Worst case here- // is O(n) readdir entries, but only the (typically single) prefix- // match actually gets opened and parsed.- const prefix = `${dedupKey}_`;-- for (const f of files) {- if (!f.startsWith(prefix)) continue;- if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;- try {- const entry = await readEntry(dir, f);- if (entry?.dedupKey === dedupKey) return { filename: f, entry };- } catch {- // Corrupted file - ignore for dedup lookup.- }- }- return null;-}--async function recoverStaleProcessing(dir) {- let files;- try {- files = await readdir(dir);- } catch {- return 0;- }-- const now = Date.now();- let recovered = 0;- for (const f of files) {- if (!f.endsWith(".processing")) continue;- const from = join(dir, f);- try {- const s = await stat(from);- if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;- const to = join(dir, pendingFromProcessingFilename(f));- await rename(from, to);- recovered++;- } catch {- // Best effort. A concurrent process may have already handled it.- }- }- return recovered;-}--/**- * Enqueue a failed operation to local disk.- *- * @param {string} type - "addMessage" or "commitSession"- * @param {string} sessionId - OV session ID- * @param {object} payload - the data that failed to send- */-export async function enqueue(type, sessionId, payload) {- const dir = getPendingDir();- const now = Date.now();- const dedupKey = makeDedupKey(type, sessionId, payload);- const filename = pendingFilename(dedupKey, 0);- const entry = {- type,- sessionId,- payload,- createdAt: now,- retries: 0,- dedupKey,- };-- try {- await ensurePendingDir(dir);- } catch (err) {- return { ok: false, error: err?.message || String(err), dedupKey };- }-- const existing = await findExistingByDedupKey(dir, dedupKey);- if (existing) {- return { ok: true, path: existing.filename, deduped: true, dedupKey };- }-- try {- await writeFile(join(dir, filename), JSON.stringify(entry), {- encoding: "utf-8",- flag: "wx",- mode: PENDING_FILE_MODE,- });- return { ok: true, path: filename, dedupKey };- } catch (err) {- if (err?.code !== "EEXIST") {- return { ok: false, error: err?.message || String(err), dedupKey };- }- }-- const duplicate = await findExistingByDedupKey(dir, dedupKey);- if (duplicate) {- return { ok: true, path: duplicate.filename, deduped: true, dedupKey };- }- return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };-}--/**- * List all pending queue entries.- * Returns array of { filename, entry } sorted by createdAt ascending.- */-export async function listPending() {- const dir = getPendingDir();- let files;- try {- await recoverStaleProcessing(dir);- files = await readdir(dir);- } catch {- return [];- }-- const entries = [];- for (const f of files) {- if (!f.endsWith(".json")) continue;- try {- const entry = await readEntry(dir, f);- entries.push({ filename: f, entry });- } catch {- // Corrupted file - skip.- }- }-- entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));- return entries;-}--/**- * Atomically claim a pending file for replay. Only the process that successfully- * renames the file may send the HTTP replay.- */-export async function claimForReplay(filename) {- if (!filename.endsWith(".json")) return null;- const dir = getPendingDir();- const claimed = processingFilename(filename);- try {- await rename(join(dir, filename), join(dir, claimed));- return claimed;- } catch {- return null;- }-}--/**- * Remove a pending entry after successful replay.- */-export async function dequeue(filename) {- const dir = getPendingDir();- try {- await unlink(join(dir, filename));- return true;- } catch {- return false;- }-}--/**- * Increment retry count on a pending entry. Returns false if max retries exceeded.- */-export async function incrementRetry(filename, entry) {- const dir = getPendingDir();- const maxRetries = getMaxRetries();- entry.retries = (entry.retries || 0) + 1;-- if (entry.retries > maxRetries) {- try {- await unlink(join(dir, filename));- } catch {- // Best effort.- }- return false;- }-- const newFilename = retryFilename(filename, entry.retries);- // Atomic write: write to a unique temp file in the same directory, then- // rename into place. Avoids leaving a half-written JSON if the process- // crashes mid-write.- const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;- try {- await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {- encoding: "utf-8",- flag: "wx",- mode: PENDING_FILE_MODE,- });- await rename(join(dir, tmpFilename), join(dir, newFilename));- await unlink(join(dir, filename)).catch(() => {});- return true;- } catch {- await unlink(join(dir, tmpFilename)).catch(() => {});- return false;- }-}--/**- * Clean up stale entries older than TTL.- */-export async function cleanStale() {- const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;- const now = Date.now();- const pending = await listPending();- let cleaned = 0;-- for (const { filename, entry } of pending) {- const age = now - (entry.createdAt || 0);- if (age > ttlMs) {- await dequeue(filename);- cleaned++;- }- }- return cleaned;-}--/**- * Replay pending entries. Call this during session-start when the server is- * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so- * a just-recovered server is not hit with an unbounded replay burst.- *- * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON- * @param {Function} log - logger function- * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}- */-export async function replayPending(fetchJSON, log) {- const pending = await listPending();-- if (pending.length === 0) {- return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };- }-- const replayLimit = getReplayLimit();- log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });-- let replayed = 0;- let failed = 0;- let skipped = 0;- let deferred = 0;- let processed = 0;-- for (const { filename, entry } of pending) {- if (processed >= replayLimit) {- deferred++;- continue;- }-- if ((entry.retries || 0) >= getMaxRetries()) {- await dequeue(filename);- skipped++;- continue;- }-- const claimedFilename = await claimForReplay(filename);- if (!claimedFilename) {- skipped++;- continue;- }- processed++;-- let res;- try {- const encodedSid = encodeURIComponent(entry.sessionId);- if (entry.type === "addMessage") {- res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {- method: "POST",- body: JSON.stringify(entry.payload),- });- } else if (entry.type === "commitSession") {- res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {- method: "POST",- body: JSON.stringify({}),- });- } else {- await dequeue(claimedFilename);- skipped++;- continue;- }- } catch {- res = { ok: false };- }-- if (res?.ok) {- await dequeue(claimedFilename);- replayed++;- } else if (!isRetryableReplayFailure(res)) {- await dequeue(claimedFilename);- skipped++;- } else {- await incrementRetry(claimedFilename, entry);- failed++;- if (entry.type === "addMessage") {- deferred += Math.max(0, pending.length - processed);- break;- }- }- }-- const cleaned = await cleanStale();-- log("pending-queue", {- action: "replay-done",- replayed,- failed,- skipped,- deferred,- cleaned,- });-- return { replayed, failed, skipped, deferred };-}+export * from "../shared/pending-queue.mjs";diff --git a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjsnew file mode 100644index 000000000..f1f78c1ae--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs@@ -0,0 +1,69 @@+import test from "node:test";+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const scriptsDir = dirname(fileURLToPath(import.meta.url));+const pluginDir = resolve(scriptsDir, "..");+const repoRoot = resolve(scriptsDir, "..", "..", "..");+const rootCatalogPath = join(repoRoot, ".claude-plugin", "marketplace.json");+const localCatalogPath = join(repoRoot, "examples", ".claude-plugin", "marketplace.json");+const manifestPath = join(pluginDir, ".claude-plugin", "plugin.json");++const PLUGIN_NAME = "openviking-memory";++function readJson(path) {+ return JSON.parse(readFileSync(path, "utf-8"));+}++test("repo-root Claude marketplace catalog uses git-subdir source", () => {+ assert.ok(existsSync(rootCatalogPath), `missing catalog at ${rootCatalogPath}`);+ const catalog = readJson(rootCatalogPath);+ assert.equal(catalog.name, "openviking");+ const entry = catalog.plugins?.find((p) => p?.name === PLUGIN_NAME);+ assert.ok(entry, `root catalog must contain ${PLUGIN_NAME}`);+ assert.deepEqual(entry.source, {+ source: "git-subdir",+ url: "https://github.com/volcengine/OpenViking.git",+ path: "examples/claude-code-memory-plugin",+ ref: "main",+ });+});++test("local Claude marketplace entry name matches plugin manifest", () => {+ const catalog = readJson(localCatalogPath);+ const manifest = readJson(manifestPath);+ // Same marketplace name in remote and directory mode keeps the plugin id+ // (openviking-memory@openviking) stable across install modes.+ assert.equal(catalog.name, "openviking");+ const entry = catalog.plugins?.find((p) => p?.name === PLUGIN_NAME);+ assert.ok(entry, `local catalog must contain ${PLUGIN_NAME}`);+ assert.equal(entry.name, manifest.name);+ assert.equal(entry.source, "./claude-code-memory-plugin");+});++test("Claude .mcp.json starts the stdio MCP proxy", () => {+ const mcp = readJson(join(pluginDir, ".mcp.json"));+ const server = mcp.openviking;+ assert.ok(server, ".mcp.json must define openviking server");+ assert.equal(server.command, "node");+ assert.deepEqual(server.args, ["${CLAUDE_PLUGIN_ROOT}/servers/mcp-proxy.mjs"]);+ assert.ok(!("type" in server), ".mcp.json should not keep HTTP MCP type");+ assert.ok(!("url" in server), ".mcp.json should not keep direct HTTP url");+ execFileSync("node", ["--check", join(pluginDir, "servers", "mcp-proxy.mjs")], { stdio: "pipe" });+});++test("Claude hooks include optional skill experience PostToolUse Read hook", () => {+ const hooks = readJson(join(pluginDir, "hooks", "hooks.json"));+ const postToolUse = hooks.hooks?.PostToolUse;+ assert.ok(Array.isArray(postToolUse), "hooks.json must define PostToolUse hooks");+ const readHook = postToolUse.find((entry) => entry?.matcher === "Read");+ assert.ok(readHook, "PostToolUse must include a Read matcher");+ assert.equal(+ readHook.hooks?.[0]?.command,+ "node ${CLAUDE_PLUGIN_ROOT}/scripts/skill-experience.mjs",+ );+ execFileSync("node", ["--check", join(pluginDir, "scripts", "skill-experience.mjs")], { stdio: "pipe" });+});diff --git a/examples/claude-code-memory-plugin/scripts/setup.mjs b/examples/claude-code-memory-plugin/scripts/setup.mjsnew file mode 100644index 000000000..32c71ecea--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/setup.mjs@@ -0,0 +1,14 @@+#!/usr/bin/env node++/**+ * Standalone ovcli.conf setup for marketplace installs of the Claude Code plugin:+ *+ * node scripts/setup.mjs+ */++import { runSetupWizard } from "./shared/setup-wizard.mjs";++runSetupWizard().catch((err) => {+ process.stderr.write(`${err?.stack || err}\n`);+ process.exit(1);+});diff --git a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjsnew file mode 100644index 000000000..4ad0314bf--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs@@ -0,0 +1,329 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjsnew file mode 100644index 000000000..4513d57a9--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs@@ -0,0 +1,194 @@+// 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;+ }+}++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 deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");+ if (!useCli && 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 useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, 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 = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : (mode === "env" ? "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/examples/claude-code-memory-plugin/scripts/shared/debug-log.mjs b/examples/claude-code-memory-plugin/scripts/shared/debug-log.mjsnew file mode 100644index 000000000..73855cf6d--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/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/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjsnew file mode 100644index 000000000..f420887c4--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs@@ -0,0 +1,451 @@+// 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,+} = {}) {+ 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 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, message = null) {+ const headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": message?.params?.protocolVersion || 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;+ 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, message),+ 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 (!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 = message.params?.protocolVersion || protocolVersion || DEFAULT_PROTOCOL_VERSION;+ sessionId = "";+ }+ if (message.method === "notifications/initialized") {+ initializedNotification = cloneMessage(message);+ }++ try {+ 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(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/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjsnew file mode 100644index 000000000..754771d22--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs@@ -0,0 +1,439 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Local pending queue for offline resilience.+ *+ * When the OpenViking server is temporarily unreachable, write operations+ * (addMessage, commitSession) serialize their payloads to+ * `~/.openviking/pending/` as JSON files. On the next session-start, the+ * queue is replayed in small batches. This is a session-start-triggered retry+ * path with maxRetries/TTL, not a long-running background worker.+ *+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }+ *+ * Config (env vars):+ * OPENVIKING_PENDING_DIR pending queue directory+ * (default: ~/.openviking/pending)+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup+ * (default: 7)+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start+ * (default: 50)+ */++import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join } from "node:path";+import { homedir } from "node:os";++const DEFAULT_MAX_RETRIES = 3;+const DEFAULT_TTL_DAYS = 7;+const DEFAULT_REPLAY_LIMIT = 50;+const PROCESSING_STALE_MS = 10 * 60 * 1000;+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");++// Pending queue files may contain raw memory payload / transcript content.+// Use restrictive permissions explicitly so we don't depend on umask.+// - dir: 0o700 (owner: rwx; group/other: none)+// - file: 0o600 (owner: rw; group/other: none)+const PENDING_DIR_MODE = 0o700;+const PENDING_FILE_MODE = 0o600;++/**+ * Ensure the pending directory exists with 0o700 permissions. If the+ * directory was created by a previous version of this code (or by hand)+ * with looser permissions, best-effort chmod it on first use.+ */+async function ensurePendingDir(dir) {+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });+ try {+ await chmod(dir, PENDING_DIR_MODE);+ } catch {+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.+ }+}++function getPendingDir() {+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();+}++function getMaxRetries() {+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;+}++function getTTLDays() {+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;+}++function getReplayLimit() {+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;+}++function stableStringify(value) {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;+}++function makeDedupKey(type, sessionId, payload) {+ return createHash("sha256")+ .update(type)+ .update("\n")+ .update(sessionId)+ .update("\n")+ .update(stableStringify(payload))+ .digest("hex");+}++function pendingFilename(dedupKey, retries = 0) {+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;+}++function retryFilename(filename, retries) {+ const bare = filename.replace(/\.(json|processing)$/, "");+ const nextBare = /_\d+$/.test(bare)+ ? bare.replace(/_\d+$/, `_${retries}`)+ : `${bare}_${retries}`;+ return `${nextBare}.json`;+}++function processingFilename(filename) {+ return filename.replace(/\.json$/, ".processing");+}++function pendingFromProcessingFilename(filename) {+ return filename.replace(/\.processing$/, ".json");+}++function isRetryableReplayFailure(res) {+ if (!res || res.ok) return false;+ const status = Number(res.status || 0);+ return !status || status >= 500 || status === 408 || status === 429;+}++async function readEntry(dir, filename) {+ const raw = await readFile(join(dir, filename), "utf-8");+ return JSON.parse(raw);+}++async function findExistingByDedupKey(dir, dedupKey) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return null;+ }++ // Fast path: filenames are `${dedupKey}_${retries}.json` (or+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.+ // Filter on prefix BEFORE opening the file to avoid readFile ++ // JSON.parse on every entry in the directory on every enqueue call —+ // the previous implementation was O(n²) in queue size. Worst case here+ // is O(n) readdir entries, but only the (typically single) prefix+ // match actually gets opened and parsed.+ const prefix = `${dedupKey}_`;++ for (const f of files) {+ if (!f.startsWith(prefix)) continue;+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;+ try {+ const entry = await readEntry(dir, f);+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };+ } catch {+ // Corrupted file - ignore for dedup lookup.+ }+ }+ return null;+}++async function recoverStaleProcessing(dir) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return 0;+ }++ const now = Date.now();+ let recovered = 0;+ for (const f of files) {+ if (!f.endsWith(".processing")) continue;+ const from = join(dir, f);+ try {+ const s = await stat(from);+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;+ const to = join(dir, pendingFromProcessingFilename(f));+ await rename(from, to);+ recovered++;+ } catch {+ // Best effort. A concurrent process may have already handled it.+ }+ }+ return recovered;+}++/**+ * Enqueue a failed operation to local disk.+ *+ * @param {string} type - "addMessage" or "commitSession"+ * @param {string} sessionId - OV session ID+ * @param {object} payload - the data that failed to send+ */+export async function enqueue(type, sessionId, payload) {+ const dir = getPendingDir();+ const now = Date.now();+ const dedupKey = makeDedupKey(type, sessionId, payload);+ const filename = pendingFilename(dedupKey, 0);+ const entry = {+ type,+ sessionId,+ payload,+ createdAt: now,+ retries: 0,+ dedupKey,+ };++ try {+ await ensurePendingDir(dir);+ } catch (err) {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }++ const existing = await findExistingByDedupKey(dir, dedupKey);+ if (existing) {+ return { ok: true, path: existing.filename, deduped: true, dedupKey };+ }++ try {+ await writeFile(join(dir, filename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ return { ok: true, path: filename, dedupKey };+ } catch (err) {+ if (err?.code !== "EEXIST") {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }+ }++ const duplicate = await findExistingByDedupKey(dir, dedupKey);+ if (duplicate) {+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };+ }+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };+}++/**+ * List all pending queue entries.+ * Returns array of { filename, entry } sorted by createdAt ascending.+ */+export async function listPending() {+ const dir = getPendingDir();+ let files;+ try {+ await recoverStaleProcessing(dir);+ files = await readdir(dir);+ } catch {+ return [];+ }++ const entries = [];+ for (const f of files) {+ if (!f.endsWith(".json")) continue;+ try {+ const entry = await readEntry(dir, f);+ entries.push({ filename: f, entry });+ } catch {+ // Corrupted file - skip.+ }+ }++ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));+ return entries;+}++/**+ * Atomically claim a pending file for replay. Only the process that successfully+ * renames the file may send the HTTP replay.+ */+export async function claimForReplay(filename) {+ if (!filename.endsWith(".json")) return null;+ const dir = getPendingDir();+ const claimed = processingFilename(filename);+ try {+ await rename(join(dir, filename), join(dir, claimed));+ return claimed;+ } catch {+ return null;+ }+}++/**+ * Remove a pending entry after successful replay.+ */+export async function dequeue(filename) {+ const dir = getPendingDir();+ try {+ await unlink(join(dir, filename));+ return true;+ } catch {+ return false;+ }+}++/**+ * Increment retry count on a pending entry. Returns false if max retries exceeded.+ */+export async function incrementRetry(filename, entry) {+ const dir = getPendingDir();+ const maxRetries = getMaxRetries();+ entry.retries = (entry.retries || 0) + 1;++ if (entry.retries > maxRetries) {+ try {+ await unlink(join(dir, filename));+ } catch {+ // Best effort.+ }+ return false;+ }++ const newFilename = retryFilename(filename, entry.retries);+ // Atomic write: write to a unique temp file in the same directory, then+ // rename into place. Avoids leaving a half-written JSON if the process+ // crashes mid-write.+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ await rename(join(dir, tmpFilename), join(dir, newFilename));+ await unlink(join(dir, filename)).catch(() => {});+ return true;+ } catch {+ await unlink(join(dir, tmpFilename)).catch(() => {});+ return false;+ }+}++/**+ * Clean up stale entries older than TTL.+ */+export async function cleanStale() {+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;+ const now = Date.now();+ const pending = await listPending();+ let cleaned = 0;++ for (const { filename, entry } of pending) {+ const age = now - (entry.createdAt || 0);+ if (age > ttlMs) {+ await dequeue(filename);+ cleaned++;+ }+ }+ return cleaned;+}++/**+ * Replay pending entries. Call this during session-start when the server is+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so+ * a just-recovered server is not hit with an unbounded replay burst.+ *+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON+ * @param {Function} log - logger function+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}+ */+export async function replayPending(fetchJSON, log) {+ const pending = await listPending();++ if (pending.length === 0) {+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };+ }++ const replayLimit = getReplayLimit();+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });++ let replayed = 0;+ let failed = 0;+ let skipped = 0;+ let deferred = 0;+ let processed = 0;++ for (const { filename, entry } of pending) {+ if (processed >= replayLimit) {+ deferred++;+ continue;+ }++ if ((entry.retries || 0) >= getMaxRetries()) {+ await dequeue(filename);+ skipped++;+ continue;+ }++ const claimedFilename = await claimForReplay(filename);+ if (!claimedFilename) {+ skipped++;+ continue;+ }+ processed++;++ let res;+ try {+ const encodedSid = encodeURIComponent(entry.sessionId);+ if (entry.type === "addMessage") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {+ method: "POST",+ body: JSON.stringify(entry.payload),+ });+ } else if (entry.type === "commitSession") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {+ method: "POST",+ body: JSON.stringify({}),+ });+ } else {+ await dequeue(claimedFilename);+ skipped++;+ continue;+ }+ } catch {+ res = { ok: false };+ }++ if (res?.ok) {+ await dequeue(claimedFilename);+ replayed++;+ } else if (!isRetryableReplayFailure(res)) {+ await dequeue(claimedFilename);+ skipped++;+ } else {+ await incrementRetry(claimedFilename, entry);+ failed++;+ if (entry.type === "addMessage") {+ deferred += Math.max(0, pending.length - processed);+ break;+ }+ }+ }++ const cleaned = await cleanStale();++ log("pending-queue", {+ action: "replay-done",+ replayed,+ failed,+ skipped,+ deferred,+ cleaned,+ });++ return { replayed, failed, skipped, deferred };+}diff --git a/examples/claude-code-memory-plugin/scripts/shared/session-model.mjs b/examples/claude-code-memory-plugin/scripts/shared/session-model.mjsnew file mode 100644index 000000000..b6496a113--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/session-model.mjs@@ -0,0 +1,57 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared OpenViking session-id helpers for memory plugin harnesses.+ */++/**+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.+ */+function globToRe(glob) {+ let re = "^";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i];+ if (c === "*") {+ if (glob[i + 1] === "*") { re += ".*"; i++; }+ else re += "[^/]*";+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {+ re += "\\" + c;+ } else {+ re += c;+ }+ }+ re += "$";+ return new RegExp(re);+}++export function isBypassed(cfg, { sessionId, cwd } = {}) {+ if (cfg.bypassSession) return true;+ const patterns = cfg.bypassSessionPatterns || [];+ if (patterns.length === 0) return false;+ const haystacks = [sessionId, cwd].filter(Boolean);+ for (const pat of patterns) {+ const re = globToRe(pat);+ if (haystacks.some((h) => re.test(h))) return true;+ }+ return false;+}++function safeId(value, replacement = "_") {+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);+}++export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {+ if (!prefix || typeof prefix !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");+ }+ if (!sessionId || typeof sessionId !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");+ }+ const base = `${prefix}${sessionId}`;+ if (!suffix) return base;+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");+ return `${base}__${normalized}`;+}++export function deriveCodexSessionId(codexSessionId) {+ return `cx-${safeId(codexSessionId, "_")}`;+}diff --git a/examples/claude-code-memory-plugin/scripts/shared/setup-wizard.mjs b/examples/claude-code-memory-plugin/scripts/shared/setup-wizard.mjsnew file mode 100644index 000000000..5108f5f2b--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/setup-wizard.mjs@@ -0,0 +1,111 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.+ *+ * Lets a pure-marketplace install (no installer script) configure the server+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:+ *+ * node <plugin>/scripts/setup.mjs+ *+ * Conventions: show current values, keep existing secrets on empty input,+ * merge-write (never drop unknown fields), back up the previous file, 0600.+ */++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline/promises";+import { loadCredentialFiles } from "./credentials.mjs";++const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";+const LOCAL_URL = "http://127.0.0.1:1933";++function maskSecret(value) {+ const s = String(value || "");+ if (!s) return "(not set)";+ if (s.length <= 8) return "****";+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;+}++function readJsonSafe(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return {};+ }+}++export async function runSetupWizard({+ input = process.stdin,+ output = process.stdout,+ env = process.env,+} = {}) {+ const { cliPath } = loadCredentialFiles(env);+ const current = readJsonSafe(cliPath);+ const rl = createInterface({ input, output });+ const say = (line = "") => output.write(`${line}\n`);++ try {+ say("OpenViking memory plugin setup");+ say(`Config file: ${cliPath}`);+ say("");+ say("Current values:");+ say(` url: ${current.url || "(not set)"}`);+ say(` api_key: ${maskSecret(current.api_key)}`);+ if (current.account) say(` account: ${current.account}`);+ if (current.user) say(` user: ${current.user}`);+ say("");++ const defaultUrl = current.url || LOCAL_URL;+ say("Where do you connect to OpenViking?");+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);+ say(` 3) Custom URL / keep current [${defaultUrl}]`);+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();+ let url = defaultUrl;+ if (mode === "1") {+ url = LOCAL_URL;+ } else if (mode === "2") {+ url = CLOUD_URL;+ } else {+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();+ if (answer) url = answer;+ }++ const keyPrompt = current.api_key+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `+ : "API key (leave empty for unauthenticated local mode): ";+ const keyAnswer = await rl.question(keyPrompt);+ let apiKey = current.api_key || "";+ if (keyAnswer === "-") apiKey = "";+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();+ else if (!current.api_key) apiKey = "";++ const next = { ...current, url, api_key: apiKey };++ say("");+ say("Changes:");+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();+ if (confirm === "n" || confirm === "no") {+ say("Aborted; nothing written.");+ return { written: false, path: cliPath };+ }++ mkdirSync(dirname(cliPath), { recursive: true });+ if (existsSync(cliPath)) {+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);+ }+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(cliPath, 0o600);+ } catch {+ /* best effort on platforms without chmod semantics */+ }+ say(`Written: ${cliPath}`);+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");+ return { written: true, path: cliPath };+ } finally {+ rl.close();+ }+}diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.mjsnew file mode 100644index 000000000..2ee3ceaa6--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.mjs@@ -0,0 +1,163 @@+#!/usr/bin/env node++/**+ * Optional PostToolUse(Read) hook for skill experience recall.+ *+ * Default off. When enabled, it only runs for reads of a SKILL.md file under a+ * skills directory, then injects a small experience block if OpenViking has+ * relevant experience memories.+ */++import { readFileSync } from "node:fs";+import { basename, normalize, sep } from "node:path";+import { isPluginEnabled, loadConfig } from "./config.mjs";+import { createLogger } from "./debug-log.mjs";+import { makeFetchJSON } from "./lib/ov-session.mjs";++if (!isPluginEnabled()) {+ process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");+ process.exit(0);+}++const cfg = loadConfig();+const { log, logError } = createLogger("skill-experience");+const fetchJSON = makeFetchJSON(cfg);++function output(obj) {+ process.stdout.write(JSON.stringify(obj) + "\n");+}++function approve(additionalContext) {+ const out = { decision: "approve" };+ if (additionalContext) {+ out.hookSpecificOutput = {+ hookEventName: "PostToolUse",+ additionalContext,+ };+ }+ output(out);+}++async function readStdinJson() {+ try {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ return JSON.parse(Buffer.concat(chunks).toString() || "{}");+ } catch {+ return {};+ }+}++function toolName(input) {+ return String(input.tool_name || input.toolName || input.name || input.tool || "").trim();+}++function readPath(input) {+ const candidate =+ input.tool_input?.file_path ||+ input.tool_input?.path ||+ input.toolInput?.file_path ||+ input.toolInput?.path ||+ input.file_path ||+ input.path ||+ input.params?.file_path ||+ input.params?.path ||+ "";+ return String(candidate || "").trim();+}++function isSkillFile(path) {+ if (!path) return false;+ const normalized = normalize(path);+ const parts = normalized.split(sep).filter(Boolean);+ return basename(normalized) === "SKILL.md" && parts.includes("skills");+}++function skillNameFromContent(path) {+ try {+ const raw = readFileSync(path, "utf-8").slice(0, 4096);+ const fm = raw.match(/^---\s*\n([\s\S]*?)\n---/);+ const head = fm ? fm[1] : raw;+ const named = head.match(/^\s*name\s*:\s*['"]?([^'"\n]+)['"]?\s*$/im);+ if (named?.[1]) return named[1].trim();+ const title = raw.match(/^\s*#\s+(.+?)\s*$/m);+ if (title?.[1]) return title[1].trim();+ } catch {+ // The Read tool already succeeded; inability to re-read locally should only+ // disable this optional enhancement.+ }+ return basename(path.replace(/\/SKILL\.md$/, ""));+}++function clampScore(value) {+ const num = Number(value);+ if (!Number.isFinite(num)) return 0;+ return Math.max(0, Math.min(1, num));+}++async function findExperiences(query) {+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify({+ query,+ target_uri: "viking://user/memories/experiences",+ context_type: "memory",+ limit: cfg.skillExperienceLimit,+ score_threshold: cfg.scoreThreshold,+ }),+ });+ if (!res.ok) return [];+ return (res.result?.memories || [])+ .filter((item) => /\/memories\/experiences\//.test(String(item.uri || "")))+ .slice(0, cfg.skillExperienceLimit);+}++function buildContext(skillName, items) {+ if (items.length === 0) return "";+ const lines = [+ '<openviking-context source="skill-experience" format="experience-digest">',+ `Relevant prior experience for skill: ${skillName}`,+ ];+ for (const item of items) {+ const score = Math.round(clampScore(item.score) * 100);+ const text = String(item.abstract || item.overview || item.uri || "").replace(/\s+/g, " ").trim();+ lines.push(`- [experience ${score}%] ${text} (${item.uri})`);+ }+ lines.push("Use these as operational guidance, not user facts.");+ lines.push("</openviking-context>");+ return lines.join("\n");+}++async function main() {+ if (!cfg.skillExperience) {+ log("skip", { reason: "disabled" });+ approve();+ return;+ }++ const input = await readStdinJson();+ const name = toolName(input);+ const path = readPath(input);+ if (name && name !== "Read") {+ log("skip", { reason: "not_read", toolName: name });+ approve();+ return;+ }+ if (!isSkillFile(path)) {+ log("skip", { reason: "not_skill_file", path });+ approve();+ return;+ }++ const skillName = skillNameFromContent(path);+ const query = `skill ${skillName} usage experience`;+ const items = await findExperiences(query);+ const context = buildContext(skillName, items);+ log("done", { skillName, count: items.length });+ approve(context);+}++main().catch((err) => {+ logError("uncaught", err);+ approve();+});diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjsnew file mode 100644index 000000000..ccfef9c7c--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs@@ -0,0 +1,174 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import http from "node:http";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));++function readRequestBody(req) {+ return new Promise((resolve, reject) => {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const raw = Buffer.concat(chunks).toString("utf-8");+ try {+ resolve(raw ? JSON.parse(raw) : null);+ } catch (err) {+ reject(err);+ }+ });+ req.on("error", reject);+ });+}++function writeJson(res, value) {+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end(JSON.stringify(value));+}++async function withMockOpenViking(handler, fn) {+ const server = http.createServer((req, res) => {+ handler(req, res).catch((err) => {+ res.writeHead(500, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));+ });+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ const { port } = server.address();+ return await fn(`http://127.0.0.1:${port}`);+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+}++function runSkillExperience(input, env) {+ return new Promise((resolve, reject) => {+ const cleanEnv = { ...process.env };+ for (const key of Object.keys(cleanEnv)) {+ if (key.startsWith("OPENVIKING_")) delete cleanEnv[key];+ }+ const child = spawn(process.execPath, [join(SCRIPT_DIR, "skill-experience.mjs")], {+ env: { ...cleanEnv, ...env },+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => { stdout += chunk.toString(); });+ child.stderr.on("data", (chunk) => { stderr += chunk.toString(); });+ child.on("error", reject);+ child.on("close", (code) => {+ if (code !== 0) {+ reject(new Error(`skill-experience exited ${code}: ${stderr}`));+ return;+ }+ resolve({ stdout, stderr });+ });+ child.stdin.end(JSON.stringify(input));+ });+}++test("skill experience hook is disabled by default", async () => {+ const tmp = await mkdtemp(join(tmpdir(), "ov-skill-exp-disabled-"));+ try {+ const skillDir = join(tmp, "skills", "demo");+ await mkdir(skillDir, { recursive: true });+ const skillPath = join(skillDir, "SKILL.md");+ await writeFile(skillPath, "# Demo Skill\n");++ const result = await runSkillExperience(+ { tool_name: "Read", tool_input: { file_path: skillPath } },+ {+ OPENVIKING_MEMORY_ENABLED: "1",+ OPENVIKING_CONFIG_FILE: join(tmp, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(tmp, "missing-ovcli.conf"),+ },+ );+ assert.deepEqual(JSON.parse(result.stdout.trim()), { decision: "approve" });+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+});++test("skill experience hook ignores non-skill files without network access", async () => {+ const tmp = await mkdtemp(join(tmpdir(), "ov-skill-exp-nonskill-"));+ let requests = 0;+ try {+ await withMockOpenViking(async (_req, res) => {+ requests += 1;+ writeJson(res, { status: "ok", result: {} });+ }, async (baseUrl) => {+ const result = await runSkillExperience(+ { tool_name: "Read", tool_input: { file_path: join(tmp, "README.md") } },+ {+ OPENVIKING_MEMORY_ENABLED: "1",+ OPENVIKING_SKILL_EXPERIENCE: "1",+ OPENVIKING_CONFIG_FILE: join(tmp, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(tmp, "missing-ovcli.conf"),+ OPENVIKING_URL: baseUrl,+ },+ );+ assert.deepEqual(JSON.parse(result.stdout.trim()), { decision: "approve" });+ });+ assert.equal(requests, 0);+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+});++test("skill experience hook injects matching experience memories", async () => {+ const tmp = await mkdtemp(join(tmpdir(), "ov-skill-exp-enabled-"));+ const requests = [];+ try {+ const skillDir = join(tmp, "skills", "demo");+ await mkdir(skillDir, { recursive: true });+ const skillPath = join(skillDir, "SKILL.md");+ await writeFile(skillPath, "---\nname: Demo Skill\n---\n# Demo Skill\n");++ await withMockOpenViking(async (req, res) => {+ const url = new URL(req.url, "http://127.0.0.1");+ if (req.method === "POST" && url.pathname === "/api/v1/search/find") {+ const body = await readRequestBody(req);+ requests.push(body);+ writeJson(res, {+ status: "ok",+ result: {+ memories: [{+ uri: "viking://user/default/memories/experiences/demo-skill.md",+ score: 0.88,+ abstract: "Use the demo skill after checking prerequisites.",+ }],+ },+ });+ return;+ }+ writeJson(res, { status: "ok", result: {} });+ }, async (baseUrl) => {+ const result = await runSkillExperience(+ { tool_name: "Read", tool_input: { file_path: skillPath } },+ {+ OPENVIKING_MEMORY_ENABLED: "1",+ OPENVIKING_SKILL_EXPERIENCE: "1",+ OPENVIKING_CONFIG_FILE: join(tmp, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(tmp, "missing-ovcli.conf"),+ OPENVIKING_URL: baseUrl,+ },+ );+ const output = JSON.parse(result.stdout.trim());+ assert.equal(output.decision, "approve");+ assert.equal(output.hookSpecificOutput.hookEventName, "PostToolUse");+ assert.match(output.hookSpecificOutput.additionalContext, /Demo Skill/);+ assert.match(output.hookSpecificOutput.additionalContext, /checking prerequisites/);+ });++ assert.equal(requests.length, 1);+ assert.equal(requests[0].target_uri, "viking://user/memories/experiences");+ assert.equal(requests[0].limit, 3);+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+});diff --git a/examples/claude-code-memory-plugin/scripts/statusline.mjs b/examples/claude-code-memory-plugin/scripts/statusline.mjsindex 70762c80e..ff67f0ed0 100755--- a/examples/claude-code-memory-plugin/scripts/statusline.mjs+++ b/examples/claude-code-memory-plugin/scripts/statusline.mjs@@ -24,7 +24,7 @@ import { probeServer } from "./lib/server-probe.mjs";const STATE_MAX_AGE_MS = 30 * 60_000; // 30 min — older = "idle"const SESSION_EVENT_MAX_AGE_MS = 60_000; // 1 min — "🔗 resumed" fades-const MAX_WIDTH = 80;+const MAX_WIDTH = 100;const ESC = "\x1b[";function colorEnabled() {@@ -50,6 +50,47 @@ function human(n) {return Math.round(n / 1000) + "k";}+function num(v) {+ return typeof v === "number" && Number.isFinite(v) ? v : null;+}++// Context usage straight from CC's statusline payload. Registering a custom+// statusLine replaces CC's native line — and with it the built-in context+// indicator — so we have to reproduce it. Color thresholds mirror native CC:+// <70% dim, 70–89% yellow, >=90% red.+function ctxSegment(stdin) {+ if ((process.env.OPENVIKING_STATUSLINE_CTX || "").toLowerCase() === "off") return null;+ const cw = stdin.context_window;+ if (!cw || typeof cw !== "object") return null;+ let pct = num(cw.used_percentage);+ if (pct === null) {+ const remaining = num(cw.remaining_percentage);+ if (remaining !== null) pct = 100 - remaining;+ }+ if (pct === null) {+ const used = num(cw.total_input_tokens);+ const size = num(cw.context_window_size);+ if (used !== null && size !== null && size > 0) pct = (used / size) * 100;+ }+ if (pct === null) return null;+ const rounded = Math.min(100, Math.max(0, Math.round(pct)));+ const seg = `ctx ${rounded}%`;+ if (rounded >= 90) return red(seg);+ if (rounded >= 70) return yellow(seg);+ return dim(seg);+}++// Model + context cluster, one segment: "Fable 5 · ctx 42%". The model name+// rarely changes but anchors the fast-moving percentage next to it.+function modelCtxSegment(stdin) {+ const name = typeof stdin.model?.display_name === "string" ? stdin.model.display_name.trim() : "";+ const ctx = ctxSegment(stdin);+ if (name && ctx) return `${dim(name)}${dim(" · ")}${ctx}`;+ if (ctx) return ctx;+ if (name) return dim(name);+ return null;+}+async function readStdin() {if (process.stdin.isTTY) return {};return await new Promise((resolve) => {@@ -113,9 +154,13 @@ async function main() {const cwd = stdin.cwd;// Bypass shortcut: don't even probe the server when the user has opted- // this session out of OV.+ // this session out of OV. The context indicator stays — it describes the+ // CC conversation, not OV, and this line is all the user gets.if (isBypassed(cfg, { sessionId, cwd })) {- process.stdout.write(yellow("OV ⚡ bypass"));+ const bypassParts = [yellow("OV ⚡ bypass")];+ const modelCtx = modelCtxSegment(stdin);+ if (modelCtx) bypassParts.push(modelCtx);+ process.stdout.write(truncate(bypassParts.join(dim(" │ "))));return;}@@ -139,6 +184,9 @@ async function main() {parts.push(red("OV ✗ offline"));}+ const modelCtx = modelCtxSegment(stdin);+ if (modelCtx) parts.push(modelCtx);+// Recall summary: only meaningful when we actually injected memories this// turn. Skip the segment for empty/bypass/no-results reasons to keep the// line tight. The (0.92) trailing parens is the top score among pickeddiff --git a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjsnew file mode 100644index 000000000..943cd0586--- /dev/null+++ b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs@@ -0,0 +1,62 @@+#!/usr/bin/env node++/**+ * stdio -> streamable-HTTP MCP proxy for the OpenViking Claude Code plugin.+ *+ * Claude Code starts this process as a local stdio MCP server. The proxy reads+ * the same OpenViking credential sources as the lifecycle hooks, 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 "../scripts/config.mjs";+import { createLogger } from "../scripts/debug-log.mjs";+import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.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();+ return {+ mcpUrl: `${trimSlash(cfg.baseUrl)}/mcp`,+ apiKey: cfg.apiKey || "",+ account: cfg.accountId || "",+ user: cfg.userId || "",+ peerId: cfg.peerId || "",+ 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/examples/claude-code-memory-plugin/setup-helper/install.sh b/examples/claude-code-memory-plugin/setup-helper/install.shindex 3ee00c66a..2736e9c9c 100755--- a/examples/claude-code-memory-plugin/setup-helper/install.sh+++ b/examples/claude-code-memory-plugin/setup-helper/install.sh@@ -1,545 +1,16 @@#!/usr/bin/env bash-#-# OpenViking Memory Plugin for Claude Code — interactive installer.-#-# One-liner:-# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/claude-code-memory-plugin/setup-helper/install.sh)-#-# Steps (each is idempotent — re-running is safe):-# 1. Check OS (macOS / Linux only) and required tools.-# 2. Set up ~/.openviking/ovcli.conf — reuse if present, prompt otherwise.-# 3. Clone (or refresh) the OpenViking repo to ~/.openviking/openviking-repo.-# 4. Add a `claude` shell function to your rc that injects creds at invocation.-# 5. Install the plugin. On Claude Code >= 2.0 (with `claude plugin` support) we-# use marketplace + plugin install. On older builds — or if marketplace is-# unavailable — we fall back to legacy mode: `claude mcp add` + a merge into-# ~/.claude/settings.json.-#-# Env overrides:-# OPENVIKING_HOME default: $HOME/.openviking-# OPENVIKING_REPO_DIR default: $OPENVIKING_HOME/openviking-repo-# OPENVIKING_REPO_URL default: https://github.com/volcengine/OpenViking.git-# OPENVIKING_REPO_BRANCH default: main-# OPENVIKING_REPO_ARCHIVE_URL when set, fetch the source from this zip instead-# of git clone (used by the TOS bootstrap for users-# who can't reach GitHub). Requires `unzip`.-#-# Targets bash 3.2+ (macOS /bin/bash) and Linux.-set -euo pipefail-OV_HOME="${OPENVIKING_HOME:-$HOME/.openviking}"-REPO_DIR="${OPENVIKING_REPO_DIR:-$OV_HOME/openviking-repo}"-REPO_URL="${OPENVIKING_REPO_URL:-https://github.com/volcengine/OpenViking.git}"-REPO_BRANCH="${OPENVIKING_REPO_BRANCH:-main}"-REPO_ARCHIVE_URL="${OPENVIKING_REPO_ARCHIVE_URL:-}"-# Marks a $REPO_DIR populated from an archive (no .git). Lets re-runs refresh it-# safely while refusing to clobber a git checkout or unrelated user data.-ARCHIVE_MARKER='.openviking-archive-source'-# Honor OPENVIKING_CLI_CONFIG_FILE (the env var the `ov` CLI itself reads —-# crates/ov_cli/src/config.rs:6) so this installer matches CLI behavior.-OVCLI_CONF="${OPENVIKING_CLI_CONFIG_FILE:-$OV_HOME/ovcli.conf}"--MARKER_BEGIN='# >>> openviking claude-code memory plugin >>>'-MARKER_END='# <<< openviking claude-code memory plugin <<<'--if [ -t 1 ]; then- CYAN=$'\033[0;36m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'; RED=$'\033[0;31m'; BOLD=$'\033[1m'; RESET=$'\033[0m'-else- CYAN=''; GREEN=''; YELLOW=''; RED=''; BOLD=''; RESET=''-fi-info() { printf '%s==>%s %s\n' "$GREEN" "$RESET" "$*"; }-warn() { printf '%s!!%s %s\n' "$YELLOW" "$RESET" "$*"; }-err() { printf '%sxx%s %s\n' "$RED" "$RESET" "$*" >&2; }-ask() { printf '%s??%s %s' "$CYAN" "$RESET" "$*"; }-heading() { printf '\n%s%s%s\n' "$BOLD" "$*" "$RESET"; }--# Download a source zip and lay it out at $REPO_DIR (used for the GitHub-free-# TOS install path). The archive is `git archive` output: a single top-level-# OpenViking-<ref>/ dir, identical to a checkout minus .git.-fetch_archive() {- local url="$1" dest="$2" tmp_zip tmp_dir top- command -v unzip >/dev/null 2>&1 || { err 'unzip not found; required to install from an archive.'; exit 1; }- tmp_zip=$(mktemp "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; exit 1; }- tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; rm -f "$tmp_zip"; exit 1; }- info "Downloading source archive"- info " $url"- curl -fsSL -o "$tmp_zip" "$url" || { err "download failed: $url"; rm -rf "$tmp_zip" "$tmp_dir"; exit 1; }- unzip -q "$tmp_zip" -d "$tmp_dir" || { err 'unzip failed (corrupt download?)'; rm -rf "$tmp_zip" "$tmp_dir"; exit 1; }- top=$(find "$tmp_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)- if [ -z "$top" ] || [ ! -d "$top/examples" ]; then- err 'unexpected archive layout (no top-level dir containing examples/)'- rm -rf "$tmp_zip" "$tmp_dir"; exit 1- fi- rm -rf "$dest"- mkdir -p "$(dirname "$dest")"- mv "$top" "$dest"- : > "$dest/$ARCHIVE_MARKER"- rm -rf "$tmp_zip" "$tmp_dir"- info "Source ready at $dest"-}--# ----- 1. Environment check -------heading '1. Environment check'--case "$(uname -s)" in- Darwin|Linux) info "OS: $(uname -s)" ;;- *) err "Unsupported OS: $(uname -s). Only macOS and Linux are supported."; exit 1 ;;-esac--missing=0-for cmd in git jq curl; do- if ! command -v "$cmd" >/dev/null 2>&1; then- err "$cmd not found. Please install it and re-run."- missing=1- fi-done-[ "$missing" -eq 1 ] && exit 1--if command -v claude >/dev/null 2>&1; then- CLAUDE_AVAILABLE=1- info "claude CLI: $(claude --version 2>/dev/null || echo unknown)"-else- CLAUDE_AVAILABLE=0- warn "claude CLI not found on PATH. Plugin install will be skipped at the end."- warn "Install Claude Code first: https://docs.claude.com/en/docs/claude-code/setup"-fi--# ----- 2. ovcli.conf -------heading "2. OpenViking client config ($OVCLI_CONF)"--mkdir -p "$OV_HOME"-chmod 700 "$OV_HOME" 2>/dev/null || true--CURRENT_URL=""-CURRENT_KEY=""-if [ -f "$OVCLI_CONF" ]; then- CURRENT_URL=$(jq -r '.url // ""' "$OVCLI_CONF" 2>/dev/null || true)- CURRENT_KEY=$(jq -r '.api_key // ""' "$OVCLI_CONF" 2>/dev/null || true)- if [ -n "$CURRENT_URL" ] && [ -n "$CURRENT_KEY" ]; then- key_preview=$(printf '%s' "$CURRENT_KEY" | cut -c1-8)- info "Existing config found:"- info " url = $CURRENT_URL"- info " api_key = ${key_preview}…"- ask 'Reuse these values? [Y/n] '- read -r reply || reply=""- case "$reply" in- n|N|no|No|NO) CURRENT_URL=""; CURRENT_KEY="" ;;- esac- fi-fi+SHARED_REL="../../memory-plugin-shared/install.sh"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"+LOCAL_SHARED="$SCRIPT_DIR/$SHARED_REL"-if [ -z "$CURRENT_URL" ] || [ -z "$CURRENT_KEY" ]; then- printf '%sChoose where you'\''ll connect to OpenViking:%s\n' "$BOLD" "$RESET"- printf ' 1) Self-hosted / local [default: http://127.0.0.1:1933]\n'- printf ' 2) Volcengine OpenViking Cloud [https://api.vikingdb.cn-beijing.volces.com/openviking]\n'- ask '[1/2, default 1]: '- read -r MODE_INPUT || MODE_INPUT=""- case "$MODE_INPUT" in- 2)- CURRENT_URL="https://api.vikingdb.cn-beijing.volces.com/openviking"- info "Using Volcengine OpenViking Cloud: $CURRENT_URL"- KEY_PROMPT="API key (required for Volcengine OpenViking Cloud): "- ;;- *)- DEFAULT_URL="http://127.0.0.1:1933"- ask "OpenViking server URL [$DEFAULT_URL]: "- read -r URL_INPUT || URL_INPUT=""- CURRENT_URL="${URL_INPUT:-$DEFAULT_URL}"- KEY_PROMPT="API key (leave empty for unauthenticated local mode): "- ;;- esac-- ask "$KEY_PROMPT"- # -s: don't echo (hide secret); fall back if -s unsupported- if read -rs API_INPUT 2>/dev/null; then- printf '\n'- else- read -r API_INPUT || API_INPUT=""- fi- CURRENT_KEY="$API_INPUT"-- if [ -f "$OVCLI_CONF" ]; then- backup="$OVCLI_CONF.bak.$(date +%s)"- cp "$OVCLI_CONF" "$backup"- info "Backed up existing config → $backup"- fi- jq -n --arg url "$CURRENT_URL" --arg key "$CURRENT_KEY" \- '{url: $url, api_key: $key}' > "$OVCLI_CONF"- chmod 600 "$OVCLI_CONF"- info "Wrote $OVCLI_CONF (mode 0600)"-fi--# ----- 3. Clone / refresh repo -------heading "3. OpenViking source repository ($REPO_DIR)"--if [ -n "$REPO_ARCHIVE_URL" ]; then- # Archive mode (GitHub-free): refuse to overwrite anything we didn't create.- if [ -e "$REPO_DIR" ] && [ ! -f "$REPO_DIR/$ARCHIVE_MARKER" ]; then- err "$REPO_DIR exists and was not created from an archive. Move it aside or set OPENVIKING_REPO_DIR."- exit 1- fi- fetch_archive "$REPO_ARCHIVE_URL" "$REPO_DIR"-elif [ -d "$REPO_DIR/.git" ]; then- info "Updating existing checkout"- git -C "$REPO_DIR" fetch --depth 1 origin "$REPO_BRANCH"- git -C "$REPO_DIR" reset --hard "FETCH_HEAD"-else- if [ -e "$REPO_DIR" ]; then- err "$REPO_DIR exists but is not a git checkout. Move it aside or set OPENVIKING_REPO_DIR."- exit 1- fi- info "Cloning $REPO_URL (branch $REPO_BRANCH, depth 1)"- mkdir -p "$(dirname "$REPO_DIR")"- git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" "$REPO_DIR"-fi--# ----- 4. Shell rc wrapper ------#-# Source of truth: setup-helper/wrapper.sh in the plugin checkout. The-# user's shell rc just sources that file directly — no copy step, so any-# updates land via the next `git fetch + reset --hard` the installer-# already runs above. Same pattern pyenv / nvm / fnm use, except we don't-# even need an intermediate copy in $HOME.--heading '4. Shell rc — claude function wrapper'--WRAPPER_SRC="$REPO_DIR/examples/claude-code-memory-plugin/setup-helper/wrapper.sh"-if [ ! -f "$WRAPPER_SRC" ]; then- err "Wrapper source not found at $WRAPPER_SRC"- exit 1-fi--case "${SHELL:-}" in- */zsh) RC="$HOME/.zshrc" ;;- */bash) RC="$HOME/.bashrc" ;;- *)- if [ -f "$HOME/.zshrc" ]; then RC="$HOME/.zshrc"- elif [ -f "$HOME/.bashrc" ]; then RC="$HOME/.bashrc"- else RC=""; fi- ;;-esac--# Extra launch commands to wrap besides `claude` — e.g. a custom wrapper-# `cc-custom`, or a multi-word launcher matched on its sub-command.-# Persisted in the rc marker block as OPENVIKING_CC_WRAP_EXTRA; the wrapper-# reads it and injects credentials into matching invocations only.-heading '4b. Extra launch commands (optional)'-# Seed from this run's env var (automation path), else the value already in-# the rc (re-run path). The interactive prompt below can still override it.-WRAP_EXTRA="${OPENVIKING_CC_WRAP_EXTRA:-}"-if [ -z "$WRAP_EXTRA" ] && [ -n "$RC" ] && [ -f "$RC" ]; then- WRAP_EXTRA=$(awk -F"'" '/^OPENVIKING_CC_WRAP_EXTRA=/{print $2; exit}' "$RC" 2>/dev/null || true)-fi-info 'Inject OpenViking creds into other launch commands too? e.g. a custom'-info 'wrapper `cc-custom`. A multi-word launcher (a base command plus a'-info 'sub-command) is matched on that sub-command; other uses of the command'-info 'pass through untouched.'-if [ -n "$WRAP_EXTRA" ]; then- info "Currently: $WRAP_EXTRA"- ask 'Commands (;-separated; empty = keep, "-" = clear): '-else- ask 'Commands (;-separated, e.g. "cc-custom"; empty to skip): '-fi-read -r WRAP_INPUT || WRAP_INPUT=""-case "$WRAP_INPUT" in- "") : ;;- -) WRAP_EXTRA="" ;;- *) WRAP_EXTRA="$WRAP_INPUT" ;;-esac-# Normalize each ';'-entry: strip single quotes (keep the rc line safely-# single-quotable), trim, collapse internal whitespace, drop empties.-if [ -n "$WRAP_EXTRA" ]; then- WRAP_EXTRA=$(printf '%s' "$WRAP_EXTRA" | awk -F';' '{- out="";- for (i = 1; i <= NF; i++) {- s = $i; gsub(/\047/, "", s); gsub(/^[ \t]+|[ \t]+$/, "", s); gsub(/[ \t]+/, " ", s);- if (s != "") out = (out == "" ? s : out ";" s);- }- print out;- }')- [ -n "$WRAP_EXTRA" ] && info "Will wrap: $WRAP_EXTRA"+if [ -f "$LOCAL_SHARED" ]; then+ exec bash "$LOCAL_SHARED" --harness claude "$@"fi-# The user's shell rc gets a single one-line source hook pointing at the-# wrapper source in the cloned plugin checkout. Hook content stays stable-# across installs (only the absolute path matters), so the marker-# replacement only triggers a legacy-cleanup pass once when upgrading from-# a pre-split install that inlined the full wrapper into the rc.-SOURCE_HOOK="[ -f \"$WRAPPER_SRC\" ] && . \"$WRAPPER_SRC\""-if [ -n "$WRAP_EXTRA" ]; then- SOURCE_BLOCK="$MARKER_BEGIN-OPENVIKING_CC_WRAP_EXTRA='$WRAP_EXTRA'-$SOURCE_HOOK-$MARKER_END"-else- SOURCE_BLOCK="$MARKER_BEGIN-$SOURCE_HOOK-$MARKER_END"-fi--if [ -z "$RC" ]; then- warn 'Could not detect shell rc. Add this snippet to your rc manually:'- warn ''- while IFS= read -r line; do warn " $line"; done <<< "$SOURCE_BLOCK"-else- touch "$RC"- if grep -qF "$MARKER_BEGIN" "$RC"; then- info "Replacing openviking source hook in $RC"- # Strip existing block (whether it's the new one-liner or an old- # inline-wrapper block from a previous version).- awk -v b="$MARKER_BEGIN" -v e="$MARKER_END" '- $0 == b {skip=1; next}- $0 == e {skip=0; next}- !skip- ' "$RC" > "$RC.tmp" && mv "$RC.tmp" "$RC"- else- info "Appending openviking source hook to $RC"- fi- printf '\n%s\n' "$SOURCE_BLOCK" >> "$RC"-fi--# ----- 5. Plugin install ------#-# `claude plugin` was introduced in Claude Code 2.0 (2025-10). Older builds only-# expose `claude mcp add` and the hooks system. We detect the major version and-# offer a legacy install path that wires the same functionality through-# `claude mcp add` + a merge into ~/.claude/settings.json.-#-# Note on `--scope`:-# - `claude mcp add --scope user` has been supported since MCP first shipped,-# and the default (`local`) ties the server to one project, so we DO pass it.-# - `claude plugin install` / `claude plugin marketplace add` already default to-# user scope, and the `--scope` flag is rejected by older 2.0.x builds (e.g.-# 2.0.76). We omit it.--heading '5. Plugin install'--# Probe for `claude plugin` support directly rather than parsing --version output.-# The version-string format isn't a stable contract; the subcommand's existence is.-has_plugin_subcommand() {- claude plugin --help >/dev/null 2>&1-}--install_legacy() {- local plugin_dir="$REPO_DIR/examples/claude-code-memory-plugin"- local hooks_src="$plugin_dir/hooks/hooks.json"- local settings="$HOME/.claude/settings.json"- local ts; ts=$(date +%Y%m%d-%H%M%S)-- info "Legacy mode: registering MCP server + merging hooks into $settings"-- # 1) MCP server. Single-quoted ${VAR} literals so Claude Code expands them at- # MCP launch time using whatever the rc wrapper has injected.- info 'claude mcp add openviking (user scope)'- claude mcp remove openviking -s user >/dev/null 2>&1 || true- claude mcp add --scope user --transport http openviking \- '${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \- --header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \- --header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}' || {- err 'claude mcp add failed'- return 1- }-- # 2) Hooks: replace ${CLAUDE_PLUGIN_ROOT} (only expanded by 2.0+ plugin loader)- # with an absolute path, then merge into ~/.claude/settings.json. Back up- # first; verify the merged JSON before overwriting.- if [ ! -f "$hooks_src" ]; then- err "hooks source not found: $hooks_src"- return 1- fi- mkdir -p "$HOME/.claude"- [ -f "$settings" ] || echo '{}' > "$settings"- cp -p "$settings" "$settings.bak.$ts"- info "Backup: $settings.bak.$ts"-- # mktemp instead of `$$` — predictable PID-based names are vulnerable to- # symlink races on shared /tmp.- local tmp_h tmp_s- tmp_h=$(mktemp "${TMPDIR:-/tmp}/ov-hooks.XXXXXX") || { err 'mktemp failed'; return 1; }- tmp_s=$(mktemp "${TMPDIR:-/tmp}/ov-settings.XXXXXX") || { err 'mktemp failed'; rm -f "$tmp_h"; return 1; }-- # Replace ${CLAUDE_PLUGIN_ROOT} via jq, not sed — $plugin_dir comes from a- # user-configurable env var and may contain &, |, or \ which would corrupt- # sed substitution.- if ! jq --arg root "$plugin_dir" \- 'walk(if type == "string" then gsub("\\$\\{CLAUDE_PLUGIN_ROOT\\}"; $root) else . end)' \- "$hooks_src" > "$tmp_h" 2>/dev/null; then- err "expanding CLAUDE_PLUGIN_ROOT in $hooks_src failed"- rm -f "$tmp_h" "$tmp_s"- return 1- fi-- # Shallow merge — keep user's other hook events; same-event keys get overwritten.- # Explicit error branch so a malformed settings.json doesn't kill the whole- # script via `set -e` and skip our cleanup.- if ! jq --slurpfile h "$tmp_h" '.hooks = ((.hooks // {}) * $h[0].hooks)' \- "$settings" > "$tmp_s" 2>/dev/null; then- err "merging hooks into $settings failed; original untouched (intermediate: $tmp_s)"- rm -f "$tmp_h"- return 1- fi- mv "$tmp_s" "$settings"- rm -f "$tmp_h"- info 'hooks merged'-}--install_modern() {- # `--scope` intentionally omitted. Default scope is already user; passing it- # breaks older 2.0.x builds that don't recognize the flag.- local mp='openviking-plugins-local'- local plugin='claude-code-memory-plugin@openviking-plugins-local'-- # Marketplace: add when missing, else UPDATE. `marketplace add` on an existing- # entry is a no-op that does NOT re-read the source, so a bumped plugin version- # in the checkout is never picked up on re-run. Re-running the installer is the- # supported upgrade path, so the already-present branch must re-sync the catalog.- if claude plugin marketplace list 2>/dev/null | grep -qF "$mp"; then- info "claude plugin marketplace update ($mp)"- claude plugin marketplace update "$mp" || \- warn 'marketplace update returned non-zero — continuing'- else- info 'claude plugin marketplace add'- ( cd "$REPO_DIR" && claude plugin marketplace add "$REPO_DIR/examples" ) || \- warn 'marketplace add returned non-zero — continuing'- fi-- # Plugin: update when already installed, else install. `plugin install` is a- # no-op on an existing install (it will NOT pull a newer version), so an- # explicit `plugin update` is required for the re-run-to-upgrade path.- if claude plugin list 2>/dev/null | grep -qF "$plugin"; then- info "claude plugin update ($plugin)"- ( cd "$REPO_DIR" && claude plugin update "$plugin" ) || \- warn 'plugin update returned non-zero — continuing'- else- info 'claude plugin install'- ( cd "$REPO_DIR" && claude plugin install "$plugin" ) || {- warn 'plugin install failed — falling back to legacy mode'- install_legacy- return $?- }- fi- # Belt-and-suspenders: ensure enabled even if install/update left it disabled.- claude plugin enable "$plugin" >/dev/null 2>&1 || true-}--# Statusline registration. CC's plugin manifest doesn't accept a statusLine-# field (only hooks/MCP/agents/skills are bundle-able), so we have to inject-# into the user's ~/.claude/settings.json. Always opt-in: we ask first, both-# because terminal real-estate is opinionated and because users often have-# their own statusline they don't want clobbered.-register_statusline() {- local plugin_dir="$REPO_DIR/examples/claude-code-memory-plugin"- # Quote the script path so install dirs containing spaces/metacharacters- # don't break when CC invokes the command via /bin/sh -c.- local cmd="node \"$plugin_dir/scripts/statusline.mjs\""- local settings="$HOME/.claude/settings.json"-- heading 'Statusline (optional)'- info 'OpenViking can show a one-line server/recall status under the input box.'- info 'Sample: "OV ✓ │ ↩ 6 mem (0.92) · 50ms │ ✎ 573/20k · 2 arch │ +3 today"'-- mkdir -p "$HOME/.claude"- [ -f "$settings" ] || echo '{}' > "$settings"-- local existing- existing=$(jq -r '.statusLine.command // empty' "$settings" 2>/dev/null || echo "")-- if [ -n "$existing" ] && [ "$existing" = "$cmd" ]; then- info 'Already registered. (Re-run this installer with no changes to refresh.)'- return 0- fi-- if [ -n "$existing" ]; then- warn "Existing statusline detected:"- warn " $existing"- ask 'Replace it with OpenViking statusline? [y/N] '- else- ask 'Enable OpenViking statusline? [y/N] '- fi- local reply- read -r reply || reply=""- case "$reply" in- y|Y|yes|Yes|YES) ;;- *)- info 'Skipped statusline registration. Run this installer again to enable it later.'- return 0- ;;- esac-- local ts; ts=$(date +%Y%m%d-%H%M%S)- cp -p "$settings" "$settings.bak.$ts"- # mktemp inside the same directory as $settings so the final `mv` is a- # rename within one filesystem (atomic). Using $TMPDIR risks crossing- # filesystems on Linux (tmpfs vs $HOME), which makes `mv` non-atomic.- local tmp- tmp=$(mktemp "$settings.XXXXXX") || { err 'mktemp failed'; return 1; }- if ! jq --arg cmd "$cmd" \- '.statusLine = {type: "command", command: $cmd, padding: 0}' \- "$settings" > "$tmp" 2>/dev/null; then- err "writing statusline into $settings failed; original untouched"- rm -f "$tmp"- return 1- fi- mv "$tmp" "$settings"- info "statusline registered (backup: $settings.bak.$ts)"- info 'Disable later: jq "del(.statusLine)" '"$settings"' > t && mv t '"$settings"- info 'Or silence only: export OPENVIKING_STATUSLINE=off'-}--USE_LEGACY=0-if [ "$CLAUDE_AVAILABLE" -eq 1 ] && ! has_plugin_subcommand; then- warn "This Claude Code build doesn't expose 'claude plugin' (introduced in 2.0)."- ask 'Use legacy compatibility mode (claude mcp add + settings.json merge)? [Y/n] '- read -r reply || reply=""- case "$reply" in- n|N|no|No|NO)- warn "Skipping plugin install. Upgrade to Claude Code >= 2.0 and re-run."- CLAUDE_AVAILABLE=0- ;;- *) USE_LEGACY=1 ;;- esac-fi--if [ "$CLAUDE_AVAILABLE" -eq 1 ]; then- if [ "$USE_LEGACY" -eq 1 ]; then- install_legacy- else- install_modern- fi- register_statusline || warn 'statusline registration skipped (continuing)'-else- warn "Run these manually after installing Claude Code:"- warn " cd \"$REPO_DIR\""- warn ' claude plugin marketplace add "$(pwd)/examples"'- warn ' claude plugin install claude-code-memory-plugin@openviking-plugins-local'-fi--# ----- Done ------#-# We can't auto-source the rc into the user's shell — this script runs in a-# subshell (e.g. `bash <(curl ...)`), so any export/source we do here dies-# when the script exits. The user has to run `source` themselves, hence the-# bold callout below. (`source <(curl ...)` would work but is unsafe to-# recommend — it pipes remote code straight into the user's interactive shell.)--heading 'Done!'-info "Source: $REPO_DIR"-info "Config: $OVCLI_CONF"-[ -n "$RC" ] && info "Shell rc: $RC"-printf '\n'-if [ -n "$RC" ]; then- printf '%s%sNext — run this in your shell to pick up the wrapper:%s\n' "$BOLD" "$YELLOW" "$RESET"- printf ' %s%ssource %s%s\n' "$BOLD" "$CYAN" "$RC" "$RESET"- printf ' (or just open a new terminal window)\n\n'-fi-info 'Then:'-info ' claude # start Claude Code'-info ' /mcp # inside Claude Code, verify the OpenViking entry'-printf '\n'-printf '%sCurious what your statusline shows, or want to tweak it?%s Open Claude Code and paste:\n' "$BOLD" "$RESET"-printf ' %sRead %s/examples/claude-code-memory-plugin/STATUSLINE.md. Walk me through what each segment of my OpenViking statusline means, then ask me whether I want to personalize anything.%s\n' "$CYAN" "$REPO_DIR" "$RESET"+SHARED_URL="${OPENVIKING_SHARED_INSTALL_URL:-https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh}"+tmp="$(mktemp "${TMPDIR:-/tmp}/ov-memory-install.XXXXXX")" || { echo "mktemp failed" >&2; exit 1; }+trap 'rm -f "$tmp"' EXIT+curl -fsSL -o "$tmp" "$SHARED_URL"+exec bash "$tmp" --harness claude "$@"diff --git a/examples/claude-code-memory-plugin/setup-helper/tos-install.sh b/examples/claude-code-memory-plugin/setup-helper/tos-install.shindex d98f8995d..db25bb5fd 100755--- a/examples/claude-code-memory-plugin/setup-helper/tos-install.sh+++ b/examples/claude-code-memory-plugin/setup-helper/tos-install.sh@@ -2,28 +2,27 @@## OpenViking Memory Plugin for Claude Code — TOS bootstrap (China-friendly).#-# For users who can't reach github.com / raw.githubusercontent.com. Pulls both-# the installer and the source archive from Volcengine TOS instead of GitHub,-# then hands off to the standard interactive installer.+# For users who can't reach github.com / raw.githubusercontent.com. Pulls the+# shared installer from Volcengine TOS and runs it with the TOS distribution+# channel preselected (Claude preselected as the harness).## One-liner:# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/claude-code-memory-plugin/tos-install.sh)## Env overrides:-# OPENVIKING_TOS_BASE default: https://ovrelease.tos-cn-beijing.volces.com-# OPENVIKING_REPO_ARCHIVE_URL default: $OPENVIKING_TOS_BASE/releases/latest/openviking-source.zip+# OPENVIKING_TOS_BASE default: https://ovrelease.tos-cn-beijing.volces.com# (every install.sh env override applies too.)set -euo pipefailTOS_BASE="${OPENVIKING_TOS_BASE:-https://ovrelease.tos-cn-beijing.volces.com}"TOS_BASE="${TOS_BASE%/}"-export OPENVIKING_REPO_ARCHIVE_URL="${OPENVIKING_REPO_ARCHIVE_URL:-$TOS_BASE/releases/latest/openviking-source.zip}"+export OPENVIKING_TOS_BASE="$TOS_BASE"+export OPENVIKING_SHARED_INSTALL_URL="${OPENVIKING_SHARED_INSTALL_URL:-$TOS_BASE/memory-plugin-shared/install.sh}"# Fetch the real installer to a file (not a pipe) so it keeps the terminal on-# stdin for its interactive prompts. It then sources the repo from the archive-# URL above instead of git clone.+# stdin for its interactive prompts.installer=$(mktemp "${TMPDIR:-/tmp}/ov-cc-install.XXXXXX") || { echo "mktemp failed" >&2; exit 1; }trap 'rm -f "$installer"' EXIT-curl -fsSL -o "$installer" "$TOS_BASE/claude-code-memory-plugin/install.sh"-bash "$installer"+curl -fsSL -o "$installer" "$OPENVIKING_SHARED_INSTALL_URL"+bash "$installer" --harness claude --dist tos "$@"diff --git a/examples/claude-code-memory-plugin/setup-helper/wrapper.sh b/examples/claude-code-memory-plugin/setup-helper/wrapper.shdeleted file mode 100644index bcf6bf6be..000000000--- a/examples/claude-code-memory-plugin/setup-helper/wrapper.sh+++ /dev/null@@ -1,107 +0,0 @@-# OpenViking claude-code memory plugin shell wrapper.-#-# Sourced from the user's shell rc via a `[ -f ... ] && . ...` hook that-# the installer writes once. Updates land for free via the installer's-# `git fetch + reset --hard` of the plugin checkout — no need to re-run-# the installer just to refresh this wrapper.-#-# The MCP server URL and bearer token end up in `.mcp.json` rather than-# in the model's per-process env, so Claude Code needs the OpenViking-# credentials in the env at `claude` launch. The wrapper pulls them from-# ovcli.conf and injects them as a prefix, so the user doesn't need to-# `export OPENVIKING_API_KEY` globally and risk leaking it into other-# subprocesses.-#-# Besides `claude`, any extra launch commands listed in-# $OPENVIKING_CC_WRAP_EXTRA (set by the installer in your shell rc, one-# command per ';'-separated entry — e.g. "cc-custom") get the same injection.-# For a multi-word entry, only invocations whose leading arguments match the-# configured sub-command are wrapped; every other invocation of that command-# passes through untouched.-#-# Targets bash and zsh (the only shells that source ~/.bashrc / ~/.zshrc).-# Splitting is done with parameter expansion rather than unquoted word-# splitting so it behaves the same under zsh (which does not field-split-# unquoted expansions by default).--# Run a command with OpenViking credentials from ovcli.conf injected into-# its environment only — never exported globally.-_openviking_run() {- local _ov_conf="${OPENVIKING_CLI_CONFIG_FILE:-$HOME/.openviking/ovcli.conf}"- if [ -f "$_ov_conf" ] && command -v jq >/dev/null 2>&1; then- local _ov_url _ov_key- _ov_url=$(jq -r '.url // empty' "$_ov_conf" 2>/dev/null)- _ov_key=$(jq -r '.api_key // empty' "$_ov_conf" 2>/dev/null)- OPENVIKING_URL="${OPENVIKING_URL:-$_ov_url}" \- OPENVIKING_API_KEY="${OPENVIKING_API_KEY:-$_ov_key}" \- command "$@"- else- command "$@"- fi-}--# Runtime guard for a wrapped command. $1 = exec helper, $2 = command name,-# $3 = the configured sub-command prefix (empty for single-word commands),-# rest = the actual args. Inject only when the leading args match $3.-_openviking_dispatch() {- local _ov_helper="$1" _ov_cmd="$2" _ov_want="$3"; shift 3- if [ -n "$_ov_want" ]; then- local _ov_rest="$_ov_want" _ov_word _ov_actual _ov_i=1 _ov_ok=1- while [ -n "$_ov_rest" ]; do- case "$_ov_rest" in- *' '*) _ov_word="${_ov_rest%% *}"; _ov_rest="${_ov_rest#* }" ;;- *) _ov_word="$_ov_rest"; _ov_rest="" ;;- esac- eval "_ov_actual=\${$_ov_i-}"- if [ "$_ov_actual" != "$_ov_word" ]; then _ov_ok=0; break; fi- _ov_i=$((_ov_i + 1))- done- if [ "$_ov_ok" != 1 ]; then- command "$_ov_cmd" "$@"- return $?- fi- fi- "$_ov_helper" "$_ov_cmd" "$@"-}--# Define a wrapper function for each ';'-separated entry in $2, routing it-# through the exec helper $1. No subshell (functions must persist in the-# current shell) and no unquoted word splitting (zsh-safe).-_openviking_define_wrappers() {- local _ov_helper="$1" _ov_list="$2" _ov_entry _ov_head _ov_sub- [ -n "$_ov_list" ] || return 0- while [ -n "$_ov_list" ]; do- case "$_ov_list" in- *';'*) _ov_entry="${_ov_list%%;*}"; _ov_list="${_ov_list#*;}" ;;- *) _ov_entry="$_ov_list"; _ov_list="" ;;- esac- _ov_entry="${_ov_entry#"${_ov_entry%%[![:space:]]*}"}"- _ov_entry="${_ov_entry%"${_ov_entry##*[![:space:]]}"}"- [ -n "$_ov_entry" ] || continue- # Allow only word-like characters so a value can never smuggle shell- # metacharacters (" $ ` \ ;, …) into the eval below.- case "$_ov_entry" in- *[!A-Za-z0-9\ ._-]*) continue ;;- esac- _ov_head="${_ov_entry%% *}"- if [ "$_ov_head" = "$_ov_entry" ]; then _ov_sub=""; else _ov_sub="${_ov_entry#* }"; fi- # Reject empty, leading-`-` (would be misread as an option by `alias`- # below and `command` in the dispatcher), or any non-word-char head.- case "$_ov_head" in- ''|-*|*[!A-Za-z0-9_-]*) continue ;;- esac- # A same-named shell alias (e.g. `alias cc=claude`) already routes through- # the base `claude` wrapper once it expands, so it needs no function here —- # and defining one is actively harmful: bash expands the alias mid-eval and- # clobbers the real wrapper, while zsh aborts with a parse error on every- # shell start. Skip alias names; they're covered for free.- if alias "$_ov_head" >/dev/null 2>&1; then- continue- fi- eval "${_ov_head}() { _openviking_dispatch \"$_ov_helper\" \"$_ov_head\" \"$_ov_sub\" \"\$@\"; }"- done-}--claude() { _openviking_run claude "$@"; }--_openviking_define_wrappers _openviking_run "${OPENVIKING_CC_WRAP_EXTRA:-}"diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.jsonindex 4c869a5e5..729409603 100644--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "openviking-memory",- "version": "0.5.0",- "description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on PreCompact, and active-window heuristic + idle-TTL sweep on SessionStart (source=startup|clear).",+ "version": "0.6.0",+ "description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on PreCompact, and active-window heuristic + idle-TTL sweep on SessionStart (source=startup|clear). Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.","author": {"name": "OpenViking","url": "https://github.com/volcengine/OpenViking"@@ -21,7 +21,7 @@"interface": {"displayName": "OpenViking Memory","shortDescription": "Long-term semantic memory for Codex",- "longDescription": "Hooks Codex's lifecycle to keep an external semantic memory: recall relevant memories on each UserPromptSubmit; on every Stop (turn end) append the new user/assistant turns to a long-lived OpenViking session keyed by codex session_id; on PreCompact commit that session so OV's extractor produces durable memories before context is summarized; on SessionStart(source=clear) commit any orphaned prior session before /clear discards it. Also exposes explicit MCP tools (search, store, read, list, grep, glob, forget, add_resource, health) over OpenViking's native streamable-HTTP /mcp endpoint for manual use.",+ "longDescription": "Hooks Codex's lifecycle to keep an external semantic memory: recall relevant memories on each UserPromptSubmit; on every Stop (turn end) append the new user/assistant turns to a long-lived OpenViking session keyed by codex session_id; on PreCompact commit that session so OV's extractor produces durable memories before context is summarized; on SessionStart(source=clear) commit any orphaned prior session before /clear discards it. Also exposes explicit MCP tools (recall, search, store, read, list, grep, glob, forget, add_resource, health) through a local stdio proxy to OpenViking's native streamable-HTTP /mcp endpoint for manual use.","developerName": "OpenViking","category": "Productivity","capabilities": [@@ -30,7 +30,7 @@"Pre-compaction memory extraction","Session archive search and original-text read-back","Resource ingestion for RAG (add_resource)",- "Explicit MCP tools: search, store, read, list, grep, glob, forget, add_resource, health"+ "Explicit MCP tools: recall, search, store, read, list, grep, glob, forget, add_resource, health"],"websiteURL": "https://github.com/volcengine/OpenViking"}diff --git a/examples/codex-memory-plugin/.gitignore b/examples/codex-memory-plugin/.gitignoreindex d74551f99..ff2c58566 100644--- a/examples/codex-memory-plugin/.gitignore+++ b/examples/codex-memory-plugin/.gitignore@@ -1,5 +1,2 @@node_modules/-servers/*.mjs-servers/*.js-!servers/memory-server.js*.tsbuildinfodiff --git a/examples/codex-memory-plugin/.mcp.json b/examples/codex-memory-plugin/.mcp.jsonindex fb7ad4686..fd5668560 100644--- a/examples/codex-memory-plugin/.mcp.json+++ b/examples/codex-memory-plugin/.mcp.json@@ -1,7 +1,12 @@{"mcpServers": {"openviking-memory": {- "url": "http://127.0.0.1:1933/mcp"+ "command": "node",+ "args": [+ "servers/mcp-proxy.mjs"+ ],+ "cwd": ".",+ "startup_timeout_sec": 30}}}diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.mdindex 9a7b0e404..7aeaf7155 100644--- a/examples/codex-memory-plugin/DESIGN.md+++ b/examples/codex-memory-plugin/DESIGN.md@@ -136,13 +136,21 @@ machine, no sweep ever runs and the OV session stays open server-sideforever. Accepted. Future work could add an MCP tool`openviking_commit_pending` so the model can commit explicitly.-## Stop hook — append only, no commit+## Stop hook — append + threshold commitEvery `Stop` reads `transcript_path`, slices to `[capturedTurnCount, end)`,and appends each new user/assistant turn to the OV session for this codex`session_id` (the `/messages` endpoint auto-creates it on first append).State is updated:-`{ovSessionId, capturedTurnCount, lastUpdatedAt: now}`. Never commits.+`{ovSessionId, capturedTurnCount, lastUpdatedAt: now}`.++After a successful append, Stop reads session meta and commits when+`pending_tokens >= OPENVIKING_COMMIT_TOKEN_THRESHOLD` (default 20000).+The threshold commit passes+`keep_recent_count=OPENVIKING_COMMIT_KEEP_RECENT_COUNT` (default 10) so+the newest turns stay live after archive/extract. This keeps long-running+sessions from waiting until PreCompact/SessionStart while still avoiding+commit-on-every-turn fragmentation.## Injected context boundarydiff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex 84eae4217..516f3f85a 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -5,43 +5,42 @@ Long-term semantic memory for [Codex](https://developers.openai.com/codex), poweThis is the Codex counterpart to [`claude-code-memory-plugin`](../claude-code-memory-plugin). It hooks Codex's lifecycle to:- **Auto-recall** relevant memories on every `UserPromptSubmit` and inject them via `hookSpecificOutput.additionalContext`-- **Incremental capture on `Stop`** (turn end): append the new user/assistant turns to a deterministic OpenViking session id `cx-<codex_session_id>`. No commit per turn.+- **Incremental capture on `Stop`** (turn end): append the new user/assistant turns to a deterministic OpenViking session id `cx-<codex_session_id>`. When `pending_tokens` reaches `OPENVIKING_COMMIT_TOKEN_THRESHOLD`, commit while keeping a recent live tail.- **Commit on `PreCompact`**: trigger OpenViking's memory extractor on the full pre-compact transcript before Codex summarizes it.- **Commit on `SessionStart` (source=startup|clear)**: active-window heuristic — if exactly one *other* state file was touched within the last 2 min, commit it (the just-ended session). On `≥2`, defer to idle-TTL sweep at the tail. `source=resume` never commits or sweeps; if the live OV session was already committed, it may inject the latest archive summary for continuity. See `DESIGN.md` for the full decision tree.-It also wires Codex up to OpenViking's native `/mcp` endpoint (streamable HTTP, Bearer auth), so the model has direct access to the `search`, `store`, `read`, `list`, `grep`, `glob`, `forget`, `add_resource`, and `health` tools — no local MCP server process to maintain.+It also starts a local stdio MCP proxy that forwards to OpenViking's native `/mcp` endpoint with credentials resolved from env / `ovcli.conf`, so the model has direct access to the `search`, `store`, `read`, `list`, `grep`, `glob`, `forget`, `add_resource`, and `health` tools.## Quick Start-There are two install paths. **Pick one — don't mix them** (both surface the same `openviking-memory` plugin; enabling it from both would run the hooks twice). The **one-line installer (A)** is the recommended path for most users, and the only one that supports authenticated or remote/cloud servers; the **marketplace install (B)** is a convenience for a local, unauthenticated OpenViking only.+There are two install paths. **Pick one — don't mix them** (both surface the same `openviking-memory` plugin; enabling it from both would run the hooks twice). The **one-line installer (A)** is the recommended path for most users; the marketplace install (B) is useful when you already manage `~/.openviking/ovcli.conf` yourself.### A. One-line installer — `curl | bash` (recommended)```bash-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/codex-memory-plugin/setup-helper/install.sh)+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness codex```-The installer:+Claude Code and Codex share this installer (drop `--harness codex` to pick interactively). It asks for your language (English/中文), the download source (GitHub, or a TOS mirror for GitHub-blocked regions — pass `--dist tos`; Codex on TOS installs from a TOS-hosted git repo and keeps remote updates), and your OpenViking credentials. It:-1. Checks `codex`, `git`, and Node.js 22+-2. Clones or refreshes `~/.openviking/openviking-repo`-3. Registers a local `openviking-plugins-local` marketplace, enables `openviking-memory@openviking-plugins-local`, sets `features.plugin_hooks = true`-4. Renders the cached `.mcp.json` URL **and** bearer/identity headers from your active `ovcli.conf`-5. Renders the cached `hooks.json` `${PLUGIN_ROOT}` token to absolute script paths (so even older Codex builds that don't substitute `${PLUGIN_ROOT}` work)-6. Appends a `codex()` shell function to your rc that resolves the active OpenViking CLI config at invocation, injects the matching env for Codex/MCP, and strips stale inherited credential env vars+1. Checks `codex` and Node.js 18+ (the plugin itself wants Codex's bundled Node 22+ at runtime)+2. Sets up `~/.openviking/ovcli.conf` interactively+3. Registers the `openviking` marketplace — remote git by default (`codex plugin marketplace add https://github.com/volcengine/OpenViking.git`), or this checkout / a TOS archive in dev/archive mode — and enables `openviking-memory@openviking` with `features.plugin_hooks = true`+4. Keeps the checked-in stdio `.mcp.json` intact; `servers/mcp-proxy.mjs` reads your active `ovcli.conf` at runtime+5. Removes old OpenViking rc wrapper blocks and the pre-unification `openviking-plugins-local` marketplace when found+6. Runs plugin-list and stdio MCP validationAfter install:```bash-source ~/.zshrc # or ~/.bashrccodex # first run: review /hooks once```-### B. Codex marketplace install (local only — not recommended)+### B. Codex marketplace install-> **Local-only, not recommended.** This path connects the plugin to a **local, unauthenticated** OpenViking at `http://127.0.0.1:1933` only. It does **not** support authenticated or remote/cloud servers — Codex won't let user config override a plugin's MCP `url`, and the shipped `.mcp.json` carries no auth. For a remote/cloud/authenticated server — and for most users — use the **one-line installer (A)** above instead.+This path uses the same checked-in stdio MCP proxy as the installer path. Authenticated and remote/cloud servers work when `~/.openviking/ovcli.conf` or the relevant `OPENVIKING_*` env vars are present in Codex's environment.-The repo ships a Codex marketplace catalog at `.agents/plugins/marketplace.json`, so you can install with Codex's native commands — no `curl | bash`, no shell-rc wrapper:+The repo ships a Codex marketplace catalog at `.agents/plugins/marketplace.json`, so you can install with Codex's native commands:```bash# 1. add the OpenViking marketplace (use volcengine/OpenViking once merged@@ -68,76 +67,29 @@ codex # then run /hooks inside Codex to review & approve the hooks> **Requirements & notes**>-> - **Codex version**: this path relies on Codex injecting and inline-substituting `${PLUGIN_ROOT}` in plugin hook commands (current Codex does both). On an older Codex that doesn't substitute `${PLUGIN_ROOT}`, the hook script paths won't resolve — use path **A**, whose installer renders `${PLUGIN_ROOT}` to absolute paths for old Codex.+> - **Codex version**: this path relies on Codex injecting and inline-substituting `${PLUGIN_ROOT}` in plugin hook commands (current Codex does both). On an older Codex that doesn't substitute `${PLUGIN_ROOT}`, the hook script paths won't resolve — use path **A**.> - **Catalog source**: the catalog entry (`.agents/plugins/marketplace.json`) uses a relative source (`./examples/codex-memory-plugin`). `codex plugin add` therefore installs the plugin from the same marketplace snapshot/ref that you added. This keeps fork, branch, tag, and upstream-main installs reproducible and testable without rewriting the catalog.-This path works **out of the box against an unauthenticated local OpenViking** at `http://127.0.0.1:1933`: the shipped `.mcp.json` defaults to that `/mcp` URL and the hooks reference Codex's native `${PLUGIN_ROOT}` token (Codex injects it into the hook env and substitutes it inline), so the model gets the `/mcp` tools and all four lifecycle hooks with **zero rendering**.--**Authenticated or remote/cloud servers are not supported on this path.** Codex won't let user config override a plugin's MCP `url`, and the cached `.mcp.json` ships no bearer token. For an authenticated or remote/cloud server, use the **one-line installer (A)**, which renders the cached `.mcp.json` (URL + bearer + identity headers) from your active `ovcli.conf`.+This path works out of the box against an unauthenticated local OpenViking at `http://127.0.0.1:1933`. For remote/cloud servers, create `~/.openviking/ovcli.conf` with `url`, `api_key`, and optional `account` / `user`; the proxy reads it when Codex starts.### Manual setup-If you don't want the installer touching your rc, do these three things yourself:--1. **Wire the plugin shell wrapper** so Codex gets the same active credentials as the `ov` CLI. The wrapper calls `scripts/ov-credentials.mjs`, re-renders the cached `.mcp.json` bearer field on each launch, and launches Codex with stale credential env vars stripped before the resolved values are added back:-- ```bash- [ -f "$HOME/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.sh" ] \- && . "$HOME/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.sh"- ```--2. **Add the plugin** via a local marketplace pointing at this directory. See `setup-helper/install.sh` for the exact `codex plugin marketplace add` invocation.--3. **Point the cached `.mcp.json` at your server.** The checked-in `.mcp.json` defaults to `http://127.0.0.1:1933/mcp` with no bearer. For a remote/authenticated server, set the `url` and add `"bearer_token_env_var": "OPENVIKING_API_KEY"` — `node scripts/ov-credentials.mjs sync-mcp <path-to-cached .mcp.json>` does both from your active `ovcli.conf`. `hooks/hooks.json` needs **no** rendering on modern Codex: it uses the native `${PLUGIN_ROOT}` token, which Codex injects into the hook env and substitutes inline. Only older Codex builds that don't substitute `${PLUGIN_ROOT}` require replacing it with an absolute path (the installer does this for its cache copy).-- Codex App stores the installed plugin under its cache, not in this source- tree. Common cache locations are:-- - macOS/Linux: `~/.codex/plugins/cache/openviking/openviking-memory/<version>/`- - Windows: `%USERPROFILE%\.codex\plugins\cache\openviking\openviking-memory\<version>\`+If you don't want the installer touching your rc, do these things yourself:- To re-render the installed MCP config on Windows after changing- `~/.openviking/ovcli.conf`:-- ```powershell- $PluginCache = Get-ChildItem "$env:USERPROFILE\.codex\plugins\cache\openviking\openviking-memory" -Directory |- Sort-Object LastWriteTime -Descending |- Select-Object -First 1- node "$($PluginCache.FullName)\scripts\ov-credentials.mjs" sync-mcp "$($PluginCache.FullName)\.mcp.json"- Get-Content -Raw "$($PluginCache.FullName)\.mcp.json"- ```-- A rendered authenticated config looks like:+1. **Write `ovcli.conf` once** so hooks and MCP share the same connection:```json{- "mcpServers": {- "openviking-memory": {- "url": "http://localhost:1933/mcp",- "bearer_token_env_var": "OPENVIKING_API_KEY",- "env_http_headers": {- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER"- }- }- }+ "url": "https://your-openviking-server.example.com",+ "api_key": "<your-api-key>",+ "account": "my-team",+ "user": "alice"}```- Keep the API key in `ovcli.conf` or the environment; do not write the- secret value directly into `.mcp.json`. Restart Codex after changing MCP- config or environment variables.-- You can also ask Codex to repair this on the user's machine with this- prompt:+ Or run the bundled interactive wizard: `node scripts/setup.mjs` (from the plugin directory).- ```text- Fix my installed OpenViking Memory Codex plugin MCP config.- Locate the newest openviking-memory plugin cache under CODEX_HOME, or ~/.codex if unset- (Windows: %CODEX_HOME%, or %USERPROFILE%\.codex if unset). Use ~/.openviking/ovcli.conf- to run scripts/ov-credentials.mjs sync-mcp against the cached .mcp.json. Do not write- the API key value into .mcp.json; show the redacted result and remind me to restart Codex.- ```+2. **Add the plugin** via the remote marketplace (path B above), or via a local directory marketplace: `codex plugin marketplace add <checkout>/examples` reads `examples/.agents/plugins/marketplace.json` and yields the same `openviking-memory@openviking` id. `hooks/hooks.json` needs no rendering on modern Codex: it uses the native `${PLUGIN_ROOT}` token, which Codex injects into the hook env and substitutes inline.## Configuration@@ -147,22 +99,17 @@ Connection / identity source (applies to hooks, MCP, and `ov` commands run insid2. **Env-forced**: set `OPENVIKING_CREDENTIAL_SOURCE=env` to force `OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID`.3. **Fallback**: without an ovcli config, env vars are used; then `ov.conf` (`server.url` / `server.root_api_key` plus legacy `codex.*` tuning); then `http://127.0.0.1:1933` unauthenticated.-The shell wrapper promotes the resolved ovcli credentials into env vars before exec'ing Codex because Codex's MCP runtime can only read auth from env. Hooks call the same resolver directly. The wrapper also exports `OPENVIKING_CLI_CONFIG_FILE`, so an `ov ...` command run inside Codex uses the same active config.-When credentials are forced from env, the wrapper materializes a mode-0600 runtime ovcli config under `~/.openviking/codex-plugin-state/` and points `OPENVIKING_CLI_CONFIG_FILE` at it, so child `ov` commands still use the same credentials as hooks and MCP.+Hooks and the MCP proxy call the same resolver directly, so the model tools and lifecycle hooks follow the same target.Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).Set `actor_peer_id` in `ovcli.conf` (or `OPENVIKING_PEER_ID` with `OPENVIKING_CREDENTIAL_SOURCE=env`) when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Hooks pass it as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval/filesystem calls; MCP gets the same header mapping. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` still resolve as a fallback.-For **unauthenticated local OV** (`ovcli.conf` without `api_key`, or no ovcli.conf at all), `.mcp.json` is rendered *without* `bearer_token_env_var`. Codex 0.130 hard-fails MCP startup with `Environment variable ... is empty` if `bearer_token_env_var` points at an empty/unset env var, so it must be omitted entirely when there's no key.--The `codex()` shell-function wrapper **re-renders this field on every codex launch** based on the currently-active `ovcli.conf` (the one `OPENVIKING_CLI_CONFIG_FILE` points at, falling back to `~/.openviking/ovcli.conf`). That means you can switch between authenticated and unauthenticated OV — e.g. to isolate a benchmark run from production memory — with `ov config switch <name>` or by changing `OPENVIKING_CLI_CONFIG_FILE` before invoking `codex`, with no re-install needed. The wrapper omits empty env-var assignments and strips stale credential env vars first, so `OPENVIKING_API_KEY=` or an inherited key for another user is never accidentally passed to Codex.--**Wrapping extra launch commands.** If you start Codex through a different command — a custom wrapper like `codex-custom`, or a multi-word launcher (a base command plus a sub-command) — the installer can wrap those too. Answer its "Extra launch commands" prompt, or pass `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'` when running it (the env-var form is also what to use when piping the installer through a non-interactive shell). The list is stored in the same rc marker block (read by the wrapper as `$OPENVIKING_CODEX_WRAP_EXTRA`); for a multi-word entry, only invocations whose leading args match the sub-command get the credential injection + `.mcp.json` re-render, so every *other* use of that command passes through untouched. List the *real* launch command, never a shell alias of it: an alias expands to its target before the wrapper runs, so wrap what it points at — `alias cx=codex` already rides the base `codex` wrapper (add nothing), while `alias cx=codex-custom` is covered by listing `codex-custom`. Alias names are skipped if listed.+The checked-in `.mcp.json` contains only a stdio command. It never stores server URLs, bearer-token env mappings, or identity headers, so switching `ovcli.conf` changes the MCP target on the next Codex launch without cache rendering.### Tuning the plugin-All plugin behavior is controlled by `OPENVIKING_*` environment variables — set them in your shell rc (`~/.zshrc` / `~/.bashrc`) so every `codex` launch picks them up. The shell-function wrapper installed alongside the plugin already exports identity vars from `ovcli.conf`; tuning vars sit next to it.+All plugin behavior is controlled by `OPENVIKING_*` environment variables. Connection and identity should normally live in `ovcli.conf`; tuning vars can be exported in your shell rc when you want every Codex launch to pick them up.```sh# ~/.zshrc — examples@@ -196,7 +143,7 @@ Earlier plugin versions configured tuning fields under a `codex` block in `~/.op│ session-start │ │ auto- │ │ auto- │ │ pre-compact- ││ -commit.mjs │ │ recall.mjs│ │ capture.mjs │ │ capture.mjs ││ (active-win │ │ (search + │ │ (append + │ │ (commit + reset │- │ heuristic + │ │ compress) │ │ no commit) │ │ ovSessionId) │+ │ heuristic + │ │ compress) │ │ threshold │ │ ovSessionId) ││ idle TTL + │ │ │ │ │ │ ││ resume inject)│ │ │ │ │ │ │└────┬──────────┘ └────┬──────┘ └──────┬──────┘ └──────────┬──────┘@@ -208,12 +155,12 @@ Earlier plugin versions configured tuning fields under a `codex` block in `~/.op│ /api/v1/content/read │└─────────────────┬─────────────────────────┘│- Codex ◄──────── streamable-HTTP MCP ◄ /mcp (search, store, read, list,- (bearer token via grep, glob, forget,- OPENVIKING_API_KEY) add_resource, health)+ Codex ◄── stdio MCP proxy ──► /mcp (search, store, read, list,+ (env/ovcli.conf) grep, glob, forget,+ add_resource, health)```-The plugin no longer bundles a local stdio MCP server. Codex talks to OpenViking's built-in `/mcp` endpoint directly via streamable HTTP. The checked-in `.mcp.json` ships only the local-default `url` (no `bearer_token_env_var`), so a `codex plugin marketplace add` install connects to an unauthenticated local OV out of the box. For an authenticated server, the one-line installer/wrapper adds `bearer_token_env_var: "OPENVIKING_API_KEY"` to the cached copy when an API key is configured — the key itself stays in `ovcli.conf` / the env, never on disk in `.mcp.json`. (Marketplace installs don't render this, which is why that path is local-only.)+The checked-in `.mcp.json` starts `servers/mcp-proxy.mjs` with `node`. The proxy keeps stdout protocol-clean, reads the same credential sources as the hooks, sends auth and identity headers to `/mcp`, caches the server `mcp-session-id`, and transparently reinitializes once if the server restarts.For details on OpenViking's MCP endpoint, tools, and protocol, see the [MCP Integration Guide](../../docs/en/guides/06-mcp-integration.md). The tools list and per-tool semantics are documented there once, not duplicated here.@@ -267,9 +214,11 @@ Config knobs:| `OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS` | `15000` | Per-candidate startup probe timeout. || `OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS` | `604800000` | Cache TTL used by `UserPromptSubmit` when reading the latest profile. |-### Stop (turn end → `add_message`, NOT `commit`)+### Stop (turn end → `add_message`, threshold commit)++`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append; tool calls/results are retained as compact `[tool-call ...]` / `[tool-result ...]` lines capped by `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default 2000).-`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. No `/commit` per turn — that would over-fragment memory extraction. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append; tool calls/results are retained as compact `[tool-call ...]` / `[tool-result ...]` lines capped by `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default 2000).+After a successful append, Stop reads the session meta and commits when `pending_tokens >= OPENVIKING_COMMIT_TOKEN_THRESHOLD` (default `20000`). Threshold commits pass `keep_recent_count=OPENVIKING_COMMIT_KEEP_RECENT_COUNT` (default `10`) so the newest turns remain live for continuity while older context is archived and extracted. `PreCompact` still commits everything before compaction.### PreCompact (deterministic commit)@@ -316,18 +265,21 @@ codex-memory-plugin/│ ├── recall-compressor-profile.mjs # Compressor profile detection/cache│ ├── session-state.mjs # Per-codex-session OV session state│ ├── auto-recall.mjs # UserPromptSubmit hook (REST /search/search)-│ ├── auto-capture.mjs # Stop hook (REST /sessions/{id}/messages)+│ ├── auto-capture.mjs # Stop hook (append + threshold commit)│ ├── session-start-commit.mjs # SessionStart hook (active-window + idle TTL)│ └── pre-compact-capture.mjs # PreCompact hook+├── servers/+│ ├── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge+│ └── mcp-proxy.test.mjs # proxy contract tests├── setup-helper/│ └── install.sh # One-line installer-├── .mcp.json # Streamable-HTTP MCP wiring (local-default url; installer adds auth)+├── .mcp.json # stdio MCP wiring├── DESIGN.md├── VERIFICATION.md└── README.md```-No `src/`, `servers/`, `node_modules/`, or `package.json`: there is no local MCP server to build or run. All hook scripts are zero-dep `.mjs` running on Codex's bundled Node 22.+No `src/` or `package.json`: there is no build step. Hook scripts and the MCP proxy are zero-dep `.mjs` files running on Codex's bundled Node 22 or a compatible system Node.The Codex marketplace catalog that exposes this plugin for `codex plugin marketplace add` lives at the **repo root** in `.agents/plugins/marketplace.json` (Codex resolves a marketplace manifest from the source root, not from this subdirectory). The catalog points at `./examples/codex-memory-plugin` using a relative source, so the installed plugin follows the same marketplace snapshot/ref that the user added.@@ -341,7 +293,7 @@ The Codex marketplace catalog that exposes this plugin for `codex plugin marketp| Compaction hook | n/a (Claude Code does not expose one) | `PreCompact` — full-transcript commit before context loss || Config section | `claude_code` | `codex` || Default config file | `~/.openviking/ov.conf` | `~/.openviking/ovcli.conf`, falls back to `ov.conf` |-| MCP server | Local stdio (CC quirk: `.mcp.json` doesn't support env var auth) | Streamable HTTP to OpenViking's native `/mcp` (Codex supports `bearer_token_env_var`) |+| MCP server | Local stdio proxy to OpenViking `/mcp` | Local stdio proxy to OpenViking `/mcp` |## Licensediff --git a/examples/codex-memory-plugin/VERIFICATION.md b/examples/codex-memory-plugin/VERIFICATION.mdindex 82d73657a..7b29877ab 100644--- a/examples/codex-memory-plugin/VERIFICATION.md+++ b/examples/codex-memory-plugin/VERIFICATION.md@@ -1,4 +1,4 @@-# Verification SOP — codex plugin (v0.5.0)+# Verification SOP — codex plugin (v0.6.0)End-to-end smoke test against a live OpenViking server. Run this whenever thehook scripts change. Takes ~3 minutes; the only async wait is OV's memorydiff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjsindex 0d3814452..0e347d04e 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs@@ -8,14 +8,14 @@** Strategy:* 1. For this codex session_id, derive one long-lived OpenViking session- * id (`cx-<codex-session-id>`) and remember it in state. Do NOT commit- * per turn.+ * id (`cx-<codex-session-id>`) and remember it in state.* 2. Read transcript_path, parse JSONL rollout, append every new* user/assistant turn since last capture via add_message.+ * 3. If session pending_tokens crosses commitTokenThreshold, commit while+ * keeping a recent live tail for continuity.*- * Commit happens in two other places, never here:- * - PreCompact hook (deterministic, before context compaction)- * - SessionStart hook (active-window heuristic + idle-TTL sweep at tail)+ * PreCompact still commits deterministically before context compaction, and+ * SessionStart still handles orphaned sessions / idle TTL sweep.** Stop output schema accepts {} as a no-op.*@@ -27,10 +27,7 @@import { readFile } from "node:fs/promises";import {- extractTextFromPayload,- isAssistantSideCaptureRole,- normalizeCaptureRole,- shouldCaptureText,+ extractCaptureTurns,} from "./capture-utils.mjs";import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";@@ -89,22 +86,7 @@ function parseTranscript(content) {}function extractTurns(rolloutEntries) {- const turns = [];- for (const entry of rolloutEntries) {- if (!entry || typeof entry !== "object") continue;- const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;- const message = payload.message && typeof payload.message === "object" ? payload.message : null;- const rawRole = message?.role || payload.role || payload.type || payload.kind;- const role = normalizeCaptureRole(rawRole);- if (!role) continue;- if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;-- const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });- const decision = shouldCaptureText(rawText, role, cfg);- if (!decision.shouldCapture) continue;- turns.push({ role, text: decision.text });- }- return turns;+ return extractCaptureTurns(rolloutEntries, cfg);}async function readTranscriptTurns(transcriptPath) {@@ -131,7 +113,9 @@ function selectStopTurns(state, turns) {async function appendTurns(ovSessionId, turns, state) {let appended = 0;for (const turn of turns) {- const body = { role: turn.role, content: turn.text };+ const body = turn.parts?.length+ ? { role: turn.role, parts: turn.parts }+ : { role: turn.role, content: turn.text };if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",@@ -145,6 +129,35 @@ async function appendTurns(ovSessionId, turns, state) {return appended;}+async function maybeCommitByThreshold(ovSessionId, added) {+ if (added <= 0) return { committed: false, pendingTokens: 0, commitCount: 0, totalMessageCount: 0 };+ const meta = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}`);+ const pendingTokens = Number(meta?.pending_tokens || 0);+ const commitCount = Number(meta?.commit_count || 0);+ const totalMessageCount = Number(meta?.total_message_count || 0);+ log("pending_tokens", {+ ovSessionId,+ pending: pendingTokens,+ threshold: cfg.commitTokenThreshold,+ keepRecentCount: cfg.commitKeepRecentCount,+ });+ if (pendingTokens < cfg.commitTokenThreshold) {+ return { committed: false, pendingTokens, commitCount, totalMessageCount };+ }+ const commit = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, {+ method: "POST",+ body: JSON.stringify({ keep_recent_count: cfg.commitKeepRecentCount }),+ });+ const committed = Boolean(commit);+ log("commit", { ovSessionId, ok: committed, pending: pendingTokens });+ return {+ committed,+ pendingTokens,+ commitCount: committed ? commitCount + 1 : commitCount,+ totalMessageCount,+ };+}+// ---------------------------------------------------------------------------// Main// ---------------------------------------------------------------------------@@ -210,8 +223,10 @@ async function main() {}let added = 0;+ let ovSessionId = "";+ let commitInfo = { committed: false, pendingTokens: 0, commitCount: 0, totalMessageCount: 0 };if (newTurns.length > 0) {- const ovSessionId = resolveOvSessionId(state);+ ovSessionId = resolveOvSessionId(state);if (!ovSessionId) {logError("resolve_ov_session", "failed to derive OV session id");} else {@@ -219,6 +234,7 @@ async function main() {await saveState(state);added = await appendTurns(ovSessionId, turnsToAppend, state);log("appended", { ovSessionId, added });+ commitInfo = await maybeCommitByThreshold(ovSessionId, added);}}@@ -227,7 +243,10 @@ async function main() {// could also sweep here, deliberately not — see header comment + DESIGN.md §5.if (added > 0) {- noop(`appended ${added} turn(s) to OpenViking session ${state.ovSessionId}`);+ noop(+ `appended ${added} turn(s) to OpenViking session ${state.ovSessionId}` ++ (commitInfo.committed ? " (committed)" : ""),+ );} else {noop();}diff --git a/examples/codex-memory-plugin/scripts/auto-capture.test.mjs b/examples/codex-memory-plugin/scripts/auto-capture.test.mjsnew file mode 100644index 000000000..d50305c2d--- /dev/null+++ b/examples/codex-memory-plugin/scripts/auto-capture.test.mjs@@ -0,0 +1,200 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import http from "node:http";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));++function readRequestBody(req) {+ return new Promise((resolve, reject) => {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const raw = Buffer.concat(chunks).toString("utf-8");+ try {+ resolve(raw ? JSON.parse(raw) : null);+ } catch (err) {+ reject(err);+ }+ });+ req.on("error", reject);+ });+}++function writeJson(res, value) {+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end(JSON.stringify(value));+}++async function withMockOpenViking(handler, fn) {+ const server = http.createServer((req, res) => {+ handler(req, res).catch((err) => {+ res.writeHead(500, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));+ });+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ const { port } = server.address();+ return await fn(`http://127.0.0.1:${port}`);+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+}++function runAutoCapture(input, env) {+ return new Promise((resolve, reject) => {+ const cleanEnv = { ...process.env };+ for (const key of Object.keys(cleanEnv)) {+ if (key.startsWith("OPENVIKING_")) delete cleanEnv[key];+ }+ const child = spawn(process.execPath, [join(SCRIPT_DIR, "auto-capture.mjs")], {+ env: { ...cleanEnv, ...env },+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => { stdout += chunk.toString(); });+ child.stderr.on("data", (chunk) => { stderr += chunk.toString(); });+ child.on("error", reject);+ child.on("close", (code) => {+ if (code !== 0) {+ reject(new Error(`auto-capture exited ${code}: ${stderr}`));+ return;+ }+ resolve({ stdout, stderr });+ });+ child.stdin.end(JSON.stringify(input));+ });+}++test("auto-capture commits when pending tokens cross threshold", async () => {+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-capture-state-"));+ const transcriptPath = join(stateDir, "transcript.jsonl");+ const debugLogPath = join(stateDir, "debug.log");+ const calls = [];++ try {+ await writeFile(+ transcriptPath,+ [+ JSON.stringify({+ payload: {+ message: {+ role: "user",+ content: "remember that I prefer compact commits",+ },+ },+ }),+ JSON.stringify({+ payload: {+ message: {+ role: "assistant",+ content: "noted for future sessions",+ },+ },+ }),+ JSON.stringify({+ payload: {+ type: "function_call",+ id: "call-1",+ name: "shell",+ arguments: "{\"cmd\":\"pwd\"}",+ },+ }),+ JSON.stringify({+ payload: {+ type: "function_call_output",+ call_id: "call-1",+ output: "project root",+ },+ }),+ ].join("\n"),+ );++ await withMockOpenViking(async (req, res) => {+ const url = new URL(req.url, "http://127.0.0.1");+ calls.push({ method: req.method, path: url.pathname, body: null });+ if (req.method === "GET" && url.pathname === "/health") {+ writeJson(res, { status: "ok", result: { ok: true } });+ return;+ }+ if (req.method === "POST" && url.pathname.endsWith("/messages")) {+ calls[calls.length - 1].body = await readRequestBody(req);+ writeJson(res, { status: "ok", result: { ok: true } });+ return;+ }+ if (req.method === "GET" && url.pathname === "/api/v1/sessions/cx-codex_commit") {+ writeJson(res, {+ status: "ok",+ result: { pending_tokens: 2500, commit_count: 2, total_message_count: 8 },+ });+ return;+ }+ if (req.method === "POST" && url.pathname === "/api/v1/sessions/cx-codex_commit/commit") {+ calls[calls.length - 1].body = await readRequestBody(req);+ writeJson(res, { status: "ok", result: { archived: true, task_id: "task-1" } });+ return;+ }+ res.writeHead(404, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ status: "error", error: "not found" }));+ }, async (baseUrl) => {+ const result = await runAutoCapture(+ { session_id: "codex:commit", transcript_path: transcriptPath },+ {+ OPENVIKING_AUTO_CAPTURE: "1",+ OPENVIKING_CAPTURE_ASSISTANT_TURNS: "1",+ OPENVIKING_CODEX_STATE_DIR: stateDir,+ OPENVIKING_DEBUG: "1",+ OPENVIKING_DEBUG_LOG: debugLogPath,+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),+ OPENVIKING_CREDENTIAL_SOURCE: "env",+ OPENVIKING_COMMIT_TOKEN_THRESHOLD: "1000",+ OPENVIKING_COMMIT_KEEP_RECENT_COUNT: "7",+ OPENVIKING_MIN_QUERY_LENGTH: "1",+ OPENVIKING_TIMEOUT_MS: "5000",+ OPENVIKING_URL: baseUrl,+ },+ );++ const output = JSON.parse(result.stdout.trim());+ assert.ok(output && typeof output === "object");+ });++ const commitCall = calls.find((call) => call.path.endsWith("/commit"));+ const debugLog = await readFile(debugLogPath, "utf-8").catch(() => "");+ assert.ok(commitCall, `expected threshold commit call; calls=${JSON.stringify(calls)} debug=${debugLog}`);+ assert.deepEqual(commitCall.body, { keep_recent_count: 7 });++ const messageBodies = calls+ .filter((call) => call.path.endsWith("/messages"))+ .map((call) => call.body);+ const toolCallBody = messageBodies.find((body) =>+ body.parts?.some((part) => part.type === "tool" && part.tool_status === "running")+ );+ const toolResultBody = messageBodies.find((body) =>+ body.parts?.some((part) => part.type === "tool" && part.tool_status === "completed")+ );+ assert.deepEqual(toolCallBody.parts[0], {+ type: "tool",+ tool_id: "call-1",+ tool_name: "shell",+ tool_status: "running",+ tool_input: { cmd: "pwd" },+ });+ assert.deepEqual(toolResultBody.parts[0], {+ type: "tool",+ tool_id: "call-1",+ tool_name: "shell",+ tool_status: "completed",+ tool_output: "project root",+ });+ } finally {+ await rm(stateDir, { recursive: true, force: true });+ }+});diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjsindex 8d251ec4f..74298718b 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs@@ -97,11 +97,13 @@ async function fetchJSON(path, init = {}) {if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);- if (!body) return null;- if (!res.ok || body.status === "error") return null;- return body.result ?? body;+ if (!body) return { ok: false, status: res.status };+ if (!res.ok || body.status === "error") {+ return { ok: false, status: res.status, error: body.error || body };+ }+ return { ok: true, result: body.result ?? body };} catch {- return null;+ return { ok: false, status: 0 };} finally {clearTimeout(timer);}@@ -220,7 +222,7 @@ async function searchScope(query, targetUri, limit, bucket = "memories", sessionmethod: "POST",body: JSON.stringify(body),});- return result?.[bucket] || [];+ return result.ok ? (result.result?.[bucket] || []) : [];}// Candidate target URIs for a bucket, most-specific first. In trusted mode a@@ -287,11 +289,41 @@ function resolveRecallSessionId(codexSessionId) {async function readMemoryContent(uri) {try {const result = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);- if (result && typeof result === "string" && result.trim()) return result.trim();+ if (result.ok && typeof result.result === "string" && result.result.trim()) return result.result.trim();} catch { /* fallback */ }return null;}+async function recallViaTypeQuotaEndpoint(query) {+ const result = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify({+ query,+ quotas: {+ events: Math.max(cfg.recallLimit, 1),+ entities: Math.max(cfg.recallLimit, 1),+ preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),+ experiences: 0,+ },+ max_chars: cfg.recallCompressMaxInputChars || 6500,+ min_score: cfg.scoreThreshold,+ render: true,+ }),+ });+ if (!result.ok) {+ log("recall_endpoint_fallback", { status: result.status || 0 });+ return null;+ }+ const rendered = String(result.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "OpenViking memory digest:",+ rendered,+ "",+ "More detail: use the OpenViking MCP recall/read/search tools with cited viking:// URIs if needed.",+ ].join("\n");+}+function truncateText(text, maxChars) {const value = String(text || "").trim();if (value.length <= maxChars) return value;@@ -509,12 +541,24 @@ async function main() {}const health = await fetchJSON("/health");- if (!health) {+ if (!health.ok) {logError("health_check", "server unreachable or unhealthy");emit();return;}+ const endpointRecall = await recallViaTypeQuotaEndpoint(userPrompt);+ if (endpointRecall !== null) {+ if (!endpointRecall) {+ log("skip", { stage: "recall_endpoint", reason: "no results" });+ emit();+ return;+ }+ log("recall_endpoint", { chars: endpointRecall.length });+ emit(endpointRecall);+ return;+ }+const candidateLimit = Math.max(cfg.recallLimit * 4, 20);const allMemories = await searchAll(userPrompt, candidateLimit, recallSessionId);if (allMemories.length === 0) {diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjsindex a04529c9d..641925b86 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs@@ -30,6 +30,11 @@ function writeJson(res, value) {res.end(JSON.stringify(value));}+function writeStatusJson(res, status, value) {+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify(value));+}+async function withMockOpenViking(handler, fn) {const server = http.createServer((req, res) => {handler(req, res).catch((err) => {@@ -151,6 +156,74 @@ test("auto-recall uses context-aware search with the derived OpenViking session}});+test("auto-recall prefers the server recall endpoint when available", async () => {+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-endpoint-"));+ const requests = [];++ try {+ await withMockOpenViking(async (req, res) => {+ const url = new URL(req.url, "http://127.0.0.1");+ if (req.method === "GET" && url.pathname === "/health") {+ writeJson(res, { status: "ok", result: { ok: true } });+ return;+ }+ if (req.method === "POST" && url.pathname === "/api/v1/search/recall") {+ const body = await readRequestBody(req);+ requests.push({ path: url.pathname, body });+ writeJson(res, {+ status: "ok",+ result: {+ entries: [{+ uri: "viking://user/zeus/memories/events/launch.md",+ score: 0.9,+ type: "events",+ mode: "summary",+ summary: "Launch summary",+ }],+ rendered: '<memory_group type="events" count="1">\n<memory index="1" type="summary">\n <uri>viking://user/zeus/memories/events/launch.md</uri>\n <summary>Launch summary</summary>\n</memory>\n</memory_group>',+ stats: { returned: 1 },+ },+ });+ return;+ }+ if (req.method === "POST" && url.pathname === "/api/v1/search/search") {+ requests.push({ path: url.pathname, body: await readRequestBody(req) });+ writeStatusJson(res, 500, { status: "error", error: "should not fallback" });+ return;+ }+ res.writeHead(404, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ status: "error", error: "not found" }));+ }, async (baseUrl) => {+ const result = await runAutoRecall(+ { prompt: "please use server recall", session_id: "codex:recall" },+ {+ OPENVIKING_AUTO_RECALL: "1",+ OPENVIKING_CODEX_STATE_DIR: stateDir,+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),+ OPENVIKING_CREDENTIAL_SOURCE: "env",+ OPENVIKING_RECALL_COMPRESS: "0",+ OPENVIKING_RECALL_LIMIT: "2",+ OPENVIKING_RECALL_TIMEOUT_MS: "10000",+ OPENVIKING_MIN_QUERY_LENGTH: "1",+ OPENVIKING_SCORE_THRESHOLD: "0",+ OPENVIKING_TIMEOUT_MS: "5000",+ OPENVIKING_URL: baseUrl,+ },+ );++ const output = JSON.parse(result.stdout.trim());+ assert.match(output.hookSpecificOutput.additionalContext, /OpenViking memory digest/);+ assert.match(output.hookSpecificOutput.additionalContext, /Launch summary/);+ });++ assert.deepEqual(requests.map((request) => request.path), ["/api/v1/search/recall"]);+ assert.equal(requests[0].body.quotas.events, 2);+ } finally {+ await rm(stateDir, { recursive: true, force: true });+ }+});+test("auto-recall expands configured user in memory search target", async () => {const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-user-target-"));const requests = [];diff --git a/examples/codex-memory-plugin/scripts/capture-utils.mjs b/examples/codex-memory-plugin/scripts/capture-utils.mjsindex 005175bad..0eae451ed 100644--- a/examples/codex-memory-plugin/scripts/capture-utils.mjs+++ b/examples/codex-memory-plugin/scripts/capture-utils.mjs@@ -71,6 +71,17 @@ function stringifyCompact(value, maxChars) {}}+function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}+function blockText(block) {if (!block || typeof block !== "object") return "";if (typeof block.text === "string") return block.text;@@ -114,6 +125,51 @@ function toolPayload(block, kind) {"";}+function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}+function formatToolBlock(block, kind, maxChars) {const name = toolName(block);const payload = toolPayload(block, kind);@@ -192,6 +248,121 @@ export function extractTextFromPayload(payload, options = {}) {return chunks.join("\n\n");}+function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}+export function normalizeCaptureRole(role) {const value = normalizeType(role);if (value === "user") return "user";diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjsindex a13a22e13..724592856 100644--- a/examples/codex-memory-plugin/scripts/config.mjs+++ b/examples/codex-memory-plugin/scripts/config.mjs@@ -9,10 +9,9 @@** Tuning resolution remains env vars > ov.conf codex.* > built-in defaults.*- * Mirrors the credential fields that Codex's streamable-HTTP MCP entry- * receives from the shell wrapper. Aligning the resolver prevents identity- * drift between auto-capture/auto-recall hooks, MCP calls, and child `ov`- * commands launched from inside Codex.+ * The stdio MCP proxy calls the same resolver directly. Aligning the resolver+ * prevents identity drift between auto-capture/auto-recall hooks, MCP calls,+ * and child `ov` commands launched from inside Codex.** File-path env vars:* OPENVIKING_CLI_CONFIG_FILE alternate ovcli.conf path (preferred)@@ -197,6 +196,14 @@ export function loadConfig() {// user-only behavior can set OPENVIKING_CAPTURE_ASSISTANT_TURNS=0 or codex.captureAssistantTurns=false.captureAssistantTurns: envBool("OPENVIKING_CAPTURE_ASSISTANT_TURNS") ?? (cx.captureAssistantTurns !== false),captureLastAssistantOnStop: envBool("OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP") ?? (cx.captureLastAssistantOnStop !== false),+ commitTokenThreshold: Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD,+ num(cx.commitTokenThreshold, 20000),+ ))),+ commitKeepRecentCount: Math.max(0, Math.floor(num(+ process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT,+ num(cx.commitKeepRecentCount, 10),+ ))),autoCommitOnCompact: envBool("OPENVIKING_AUTO_COMMIT_ON_COMPACT") ?? (cx.autoCommitOnCompact !== false),resumeArchiveInject: envBool("OPENVIKING_RESUME_ARCHIVE_INJECT") ?? (cx.resumeArchiveInject !== false),diff --git a/examples/codex-memory-plugin/scripts/debug-log.mjs b/examples/codex-memory-plugin/scripts/debug-log.mjsindex c9c2238fd..3dd132d4d 100644--- a/examples/codex-memory-plugin/scripts/debug-log.mjs+++ b/examples/codex-memory-plugin/scripts/debug-log.mjs@@ -6,9 +6,8 @@* Format: JSON Lines — { ts, hook, stage, data } | { ts, hook, stage, error }.*/-import { appendFileSync, mkdirSync } from "node:fs";-import { dirname } from "node:path";import { loadConfig } from "./config.mjs";+import { createLogger as createSharedLogger } from "./shared/debug-log.mjs";let _cfg;function cfg() {@@ -16,49 +15,6 @@ function cfg() {return _cfg;}-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 || cfg();- if (!c.debug) return { log: noop, logError: noop };-- const logPath = c.debugLogPath;- 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 };+ return createSharedLogger(hookName, overrideCfg || cfg());}diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjsindex 0cf676327..e69721846 100644--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs@@ -5,12 +5,13 @@* These checks guard the `codex plugin marketplace add <owner>/OpenViking`* install path: the catalog must exist, be valid JSON, point at this plugin,* and the plugin's manifest / hooks / mcp wiring must stay consistent with the- * marketplace-install assumptions (native ${PLUGIN_ROOT}, local-default url,+ * marketplace-install assumptions (native ${PLUGIN_ROOT}, stdio MCP proxy,* no stale tool names).*/import test from "node:test";import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";import { existsSync, readFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -22,7 +23,7 @@ const catalogPath = join(repoRoot, ".agents", "plugins", "marketplace.json");const manifestPath = join(pluginDir, ".codex-plugin", "plugin.json");const PLUGIN_NAME = "openviking-memory";-const REAL_MCP_TOOLS = ["search", "store", "read", "list", "grep", "glob", "forget", "add_resource", "health"];+const REAL_MCP_TOOLS = ["recall", "search", "store", "read", "list", "grep", "glob", "forget", "add_resource", "health"];const LEGACY_TOOL_NAMES = ["openviking_recall", "openviking_store", "openviking_forget", "openviking_health"];function readJson(path) {@@ -92,6 +93,21 @@ test("catalog source is local to the marketplace snapshot", () => {}});+test("examples/.agents catalog backs the directory-marketplace install path", () => {+ // The shared installer registers examples/ itself as a local marketplace in+ // dev/archive mode, so a Codex catalog must exist there too and stay+ // consistent with the repo-root one (same marketplace name -> same plugin id+ // openviking-memory@openviking across all install modes).+ const localCatalogPath = join(repoRoot, "examples", ".agents", "plugins", "marketplace.json");+ assert.ok(existsSync(localCatalogPath), `missing catalog at ${localCatalogPath}`);+ const localCatalog = readJson(localCatalogPath);+ const rootCatalog = readJson(catalogPath);+ assert.equal(localCatalog.name, rootCatalog.name, "examples/.agents catalog must keep the same marketplace name as the repo root");+ const entry = localCatalog.plugins.find((p) => p && p.name === PLUGIN_NAME);+ assert.ok(entry, `examples/.agents catalog must contain "${PLUGIN_NAME}"`);+ assert.equal(resolve(repoRoot, "examples", sourcePath(entry.source)), pluginDir, "examples/.agents catalog source must resolve to this plugin directory");+});+test("required plugin files are present", () => {for (const rel of [".codex-plugin/plugin.json", ".mcp.json", "hooks/hooks.json"]) {assert.ok(existsSync(join(pluginDir, rel)), `missing required plugin file: ${rel}`);@@ -104,7 +120,7 @@ test("plugin.json describes the real MCP tools, not the legacy names", () => {for (const legacy of LEGACY_TOOL_NAMES) {assert.ok(!longDesc.includes(legacy), `longDescription must not reference legacy tool name "${legacy}"`);}- for (const tool of ["search", "add_resource", "health"]) {+ for (const tool of ["recall", "search", "add_resource", "health"]) {assert.ok(longDesc.includes(tool), `longDescription should mention real tool "${tool}"`);}});@@ -125,18 +141,21 @@ test("hooks.json uses Codex's native ${PLUGIN_ROOT}, not the legacy placeholder"}});-test(".mcp.json ships a concrete local-default url and omits bearer by default", () => {+test(".mcp.json starts the stdio MCP proxy from the plugin root", () => {const mcp = readJson(join(pluginDir, ".mcp.json"));const server = mcp.mcpServers?.[PLUGIN_NAME];assert.ok(server, `.mcp.json must define mcpServers["${PLUGIN_NAME}"]`);- assert.ok(/^https?:\/\//.test(server.url || ""), `.mcp.json url must be a concrete http(s) endpoint, got "${server.url}"`);- assert.ok(!String(server.url).includes("__OPENVIKING_MCP_URL__"), ".mcp.json must not keep the legacy url placeholder");- // Codex hard-fails MCP startup if bearer_token_env_var points at an unset var,- // so the checked-in (marketplace-default, unauthenticated) file must omit it.- assert.ok(!("bearer_token_env_var" in server), "checked-in .mcp.json should omit bearer_token_env_var for the local-default install");+ assert.equal(server.command, "node");+ assert.deepEqual(server.args, ["servers/mcp-proxy.mjs"]);+ assert.equal(server.cwd, ".");+ assert.equal(server.startup_timeout_sec, 30);+ assert.ok(!("url" in server), ".mcp.json should not keep streamable-HTTP url wiring");+ assert.ok(!("bearer_token_env_var" in server), ".mcp.json should not require Codex env-var bearer wiring");++ execFileSync("node", ["--check", join(pluginDir, "servers", "mcp-proxy.mjs")], { stdio: "pipe" });});test("plugin.json keeps the canonical tool list available for reference", () => {// Sanity: the documented tool set is the one we assert against above.- assert.equal(REAL_MCP_TOOLS.length, 9);+ assert.equal(REAL_MCP_TOOLS.length, 10);});diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.mjsindex e0871f432..fc495c5c0 100644--- a/examples/codex-memory-plugin/scripts/ov-credentials.mjs+++ b/examples/codex-memory-plugin/scripts/ov-credentials.mjs@@ -1,315 +1,14 @@-import { createHash } from "node:crypto";-import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { homedir } from "node:os";import { join, resolve as resolvePath } from "node:path";import { fileURLToPath } from "node:url";+import {+ loadCredentialFiles,+ resolveOpenVikingCredentials,+} from "./shared/credentials.mjs";-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;- }-}--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");-}--function normalizeAuthMode(val) {- const mode = str(val, "").toLowerCase();- return ["trusted", "api_key"].includes(mode) ? mode : "";-}--function resolveAuthMode(creds, env = process.env) {- const cx = creds.ovFile.codex || {};- const server = creds.ovFile.server || {};- return (- normalizeAuthMode(env.OPENVIKING_AUTH_MODE) ||- normalizeAuthMode(cx.authMode) ||- normalizeAuthMode(cx.auth_mode) ||- normalizeAuthMode(server.auth_mode) ||- ((creds.account || creds.user) ? "trusted" : "api_key")- );-}--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 deriveBaseUrl({ env, cliFile, ovFile, useCli }) {- const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));- const cliUrl = str(cliFile.url, "");-- if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");- if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");- if (!useCli && 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 useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));- const cx = files.ovFile.codex || {};- const server = files.ovFile.server || {};-- const baseUrl = deriveBaseUrl({ env, ...files, 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 = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;-- return {- ...files,- credentialSource: useCli ? "ovcli" : (mode === "env" ? "env" : "auto"),- baseUrl,- mcpUrl,- apiKey,- account,- user,- peerId,- hasApiKey: Boolean(apiKey),- };-}--function shellQuote(value) {- return `'${String(value ?? "").replace(/'/g, "'\\''")}'`;-}--function runtimeCliConfigObject(creds) {- const config = {};- if (creds.baseUrl) config.url = creds.baseUrl;- if (creds.apiKey) config.api_key = creds.apiKey;- if (creds.account) config.account = creds.account;- if (creds.user) config.user = creds.user;- if (creds.peerId) config.actor_peer_id = creds.peerId;- return config;-}--function ensureRuntimeCliConfig(creds) {- if (creds.credentialSource === "ovcli") {- return creds.cliPath || creds.cliPathCandidate || "";- }-- const content = JSON.stringify(runtimeCliConfigObject(creds), null, 2) + "\n";- const digest = createHash("sha256").update(content).digest("hex").slice(0, 16);- const dir = join(homedir(), ".openviking", "codex-plugin-state");- const path = join(dir, `runtime-ovcli.${digest}.conf`);-- mkdirSync(dir, { recursive: true, mode: 0o700 });- writeFileSync(path, content, { mode: 0o600 });- try {- chmodSync(path, 0o600);- } catch { /* best effort */ }- return path;-}--function printShellEnv() {- const creds = resolveOpenVikingCredentials();- const cliConfigPath = ensureRuntimeCliConfig(creds);- const assignments = {- OV_RESOLVED_SOURCE: creds.credentialSource,- OV_RESOLVED_URL: creds.baseUrl,- OV_RESOLVED_MCP_URL: creds.mcpUrl,- OV_RESOLVED_API_KEY: creds.apiKey,- OV_RESOLVED_ACCOUNT: creds.account,- OV_RESOLVED_USER: creds.user,- OV_RESOLVED_PEER_ID: creds.peerId,- OV_RESOLVED_CLI_CONFIG_FILE: cliConfigPath,- OV_RESOLVED_HAS_API_KEY: creds.hasApiKey ? "1" : "0",- };- for (const [key, value] of Object.entries(assignments)) {- process.stdout.write(`${key}=${shellQuote(value)}\n`);- }-}--export function syncMcpConfig(file, env = process.env) {- const creds = resolveOpenVikingCredentials(env);- const authMode = resolveAuthMode(creds, env);- const j = JSON.parse(readFileSync(file, "utf-8"));- const s = j.mcpServers && j.mcpServers["openviking-memory"];- if (!s) return false;-- let changed = false;- if (creds.mcpUrl && s.url !== creds.mcpUrl) {- s.url = creds.mcpUrl;- changed = true;- }-- const curBearer = s.bearer_token_env_var || "";- if (creds.hasApiKey && curBearer !== "OPENVIKING_API_KEY") {- s.bearer_token_env_var = "OPENVIKING_API_KEY";- changed = true;- } else if (!creds.hasApiKey && curBearer) {- delete s.bearer_token_env_var;- changed = true;- }-- const headers = s.env_http_headers || {};- const expectedHeaders = {};- if (authMode === "trusted" && creds.account) {- expectedHeaders["X-OpenViking-Account"] = "OPENVIKING_ACCOUNT";- } else if (headers["X-OpenViking-Account"]) {- delete headers["X-OpenViking-Account"];- changed = true;- }- if (authMode === "trusted" && creds.user) {- expectedHeaders["X-OpenViking-User"] = "OPENVIKING_USER";- } else if (headers["X-OpenViking-User"]) {- delete headers["X-OpenViking-User"];- changed = true;- }- // Actor-peer is only mapped when a peer is actually configured. Codex's MCP- // runtime treats unset env vars in env_http_headers as empty-string headers,- // which the OV side then has to disambiguate from "no peer scope". Match- // the bearer_token_env_var pattern: present only when there's something to- // send. The wrapper.sh strips empty OPENVIKING_PEER_ID before exec'ing- // codex, so without this guard the header would silently flip to "".- if (creds.peerId) {- expectedHeaders["X-OpenViking-Actor-Peer"] = "OPENVIKING_PEER_ID";- } else if (headers["X-OpenViking-Actor-Peer"]) {- delete headers["X-OpenViking-Actor-Peer"];- changed = true;- }- for (const [header, envName] of Object.entries(expectedHeaders)) {- if (headers[header] !== envName) {- headers[header] = envName;- changed = true;- }- }- if (s.env_http_headers !== headers) {- s.env_http_headers = headers;- changed = true;- }-- if (changed) {- writeFileSync(file, JSON.stringify(j, null, 2) + "\n");- }- return changed;-}+export { loadCredentialFiles, resolveOpenVikingCredentials } from "./shared/credentials.mjs";function main() {const cmd = process.argv[2] || "";- if (cmd === "shell-env") {- printShellEnv();- return;- }if (cmd === "mcp-url") {process.stdout.write(resolveOpenVikingCredentials().mcpUrl);return;@@ -322,17 +21,7 @@ function main() {process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");return;}- if (cmd === "sync-mcp") {- const file = process.argv[3];- if (!file) {- process.stderr.write("usage: ov-credentials.mjs sync-mcp <mcp.json>\n");- process.exitCode = 2;- return;- }- syncMcpConfig(file);- return;- }- process.stderr.write("usage: ov-credentials.mjs <shell-env|mcp-url|has-api-key|has-peer-id|sync-mcp>\n");+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");process.exitCode = 2;}diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjsindex 1082d1088..f38c04131 100644--- a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs+++ b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs@@ -1,9 +1,9 @@import assert from "node:assert/strict";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";-import { resolveOpenVikingCredentials, syncMcpConfig } from "./ov-credentials.mjs";+import { resolveOpenVikingCredentials } from "./ov-credentials.mjs";async function tempJson(prefix, value) {const dir = await mkdtemp(join(tmpdir(), prefix));@@ -91,175 +91,3 @@ test("ovcli config without api_key does not inherit stale env key", async () =>await rm(dir, { recursive: true, force: true });}});--test("syncMcpConfig with peerId maps actor-peer header", async () => {- const { dir, path } = await tempJson("ov-creds-mcp-peer-", {- url: "https://ov.example.com",- api_key: "cli-key",- actor_peer_id: "peer-a",- });- const mcpPath = join(dir, ".mcp.json");- await writeFile(mcpPath, JSON.stringify({- mcpServers: {- "openviking-memory": {- url: "__OPENVIKING_MCP_URL__",- bearer_token_env_var: "STALE_KEY",- env_http_headers: {},- },- },- }, null, 2) + "\n");-- try {- syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });- const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));- const server = rendered.mcpServers["openviking-memory"];-- assert.equal(server.url, "https://ov.example.com/mcp");- assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");- assert.deepEqual(server.env_http_headers, {- "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID",- });- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("syncMcpConfig without peerId omits actor-peer header (symmetric to bearer)", async () => {- const { dir, path } = await tempJson("ov-creds-mcp-nopeer-", {- url: "https://ov.example.com",- api_key: "cli-key",- });- const mcpPath = join(dir, ".mcp.json");- await writeFile(mcpPath, JSON.stringify({- mcpServers: {- "openviking-memory": {- url: "__OPENVIKING_MCP_URL__",- bearer_token_env_var: "STALE_KEY",- env_http_headers: {},- },- },- }, null, 2) + "\n");-- try {- syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });- const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));- const server = rendered.mcpServers["openviking-memory"];-- assert.equal(server.url, "https://ov.example.com/mcp");- assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");- assert.deepEqual(server.env_http_headers, {});- assert.equal(- Object.prototype.hasOwnProperty.call(server.env_http_headers, "X-OpenViking-Actor-Peer"),- false,- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("syncMcpConfig in trusted mode maps configured identity headers", async () => {- const { dir, path } = await tempJson("ov-creds-mcp-trusted-auth-", {- url: "https://ov.example.com",- api_key: "cli-key",- account: "default",- user: "zeus",- });- const mcpPath = join(dir, ".mcp.json");- await writeFile(mcpPath, JSON.stringify({- mcpServers: {- "openviking-memory": {- url: "__OPENVIKING_MCP_URL__",- bearer_token_env_var: "STALE_KEY",- env_http_headers: {},- },- },- }, null, 2) + "\n");-- try {- syncMcpConfig(mcpPath, {- OPENVIKING_CLI_CONFIG_FILE: path,- OPENVIKING_AUTH_MODE: "trusted",- });- const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));- const server = rendered.mcpServers["openviking-memory"];-- assert.deepEqual(server.env_http_headers, {- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER",- });- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("syncMcpConfig in api_key mode omits trusted identity headers", async () => {- const { dir, path } = await tempJson("ov-creds-mcp-apikey-auth-", {- url: "https://ov.example.com",- api_key: "cli-key",- account: "default",- user: "zeus",- });- const mcpPath = join(dir, ".mcp.json");- await writeFile(mcpPath, JSON.stringify({- mcpServers: {- "openviking-memory": {- url: "__OPENVIKING_MCP_URL__",- bearer_token_env_var: "STALE_KEY",- env_http_headers: {- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER",- },- },- },- }, null, 2) + "\n");-- try {- syncMcpConfig(mcpPath, {- OPENVIKING_CLI_CONFIG_FILE: path,- OPENVIKING_AUTH_MODE: "api_key",- });- const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));- const server = rendered.mcpServers["openviking-memory"];-- assert.equal(server.url, "https://ov.example.com/mcp");- assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");- assert.deepEqual(server.env_http_headers, {});- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("syncMcpConfig drops stale actor-peer header when peer is unset", async () => {- const { dir, path } = await tempJson("ov-creds-mcp-drop-peer-", {- url: "https://ov.example.com",- api_key: "cli-key",- });- const mcpPath = join(dir, ".mcp.json");- await writeFile(mcpPath, JSON.stringify({- mcpServers: {- "openviking-memory": {- url: "__OPENVIKING_MCP_URL__",- bearer_token_env_var: "STALE_KEY",- env_http_headers: {- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER",- "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID",- },- },- },- }, null, 2) + "\n");-- try {- const changed = syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });- assert.equal(changed, true);- const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));- const server = rendered.mcpServers["openviking-memory"];-- assert.equal(- Object.prototype.hasOwnProperty.call(server.env_http_headers, "X-OpenViking-Actor-Peer"),- false,- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjsindex b662f1226..0288a5455 100644--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs@@ -22,10 +22,7 @@import { readFile } from "node:fs/promises";import {- extractTextFromPayload,- isAssistantSideCaptureRole,- normalizeCaptureRole,- shouldCaptureText,+ extractCaptureTurns,} from "./capture-utils.mjs";import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";@@ -80,22 +77,7 @@ function parseTranscript(content) {}function extractTurns(entries) {- const turns = [];- for (const entry of entries) {- if (!entry || typeof entry !== "object") continue;- const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;- const message = payload.message && typeof payload.message === "object" ? payload.message : null;- const rawRole = message?.role || payload.role || payload.type || payload.kind;- const role = normalizeCaptureRole(rawRole);- if (!role) continue;- if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;-- const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });- const decision = shouldCaptureText(rawText, role, cfg);- if (!decision.shouldCapture) continue;- turns.push({ role, text: decision.text });- }- return turns;+ return extractCaptureTurns(entries, cfg);}async function readTranscriptTurns(transcriptPath) {@@ -113,7 +95,9 @@ async function readTranscriptTurns(transcriptPath) {async function appendTurns(ovSessionId, turns) {let appended = 0;for (const turn of turns) {- const body = { role: turn.role, content: turn.text };+ const body = turn.parts?.length+ ? { role: turn.role, parts: turn.parts }+ : { role: turn.role, content: turn.text };if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",diff --git a/examples/codex-memory-plugin/scripts/session-state.mjs b/examples/codex-memory-plugin/scripts/session-state.mjsindex ef04beb64..80bbee08a 100644--- a/examples/codex-memory-plugin/scripts/session-state.mjs+++ b/examples/codex-memory-plugin/scripts/session-state.mjs@@ -13,6 +13,7 @@import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";+import { deriveCodexSessionId } from "./shared/session-model.mjs";const DEFAULT_STATE_DIR = join(homedir(), ".openviking", "codex-plugin-state");@@ -25,7 +26,7 @@ function safeId(codexSessionId) {}export function deriveOvSessionId(codexSessionId) {- return `cx-${safeId(codexSessionId || "unknown")}`;+ return deriveCodexSessionId(codexSessionId);}export function resolveOvSessionId(state) {diff --git a/examples/codex-memory-plugin/scripts/setup.mjs b/examples/codex-memory-plugin/scripts/setup.mjsnew file mode 100644index 000000000..2548237e1--- /dev/null+++ b/examples/codex-memory-plugin/scripts/setup.mjs@@ -0,0 +1,14 @@+#!/usr/bin/env node++/**+ * Standalone ovcli.conf setup for marketplace installs of the Codex plugin:+ *+ * node scripts/setup.mjs+ */++import { runSetupWizard } from "./shared/setup-wizard.mjs";++runSetupWizard().catch((err) => {+ process.stderr.write(`${err?.stack || err}\n`);+ process.exit(1);+});diff --git a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjsnew file mode 100644index 000000000..4ad0314bf--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs@@ -0,0 +1,329 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/codex-memory-plugin/scripts/shared/credentials.mjs b/examples/codex-memory-plugin/scripts/shared/credentials.mjsnew file mode 100644index 000000000..4513d57a9--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/credentials.mjs@@ -0,0 +1,194 @@+// 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;+ }+}++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 deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");+ if (!useCli && 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 useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, 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 = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : (mode === "env" ? "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/examples/codex-memory-plugin/scripts/shared/debug-log.mjs b/examples/codex-memory-plugin/scripts/shared/debug-log.mjsnew file mode 100644index 000000000..73855cf6d--- /dev/null+++ b/examples/codex-memory-plugin/scripts/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/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjsnew file mode 100644index 000000000..f420887c4--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs@@ -0,0 +1,451 @@+// 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,+} = {}) {+ 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 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, message = null) {+ const headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": message?.params?.protocolVersion || 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;+ 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, message),+ 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 (!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 = message.params?.protocolVersion || protocolVersion || DEFAULT_PROTOCOL_VERSION;+ sessionId = "";+ }+ if (message.method === "notifications/initialized") {+ initializedNotification = cloneMessage(message);+ }++ try {+ 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(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/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjsnew file mode 100644index 000000000..754771d22--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs@@ -0,0 +1,439 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Local pending queue for offline resilience.+ *+ * When the OpenViking server is temporarily unreachable, write operations+ * (addMessage, commitSession) serialize their payloads to+ * `~/.openviking/pending/` as JSON files. On the next session-start, the+ * queue is replayed in small batches. This is a session-start-triggered retry+ * path with maxRetries/TTL, not a long-running background worker.+ *+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }+ *+ * Config (env vars):+ * OPENVIKING_PENDING_DIR pending queue directory+ * (default: ~/.openviking/pending)+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup+ * (default: 7)+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start+ * (default: 50)+ */++import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join } from "node:path";+import { homedir } from "node:os";++const DEFAULT_MAX_RETRIES = 3;+const DEFAULT_TTL_DAYS = 7;+const DEFAULT_REPLAY_LIMIT = 50;+const PROCESSING_STALE_MS = 10 * 60 * 1000;+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");++// Pending queue files may contain raw memory payload / transcript content.+// Use restrictive permissions explicitly so we don't depend on umask.+// - dir: 0o700 (owner: rwx; group/other: none)+// - file: 0o600 (owner: rw; group/other: none)+const PENDING_DIR_MODE = 0o700;+const PENDING_FILE_MODE = 0o600;++/**+ * Ensure the pending directory exists with 0o700 permissions. If the+ * directory was created by a previous version of this code (or by hand)+ * with looser permissions, best-effort chmod it on first use.+ */+async function ensurePendingDir(dir) {+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });+ try {+ await chmod(dir, PENDING_DIR_MODE);+ } catch {+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.+ }+}++function getPendingDir() {+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();+}++function getMaxRetries() {+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;+}++function getTTLDays() {+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;+}++function getReplayLimit() {+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;+}++function stableStringify(value) {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;+}++function makeDedupKey(type, sessionId, payload) {+ return createHash("sha256")+ .update(type)+ .update("\n")+ .update(sessionId)+ .update("\n")+ .update(stableStringify(payload))+ .digest("hex");+}++function pendingFilename(dedupKey, retries = 0) {+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;+}++function retryFilename(filename, retries) {+ const bare = filename.replace(/\.(json|processing)$/, "");+ const nextBare = /_\d+$/.test(bare)+ ? bare.replace(/_\d+$/, `_${retries}`)+ : `${bare}_${retries}`;+ return `${nextBare}.json`;+}++function processingFilename(filename) {+ return filename.replace(/\.json$/, ".processing");+}++function pendingFromProcessingFilename(filename) {+ return filename.replace(/\.processing$/, ".json");+}++function isRetryableReplayFailure(res) {+ if (!res || res.ok) return false;+ const status = Number(res.status || 0);+ return !status || status >= 500 || status === 408 || status === 429;+}++async function readEntry(dir, filename) {+ const raw = await readFile(join(dir, filename), "utf-8");+ return JSON.parse(raw);+}++async function findExistingByDedupKey(dir, dedupKey) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return null;+ }++ // Fast path: filenames are `${dedupKey}_${retries}.json` (or+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.+ // Filter on prefix BEFORE opening the file to avoid readFile ++ // JSON.parse on every entry in the directory on every enqueue call —+ // the previous implementation was O(n²) in queue size. Worst case here+ // is O(n) readdir entries, but only the (typically single) prefix+ // match actually gets opened and parsed.+ const prefix = `${dedupKey}_`;++ for (const f of files) {+ if (!f.startsWith(prefix)) continue;+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;+ try {+ const entry = await readEntry(dir, f);+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };+ } catch {+ // Corrupted file - ignore for dedup lookup.+ }+ }+ return null;+}++async function recoverStaleProcessing(dir) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return 0;+ }++ const now = Date.now();+ let recovered = 0;+ for (const f of files) {+ if (!f.endsWith(".processing")) continue;+ const from = join(dir, f);+ try {+ const s = await stat(from);+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;+ const to = join(dir, pendingFromProcessingFilename(f));+ await rename(from, to);+ recovered++;+ } catch {+ // Best effort. A concurrent process may have already handled it.+ }+ }+ return recovered;+}++/**+ * Enqueue a failed operation to local disk.+ *+ * @param {string} type - "addMessage" or "commitSession"+ * @param {string} sessionId - OV session ID+ * @param {object} payload - the data that failed to send+ */+export async function enqueue(type, sessionId, payload) {+ const dir = getPendingDir();+ const now = Date.now();+ const dedupKey = makeDedupKey(type, sessionId, payload);+ const filename = pendingFilename(dedupKey, 0);+ const entry = {+ type,+ sessionId,+ payload,+ createdAt: now,+ retries: 0,+ dedupKey,+ };++ try {+ await ensurePendingDir(dir);+ } catch (err) {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }++ const existing = await findExistingByDedupKey(dir, dedupKey);+ if (existing) {+ return { ok: true, path: existing.filename, deduped: true, dedupKey };+ }++ try {+ await writeFile(join(dir, filename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ return { ok: true, path: filename, dedupKey };+ } catch (err) {+ if (err?.code !== "EEXIST") {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }+ }++ const duplicate = await findExistingByDedupKey(dir, dedupKey);+ if (duplicate) {+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };+ }+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };+}++/**+ * List all pending queue entries.+ * Returns array of { filename, entry } sorted by createdAt ascending.+ */+export async function listPending() {+ const dir = getPendingDir();+ let files;+ try {+ await recoverStaleProcessing(dir);+ files = await readdir(dir);+ } catch {+ return [];+ }++ const entries = [];+ for (const f of files) {+ if (!f.endsWith(".json")) continue;+ try {+ const entry = await readEntry(dir, f);+ entries.push({ filename: f, entry });+ } catch {+ // Corrupted file - skip.+ }+ }++ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));+ return entries;+}++/**+ * Atomically claim a pending file for replay. Only the process that successfully+ * renames the file may send the HTTP replay.+ */+export async function claimForReplay(filename) {+ if (!filename.endsWith(".json")) return null;+ const dir = getPendingDir();+ const claimed = processingFilename(filename);+ try {+ await rename(join(dir, filename), join(dir, claimed));+ return claimed;+ } catch {+ return null;+ }+}++/**+ * Remove a pending entry after successful replay.+ */+export async function dequeue(filename) {+ const dir = getPendingDir();+ try {+ await unlink(join(dir, filename));+ return true;+ } catch {+ return false;+ }+}++/**+ * Increment retry count on a pending entry. Returns false if max retries exceeded.+ */+export async function incrementRetry(filename, entry) {+ const dir = getPendingDir();+ const maxRetries = getMaxRetries();+ entry.retries = (entry.retries || 0) + 1;++ if (entry.retries > maxRetries) {+ try {+ await unlink(join(dir, filename));+ } catch {+ // Best effort.+ }+ return false;+ }++ const newFilename = retryFilename(filename, entry.retries);+ // Atomic write: write to a unique temp file in the same directory, then+ // rename into place. Avoids leaving a half-written JSON if the process+ // crashes mid-write.+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ await rename(join(dir, tmpFilename), join(dir, newFilename));+ await unlink(join(dir, filename)).catch(() => {});+ return true;+ } catch {+ await unlink(join(dir, tmpFilename)).catch(() => {});+ return false;+ }+}++/**+ * Clean up stale entries older than TTL.+ */+export async function cleanStale() {+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;+ const now = Date.now();+ const pending = await listPending();+ let cleaned = 0;++ for (const { filename, entry } of pending) {+ const age = now - (entry.createdAt || 0);+ if (age > ttlMs) {+ await dequeue(filename);+ cleaned++;+ }+ }+ return cleaned;+}++/**+ * Replay pending entries. Call this during session-start when the server is+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so+ * a just-recovered server is not hit with an unbounded replay burst.+ *+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON+ * @param {Function} log - logger function+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}+ */+export async function replayPending(fetchJSON, log) {+ const pending = await listPending();++ if (pending.length === 0) {+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };+ }++ const replayLimit = getReplayLimit();+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });++ let replayed = 0;+ let failed = 0;+ let skipped = 0;+ let deferred = 0;+ let processed = 0;++ for (const { filename, entry } of pending) {+ if (processed >= replayLimit) {+ deferred++;+ continue;+ }++ if ((entry.retries || 0) >= getMaxRetries()) {+ await dequeue(filename);+ skipped++;+ continue;+ }++ const claimedFilename = await claimForReplay(filename);+ if (!claimedFilename) {+ skipped++;+ continue;+ }+ processed++;++ let res;+ try {+ const encodedSid = encodeURIComponent(entry.sessionId);+ if (entry.type === "addMessage") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {+ method: "POST",+ body: JSON.stringify(entry.payload),+ });+ } else if (entry.type === "commitSession") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {+ method: "POST",+ body: JSON.stringify({}),+ });+ } else {+ await dequeue(claimedFilename);+ skipped++;+ continue;+ }+ } catch {+ res = { ok: false };+ }++ if (res?.ok) {+ await dequeue(claimedFilename);+ replayed++;+ } else if (!isRetryableReplayFailure(res)) {+ await dequeue(claimedFilename);+ skipped++;+ } else {+ await incrementRetry(claimedFilename, entry);+ failed++;+ if (entry.type === "addMessage") {+ deferred += Math.max(0, pending.length - processed);+ break;+ }+ }+ }++ const cleaned = await cleanStale();++ log("pending-queue", {+ action: "replay-done",+ replayed,+ failed,+ skipped,+ deferred,+ cleaned,+ });++ return { replayed, failed, skipped, deferred };+}diff --git a/examples/codex-memory-plugin/scripts/shared/session-model.mjs b/examples/codex-memory-plugin/scripts/shared/session-model.mjsnew file mode 100644index 000000000..b6496a113--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/session-model.mjs@@ -0,0 +1,57 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared OpenViking session-id helpers for memory plugin harnesses.+ */++/**+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.+ */+function globToRe(glob) {+ let re = "^";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i];+ if (c === "*") {+ if (glob[i + 1] === "*") { re += ".*"; i++; }+ else re += "[^/]*";+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {+ re += "\\" + c;+ } else {+ re += c;+ }+ }+ re += "$";+ return new RegExp(re);+}++export function isBypassed(cfg, { sessionId, cwd } = {}) {+ if (cfg.bypassSession) return true;+ const patterns = cfg.bypassSessionPatterns || [];+ if (patterns.length === 0) return false;+ const haystacks = [sessionId, cwd].filter(Boolean);+ for (const pat of patterns) {+ const re = globToRe(pat);+ if (haystacks.some((h) => re.test(h))) return true;+ }+ return false;+}++function safeId(value, replacement = "_") {+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);+}++export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {+ if (!prefix || typeof prefix !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");+ }+ if (!sessionId || typeof sessionId !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");+ }+ const base = `${prefix}${sessionId}`;+ if (!suffix) return base;+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");+ return `${base}__${normalized}`;+}++export function deriveCodexSessionId(codexSessionId) {+ return `cx-${safeId(codexSessionId, "_")}`;+}diff --git a/examples/codex-memory-plugin/scripts/shared/setup-wizard.mjs b/examples/codex-memory-plugin/scripts/shared/setup-wizard.mjsnew file mode 100644index 000000000..5108f5f2b--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/setup-wizard.mjs@@ -0,0 +1,111 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.+ *+ * Lets a pure-marketplace install (no installer script) configure the server+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:+ *+ * node <plugin>/scripts/setup.mjs+ *+ * Conventions: show current values, keep existing secrets on empty input,+ * merge-write (never drop unknown fields), back up the previous file, 0600.+ */++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline/promises";+import { loadCredentialFiles } from "./credentials.mjs";++const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";+const LOCAL_URL = "http://127.0.0.1:1933";++function maskSecret(value) {+ const s = String(value || "");+ if (!s) return "(not set)";+ if (s.length <= 8) return "****";+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;+}++function readJsonSafe(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return {};+ }+}++export async function runSetupWizard({+ input = process.stdin,+ output = process.stdout,+ env = process.env,+} = {}) {+ const { cliPath } = loadCredentialFiles(env);+ const current = readJsonSafe(cliPath);+ const rl = createInterface({ input, output });+ const say = (line = "") => output.write(`${line}\n`);++ try {+ say("OpenViking memory plugin setup");+ say(`Config file: ${cliPath}`);+ say("");+ say("Current values:");+ say(` url: ${current.url || "(not set)"}`);+ say(` api_key: ${maskSecret(current.api_key)}`);+ if (current.account) say(` account: ${current.account}`);+ if (current.user) say(` user: ${current.user}`);+ say("");++ const defaultUrl = current.url || LOCAL_URL;+ say("Where do you connect to OpenViking?");+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);+ say(` 3) Custom URL / keep current [${defaultUrl}]`);+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();+ let url = defaultUrl;+ if (mode === "1") {+ url = LOCAL_URL;+ } else if (mode === "2") {+ url = CLOUD_URL;+ } else {+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();+ if (answer) url = answer;+ }++ const keyPrompt = current.api_key+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `+ : "API key (leave empty for unauthenticated local mode): ";+ const keyAnswer = await rl.question(keyPrompt);+ let apiKey = current.api_key || "";+ if (keyAnswer === "-") apiKey = "";+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();+ else if (!current.api_key) apiKey = "";++ const next = { ...current, url, api_key: apiKey };++ say("");+ say("Changes:");+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();+ if (confirm === "n" || confirm === "no") {+ say("Aborted; nothing written.");+ return { written: false, path: cliPath };+ }++ mkdirSync(dirname(cliPath), { recursive: true });+ if (existsSync(cliPath)) {+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);+ }+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(cliPath, 0o600);+ } catch {+ /* best effort on platforms without chmod semantics */+ }+ say(`Written: ${cliPath}`);+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");+ return { written: true, path: cliPath };+ } finally {+ rl.close();+ }+}diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjsnew file mode 100644index 000000000..55460869d--- /dev/null+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs@@ -0,0 +1,68 @@+#!/usr/bin/env node++/**+ * stdio -> streamable-HTTP MCP proxy for the OpenViking Codex plugin.+ *+ * Codex starts this process as a local stdio MCP server. The proxy reads the+ * same OpenViking credential sources as the lifecycle hooks, 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 "../scripts/config.mjs";+import { createLogger } from "../scripts/debug-log.mjs";+import { resolveOpenVikingCredentials } from "../scripts/ov-credentials.mjs";+import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";++export { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.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 creds = resolveOpenVikingCredentials();+ const cfg = loadConfig();+ const mcpUrl = creds.mcpUrl || `${trimSlash(creds.baseUrl)}/mcp`;+ return {+ mcpUrl,+ apiKey: creds.apiKey || "",+ account: creds.account || "",+ user: creds.user || "",+ peerId: creds.peerId || "",+ timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),+ debug: cfg.debug === true,+ debugLogPath: cfg.debugLogPath,+ credentialSource: creds.credentialSource || "auto",+ credentialPath: creds.cliPath || creds.ovPath || "",+ watchedPaths: uniq([+ creds.cliPath,+ creds.ovPath,+ creds.cliPathCandidate,+ 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/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.test.mjsnew file mode 100644index 000000000..23438680b--- /dev/null+++ b/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs@@ -0,0 +1,205 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { Writable } from "node:stream";+import test from "node:test";+import { createOpenVikingMcpProxy } from "./mcp-proxy.mjs";++function jsonRpc(id, result = {}) {+ return { jsonrpc: "2.0", id, result };+}++function sseMessage(obj) {+ return `event: message\r\ndata: ${JSON.stringify(obj)}\r\n\r\n`;+}++async function readBody(req) {+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ return Buffer.concat(chunks).toString("utf-8");+}++async function withServer(handler, fn) {+ const requests = [];+ const server = createServer(async (req, res) => {+ const body = await readBody(req);+ let parsed = null;+ try {+ parsed = body ? JSON.parse(body) : null;+ } catch { /* test handler may inspect raw body */ }+ const entry = { method: req.method, url: req.url, headers: req.headers, body: parsed, rawBody: body };+ requests.push(entry);+ await handler(req, res, entry, requests);+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ const { port } = server.address();+ return await fn({ url: `http://127.0.0.1:${port}/mcp`, requests });+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+}++function makeProxy({ url, configOverrides = {}, stdout } = {}) {+ const out = [];+ const writable = stdout || new Writable({+ write(chunk, _encoding, callback) {+ out.push(chunk.toString("utf-8"));+ callback();+ },+ });+ const proxy = createOpenVikingMcpProxy({+ stdout: writable,+ readConfig: () => ({+ mcpUrl: url,+ apiKey: "test-key",+ account: "default",+ user: "zeus",+ peerId: "peer-a",+ timeoutMs: 5000,+ debug: false,+ debugLogPath: "",+ credentialSource: "test",+ credentialPath: "",+ watchedPaths: [],+ ...configOverrides,+ }),+ loggerFactory: () => ({ log() {}, logError() {} }),+ });+ return {+ proxy,+ out,+ async messages() {+ await new Promise((resolve) => setImmediate(resolve));+ return out.join("").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));+ },+ };+}++test("captures initialize session id and forwards SSE JSON-RPC response", async () => {+ await withServer((_req, res, entry) => {+ assert.equal(entry.method, "POST");+ assert.equal(entry.headers.authorization, "Bearer test-key");+ assert.equal(entry.headers["x-openviking-account"], "default");+ assert.equal(entry.headers["x-openviking-user"], "zeus");+ assert.equal(entry.headers["x-openviking-actor-peer"], "peer-a");+ assert.equal(entry.headers["mcp-protocol-version"], "2025-06-18");+ assert.equal(entry.headers["mcp-session-id"], undefined);+ res.writeHead(200, {+ "content-type": "text/event-stream",+ "mcp-session-id": "sid-1",+ });+ res.end(`: keepalive\r\n${sseMessage(jsonRpc(1, { protocolVersion: "2025-06-18" }))}`);+ }, async ({ url, requests }) => {+ const { proxy, messages } = makeProxy({ url });+ await proxy.handleMessage({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: "2025-06-18" },+ });+ assert.deepEqual(await messages(), [jsonRpc(1, { protocolVersion: "2025-06-18" })]);+ assert.equal(requests.length, 1);+ });+});++test("forwards notifications and writes no stdout for HTTP 202", async () => {+ await withServer((_req, res, entry) => {+ assert.equal(entry.body.method, "notifications/initialized");+ res.writeHead(202, { "content-type": "application/json" });+ res.end("");+ }, async ({ url }) => {+ const { proxy, messages } = makeProxy({ url });+ await proxy.handleMessage({ jsonrpc: "2.0", method: "notifications/initialized" });+ assert.deepEqual(await messages(), []);+ });+});++test("uses independent POST requests for concurrent calls", async () => {+ await withServer(async (_req, res, entry) => {+ const delay = entry.body.id === 1 ? 50 : 5;+ await new Promise((resolve) => setTimeout(resolve, delay));+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify(jsonRpc(entry.body.id, { name: entry.body.method })));+ }, async ({ url, requests }) => {+ const { proxy, messages } = makeProxy({ url });+ await Promise.all([+ proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "tools/list" }),+ proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/call" }),+ ]);+ const ids = (await messages()).map((m) => m.id).sort();+ assert.deepEqual(ids, [1, 2]);+ assert.equal(requests.length, 2);+ });+});++test("reinitializes after 404 and retries the original request once", async () => {+ let call = 0;+ await withServer((_req, res, entry) => {+ call += 1;+ if (call === 1) {+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-old" });+ res.end(JSON.stringify(jsonRpc(1, {})));+ return;+ }+ if (call === 2) {+ assert.equal(entry.headers["mcp-session-id"], "sid-old");+ res.writeHead(404, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: entry.body.id, error: { code: -32000, message: "session missing" } }));+ return;+ }+ if (call === 3) {+ assert.equal(entry.body.method, "initialize");+ assert.match(String(entry.body.id), /^openviking-proxy-reinit-/);+ assert.equal(entry.headers["mcp-session-id"], undefined);+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-new" });+ res.end(JSON.stringify(jsonRpc(entry.body.id, {})));+ return;+ }+ assert.equal(entry.headers["mcp-session-id"], "sid-new");+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify(jsonRpc(2, { ok: true })));+ }, async ({ url, requests }) => {+ const { proxy, messages } = makeProxy({ url });+ await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });+ await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });+ const responses = await messages();+ assert.equal(responses.at(-1).id, 2);+ assert.deepEqual(responses.at(-1).result, { ok: true });+ assert.equal(requests.length, 4);+ });+});++test("maps 401/403 to actionable JSON-RPC auth errors", async () => {+ await withServer((_req, res) => {+ res.writeHead(401, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32001, message: "bad token" } }));+ }, async ({ url }) => {+ const { proxy, messages } = makeProxy({ url });+ await proxy.handleMessage({ jsonrpc: "2.0", id: 7, method: "tools/list" });+ const [msg] = await messages();+ assert.equal(msg.id, 7);+ assert.equal(msg.error.code, -32001);+ assert.match(msg.error.message, /authentication failed/i);+ assert.equal(msg.error.data.status, 401);+ assert.equal(msg.error.data.serverMessage, "bad token");+ });+});++test("DELETEs the upstream MCP session on close", async () => {+ await withServer((_req, res, entry) => {+ if (entry.method === "POST") {+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-close" });+ res.end(JSON.stringify(jsonRpc(1, {})));+ return;+ }+ assert.equal(entry.method, "DELETE");+ assert.equal(entry.headers["mcp-session-id"], "sid-close");+ res.writeHead(204);+ res.end("");+ }, async ({ url, requests }) => {+ const { proxy } = makeProxy({ url });+ await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });+ await proxy.closeSession();+ assert.equal(requests.at(-1).method, "DELETE");+ });+});diff --git a/examples/codex-memory-plugin/setup-helper/install.sh b/examples/codex-memory-plugin/setup-helper/install.shindex 8fe361a9f..5a8d48bda 100755--- a/examples/codex-memory-plugin/setup-helper/install.sh+++ b/examples/codex-memory-plugin/setup-helper/install.sh@@ -11,702 +11,23 @@## Env overrides:# OPENVIKING_HOME, OPENVIKING_REPO_DIR, OPENVIKING_REPO_URL,-# OPENVIKING_REPO_REF / OPENVIKING_REPO_BRANCH, OPENVIKING_CLI_CONFIG_FILE,-# OPENVIKING_CODEX_WRAP_EXTRA (extra launch commands to wrap).+# OPENVIKING_REPO_REF / OPENVIKING_REPO_BRANCH, OPENVIKING_CLI_CONFIG_FILE.# OPENVIKING_REPO_ARCHIVE_URL when set, fetch the source from this zip instead# of git clone (used by the TOS bootstrap for users# who can't reach GitHub). Requires `unzip`.set -euo pipefail-OV_HOME="${OPENVIKING_HOME:-$HOME/.openviking}"-REPO_URL="${OPENVIKING_REPO_URL:-https://github.com/volcengine/OpenViking.git}"-REPO_DIR="${OPENVIKING_REPO_DIR:-$OV_HOME/openviking-repo}"-# Accept both OPENVIKING_REPO_REF and OPENVIKING_REPO_BRANCH so users can-# reuse the same env var across the claude-code and codex installers.-REPO_REF="${OPENVIKING_REPO_REF:-${OPENVIKING_REPO_BRANCH:-main}}"-REPO_ARCHIVE_URL="${OPENVIKING_REPO_ARCHIVE_URL:-}"-# Marks a $REPO_DIR populated from an archive (no .git). Lets re-runs refresh it-# safely while refusing to clobber a git checkout or unrelated user data.-ARCHIVE_MARKER='.openviking-archive-source'-MARKETPLACE_NAME="${OPENVIKING_CODEX_MARKETPLACE_NAME:-openviking-plugins-local}"-MARKETPLACE_ROOT="${OPENVIKING_CODEX_MARKETPLACE_ROOT:-$HOME/.codex/${MARKETPLACE_NAME}-marketplace}"-PLUGIN_NAME="openviking-memory"-PLUGIN_ID="${PLUGIN_NAME}@${MARKETPLACE_NAME}"-CODEX_CONFIG="${CODEX_CONFIG_FILE:-$HOME/.codex/config.toml}"-OVCLI_CONF="${OPENVIKING_CLI_CONFIG_FILE:-$OV_HOME/ovcli.conf}"-DEFAULT_MCP_URL="http://127.0.0.1:1933/mcp"-WRAPPER_MARKER_BEGIN="# >>> openviking-codex-plugin >>>"-WRAPPER_MARKER_END="# <<< openviking-codex-plugin <<<"+SHARED_REL="../../memory-plugin-shared/install.sh"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"+LOCAL_SHARED="$SCRIPT_DIR/$SHARED_REL"-if [ -t 1 ]; then- CYAN=$'\033[0;36m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'; RED=$'\033[0;31m'; BOLD=$'\033[1m'; RESET=$'\033[0m'-else- CYAN=''; GREEN=''; YELLOW=''; RED=''; BOLD=''; RESET=''+if [ -f "$LOCAL_SHARED" ]; then+ exec bash "$LOCAL_SHARED" --harness codex "$@"fi-info() { printf '%s==>%s %s\n' "$GREEN" "$RESET" "$*"; }-warn() { printf '%s!!%s %s\n' "$YELLOW" "$RESET" "$*"; }-err() { printf '%sxx%s %s\n' "$RED" "$RESET" "$*" >&2; }-ask() { printf '%s??%s %s' "$CYAN" "$RESET" "$*"; }-heading() { printf '\n%s%s%s\n' "$BOLD" "$*" "$RESET"; }-# Download a source zip and lay it out at $REPO_DIR (used for the GitHub-free-# TOS install path). The archive is `git archive` output: a single top-level-# OpenViking-<ref>/ dir, identical to a checkout minus .git.-fetch_archive() {- local url="$1" dest="$2" tmp_zip tmp_dir top- command -v unzip >/dev/null 2>&1 || { err 'unzip not found; required to install from an archive.'; exit 1; }- tmp_zip=$(mktemp "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; exit 1; }- tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; rm -f "$tmp_zip"; exit 1; }- info "Downloading source archive"- info " $url"- curl -fsSL -o "$tmp_zip" "$url" || { err "download failed: $url"; rm -rf "$tmp_zip" "$tmp_dir"; exit 1; }- unzip -q "$tmp_zip" -d "$tmp_dir" || { err 'unzip failed (corrupt download?)'; rm -rf "$tmp_zip" "$tmp_dir"; exit 1; }- top=$(find "$tmp_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)- if [ -z "$top" ] || [ ! -d "$top/examples" ]; then- err 'unexpected archive layout (no top-level dir containing examples/)'- rm -rf "$tmp_zip" "$tmp_dir"; exit 1- fi- rm -rf "$dest"- mkdir -p "$(dirname "$dest")"- mv "$top" "$dest"- : > "$dest/$ARCHIVE_MARKER"- rm -rf "$tmp_zip" "$tmp_dir"- info "Source ready at $dest"-}--# ----- 1. Environment check -------heading '1. Environment check'--need() {- command -v "$1" >/dev/null 2>&1 || { err "Missing required command: $1"; exit 1; }-}-need codex-need git-need node--NODE_MAJOR="$(node -p 'Number(process.versions.node.split(".")[0])')"-if [ "$NODE_MAJOR" -lt 22 ]; then- err "Node.js 22+ is required; found $(node --version)."- exit 1-fi-info "codex: $(codex --version 2>/dev/null || echo unknown)"-info "node: $(node --version)"--# ----- 2. OpenViking client config -------heading "2. OpenViking client config ($OVCLI_CONF)"--mkdir -p "$OV_HOME"-chmod 700 "$OV_HOME" 2>/dev/null || true--# Read a field from ovcli.conf via node (codex's stack — no jq dependency).-ov_read_conf() {- [ -f "$OVCLI_CONF" ] || return 0- node -e '- try {- const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));- const v = c[process.argv[2]];- if (v) process.stdout.write(String(v));- } catch {}- ' "$OVCLI_CONF" "$1" 2>/dev/null || true-}--CURRENT_URL="$(ov_read_conf url)"-CURRENT_KEY="$(ov_read_conf api_key)"--if [ -t 0 ]; then- # A url with an empty api_key is a valid unauthenticated config, so offer- # reuse whenever a url exists — don't force the prompt (which would default- # the url back to localhost and clobber a custom server).- if [ -n "$CURRENT_URL" ]; then- info "Existing config found:"- info " url = $CURRENT_URL"- if [ -n "$CURRENT_KEY" ]; then- info " api_key = $(printf '%s' "$CURRENT_KEY" | cut -c1-8)…"- else- info " api_key = (none, unauthenticated)"- fi- ask 'Reuse these values? [Y/n] '- read -r reply || reply=""- case "$reply" in- n|N|no|No|NO) CURRENT_URL=""; CURRENT_KEY="" ;;- esac- fi-- if [ -z "$CURRENT_URL" ]; then- printf '%sChoose where you'\''ll connect to OpenViking:%s\n' "$BOLD" "$RESET"- printf ' 1) Self-hosted / local [default: http://127.0.0.1:1933]\n'- printf ' 2) Volcengine OpenViking Cloud [https://api.vikingdb.cn-beijing.volces.com/openviking]\n'- ask '[1/2, default 1]: '- read -r MODE_INPUT || MODE_INPUT=""- case "$MODE_INPUT" in- 2)- CURRENT_URL="https://api.vikingdb.cn-beijing.volces.com/openviking"- info "Using Volcengine OpenViking Cloud: $CURRENT_URL"- KEY_PROMPT="API key (required for Volcengine OpenViking Cloud): "- ;;- *)- DEFAULT_URL="http://127.0.0.1:1933"- ask "OpenViking server URL [$DEFAULT_URL]: "- read -r URL_INPUT || URL_INPUT=""- CURRENT_URL="${URL_INPUT:-$DEFAULT_URL}"- KEY_PROMPT="API key (leave empty for unauthenticated local mode): "- ;;- esac-- ask "$KEY_PROMPT"- # -s: don't echo (hide secret); fall back if -s unsupported- if read -rs API_INPUT 2>/dev/null; then- printf '\n'- else- read -r API_INPUT || API_INPUT=""- fi- CURRENT_KEY="$API_INPUT"-- if [ -f "$OVCLI_CONF" ]; then- backup="$OVCLI_CONF.bak.$(date +%s)"- cp "$OVCLI_CONF" "$backup"- info "Backed up existing config → $backup"- fi- # Merge url + api_key into any existing config so extra fields (account,- # user, …) the codex wrapper reads are preserved.- node -e '- const fs = require("node:fs");- const [, file, url, key] = process.argv;- let c = {};- try { c = JSON.parse(fs.readFileSync(file, "utf8")); } catch {}- c.url = url;- c.api_key = key;- fs.writeFileSync(file, JSON.stringify(c, null, 2) + "\n");- ' "$OVCLI_CONF" "$CURRENT_URL" "$CURRENT_KEY"- chmod 600 "$OVCLI_CONF"- info "Wrote $OVCLI_CONF (mode 0600)"- else- info "Reusing existing config."- fi-else- if [ -n "$CURRENT_URL" ]; then- info "Non-interactive: using existing $OVCLI_CONF"- else- warn "Non-interactive and no $OVCLI_CONF — proceeding in unauthenticated mode."- warn 'Set OPENVIKING_URL / OPENVIKING_API_KEY, or re-run in a terminal, to configure auth.'- fi-fi--# ----- 3. OpenViking source repository -------heading "3. OpenViking source repository ($REPO_DIR)"--mkdir -p "$(dirname "$REPO_DIR")" "$HOME/.codex"--if [ -n "$REPO_ARCHIVE_URL" ]; then- # Archive mode (GitHub-free): refuse to overwrite anything we didn't create.- if [ -e "$REPO_DIR" ] && [ ! -f "$REPO_DIR/$ARCHIVE_MARKER" ]; then- err "$REPO_DIR exists and was not created from an archive. Move it aside or set OPENVIKING_REPO_DIR."- exit 1- fi- fetch_archive "$REPO_ARCHIVE_URL" "$REPO_DIR"-elif [ ! -e "$REPO_DIR/.git" ]; then- if [ -e "$REPO_DIR" ]; then- err "$REPO_DIR exists but is not a git checkout."- exit 1- fi- info "Cloning $REPO_URL (branch $REPO_REF, depth 1)"- git clone --depth 1 --branch "$REPO_REF" "$REPO_URL" "$REPO_DIR"-else- info "Refreshing existing checkout ($REPO_REF)"- git -C "$REPO_DIR" fetch --depth 1 origin "$REPO_REF"- git -C "$REPO_DIR" reset --hard FETCH_HEAD-fi--PLUGIN_DIR="$REPO_DIR/examples/codex-memory-plugin"-if [ ! -d "$PLUGIN_DIR/.codex-plugin" ]; then- err "Codex plugin not found at $PLUGIN_DIR"- exit 1-fi-CREDS_SCRIPT="$PLUGIN_DIR/scripts/ov-credentials.mjs"-if [ ! -f "$CREDS_SCRIPT" ]; then- err "Credential resolver not found at $CREDS_SCRIPT"- exit 1-fi--PLUGIN_VERSION="$(node -e 'const p=require(process.argv[1]); console.log(p.version || "0.0.0")' "$PLUGIN_DIR/.codex-plugin/plugin.json")"--# ----- 4. Plugin install -------heading "4. Plugin install ($PLUGIN_ID, version $PLUGIN_VERSION)"--# Resolve the OpenViking /mcp endpoint at install time using the same-# credential resolver that hooks and the shell wrapper use. By default the-# active ovcli.conf wins; set OPENVIKING_CREDENTIAL_SOURCE=env to force env.-resolve_mcp_url() {- OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" mcp-url 2>/dev/null || printf '%s' "$DEFAULT_MCP_URL"-}--MCP_URL="$(resolve_mcp_url)"-info "MCP endpoint: $MCP_URL"--mkdir -p "$MARKETPLACE_ROOT/.claude-plugin"-rm -f "$MARKETPLACE_ROOT/$PLUGIN_NAME"-ln -s "$PLUGIN_DIR" "$MARKETPLACE_ROOT/$PLUGIN_NAME"--cat > "$MARKETPLACE_ROOT/.claude-plugin/marketplace.json" <<EOF-{- "name": "$MARKETPLACE_NAME",- "plugins": [- { "name": "$PLUGIN_NAME", "source": "./$PLUGIN_NAME" }- ]-}-EOF--codex plugin marketplace add "$MARKETPLACE_ROOT" >/dev/null 2>&1 || true-info "Marketplace registered: $MARKETPLACE_ROOT"--node - "$CODEX_CONFIG" "$PLUGIN_ID" <<'NODE'-const fs = require("node:fs");-const path = process.argv[2];-const pluginId = process.argv[3];--let text = "";-try {- text = fs.readFileSync(path, "utf8");-} catch {- text = "";-}--function ensureSectionLine(src, section, key, value) {- const lines = src.split(/\n/);- const header = `[${section}]`;- const start = lines.findIndex((line) => line.trim() === header);- if (start === -1) {- const prefix = src.trimEnd();- return `${prefix}${prefix ? "\n\n" : ""}${header}\n${key} = ${value}\n`;- }-- let end = lines.length;- for (let i = start + 1; i < lines.length; i += 1) {- if (/^\s*\[/.test(lines[i])) {- end = i;- break;- }- }-- for (let i = start + 1; i < end; i += 1) {- if (new RegExp(`^\\s*${key}\\s*=`).test(lines[i])) {- lines[i] = `${key} = ${value}`;- return lines.join("\n").replace(/\n*$/, "\n");- }- }-- lines.splice(end, 0, `${key} = ${value}`);- return lines.join("\n").replace(/\n*$/, "\n");-}--function ensurePluginEnabled(src, pluginId) {- const header = `[plugins."${pluginId}"]`;- const lines = src.split(/\n/);- const start = lines.findIndex((line) => line.trim() === header);- if (start === -1) {- const prefix = src.trimEnd();- return `${prefix}${prefix ? "\n\n" : ""}${header}\nenabled = true\n`;- }-- let end = lines.length;- for (let i = start + 1; i < lines.length; i += 1) {- if (/^\s*\[/.test(lines[i])) {- end = i;- break;- }- }-- for (let i = start + 1; i < end; i += 1) {- if (/^\s*enabled\s*=/.test(lines[i])) {- lines[i] = "enabled = true";- return lines.join("\n").replace(/\n*$/, "\n");- }- }-- lines.splice(end, 0, "enabled = true");- return lines.join("\n").replace(/\n*$/, "\n");-}--text = ensurePluginEnabled(text, pluginId);-text = ensureSectionLine(text, "features", "plugin_hooks", "true");--fs.mkdirSync(require("node:path").dirname(path), { recursive: true });-fs.writeFileSync(path, text);-NODE-info "Enabled plugin + features.plugin_hooks in $CODEX_CONFIG"--CACHE_DIR="$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME/$PLUGIN_VERSION"--# Detect whether the user has an OpenViking API key configured anywhere.-# When they don't (typical for a local unauth OV), we render .mcp.json-# WITHOUT bearer_token_env_var, so Codex doesn't see an empty-# OPENVIKING_API_KEY at MCP launch and trigger its OAuth fallback for-# what should be an unauthenticated server.-detect_api_key() {- OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" has-api-key 2>/dev/null || echo "0"-}-HAS_API_KEY="$(detect_api_key)"--# Detect whether a peer id is configured. Older/new local setups may not use-# peer-aware identity yet, so validation must accept both header-present and-# header-absent MCP cache output depending on the actual config.-detect_peer_id() {- OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" has-peer-id 2>/dev/null || echo "0"-}-HAS_PEER_ID="$(detect_peer_id)"--render_plugin_cache() {- mkdir -p "$(dirname "$CACHE_DIR")"- rm -rf "$CACHE_DIR"- cp -R "$PLUGIN_DIR" "$CACHE_DIR"-- # The repo's checked-in hooks.json uses Codex's native ${PLUGIN_ROOT} token,- # which modern Codex injects into hook env AND substitutes inline in hook- # command strings (so a plain `codex plugin marketplace add` install works- # with no rendering). Older Codex (<=0.130) neither injects CODEX_PLUGIN_ROOT- # nor substitutes ${PLUGIN_ROOT}, so for this installer-managed cache copy we- # still render ${PLUGIN_ROOT} to an absolute path — harmless on modern Codex- # (no token left to substitute) and required on old Codex.- local hooks_json="$CACHE_DIR/hooks/hooks.json"- if [ -f "$hooks_json" ]; then- local cache_esc- cache_esc="$(printf '%s' "$CACHE_DIR" | sed -e 's/[\\/&]/\\&/g')"- sed -i.bak -e "s/\${PLUGIN_ROOT}/$cache_esc/g" "$hooks_json"- rm -f "${hooks_json}.bak"- fi-- # Render the OpenViking /mcp URL into the cached .mcp.json (and add the- # bearer_token_env_var line when an API key is configured). The repo's- # checked-in .mcp.json ships a local-default url with NO bearer field, so a- # plain `codex plugin marketplace add` install connects to unauthenticated- # local OV out of the box (Codex hard-fails MCP startup if- # bearer_token_env_var points at an unset/empty var). For this installer- # path, sync-mcp overwrites the url and adds bearer/identity headers based on- # the active ovcli.conf; the cache copy is what Codex actually loads.- local mcp_json="$CACHE_DIR/.mcp.json"- if [ -f "$mcp_json" ]; then- OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" OPENVIKING_MCP_URL="$MCP_URL" \- node "$CREDS_SCRIPT" sync-mcp "$mcp_json"- fi-}--render_plugin_cache-info "Plugin cache: $CACHE_DIR"-info "MCP auth: $([ "$HAS_API_KEY" = "1" ] && echo "Bearer (OPENVIKING_API_KEY)" || echo "none (unauthenticated)")"--# ----- 5. Shell rc wrapper ------#-# The MCP server reads OPENVIKING_API_KEY (and OPENVIKING_ACCOUNT / _USER /-# _PEER_ID) from the process env at codex launch. Install a `codex` shell-# function that pulls these from ovcli.conf at invocation time, so the user-# doesn't have to `export` secrets globally.-#-# Source of truth: setup-helper/wrapper.sh in the plugin checkout. The user's-# shell rc just sources that file directly — no copy step, so any updates land-# via the next `git fetch + reset --hard` the installer runs at the top.--heading '5. Shell rc — codex function wrapper'--WRAPPER_SRC="$PLUGIN_DIR/setup-helper/wrapper.sh"-if [ ! -f "$WRAPPER_SRC" ]; then- err "Wrapper source not found at $WRAPPER_SRC"- exit 1-fi--case "${SHELL:-}" in- */zsh) RC="$HOME/.zshrc" ;;- */bash) RC="$HOME/.bashrc" ;;- *)- if [ -f "$HOME/.zshrc" ]; then RC="$HOME/.zshrc"- elif [ -f "$HOME/.bashrc" ]; then RC="$HOME/.bashrc"- else RC=""; fi- ;;-esac--read_marker_export() {- local key="$1"- [ -n "$RC" ] && [ -f "$RC" ] || return 0- awk -v k="$key" -F"'" '- $0 ~ "^export " k "=" { print $2; exit }- $0 ~ "^" k "=" { print $2; exit }- ' "$RC" 2>/dev/null || true-}--sanitize_marker_value() {- printf '%s' "$1" | tr -d '\r\n' | sed "s/'//g"-}--RECALL_COMPRESS_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS:-$(read_marker_export OPENVIKING_RECALL_COMPRESS)}")"-RECALL_COMPRESS_MODEL_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS_MODEL:-$(read_marker_export OPENVIKING_RECALL_COMPRESS_MODEL)}")"-RECALL_COMPRESS_THINKING_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS_THINKING:-$(read_marker_export OPENVIKING_RECALL_COMPRESS_THINKING)}")"--if [ -t 0 ]; then- info 'Recall compressor profile: re-detect at each Codex SessionStart, cached for later UserPromptSubmit hooks.'- info 'Auto fallback order: configured model/thinking -> gpt-5.3-codex-spark/default -> gpt-5.5/low -> off.'- if [ -n "$RECALL_COMPRESS_SETTING$RECALL_COMPRESS_MODEL_SETTING$RECALL_COMPRESS_THINKING_SETTING" ]; then- info "Current recall compressor env: compress=${RECALL_COMPRESS_SETTING:-auto} model=${RECALL_COMPRESS_MODEL_SETTING:-auto} thinking=${RECALL_COMPRESS_THINKING_SETTING:-auto}"- ask 'Recall compressor [k=keep, a=auto, c=custom, o=off; default k]: '- read -r RECALL_INPUT || RECALL_INPUT=""- RECALL_INPUT="${RECALL_INPUT:-k}"- else- ask 'Recall compressor [a=auto, c=custom, o=off; default a]: '- read -r RECALL_INPUT || RECALL_INPUT=""- RECALL_INPUT="${RECALL_INPUT:-a}"- fi- case "$RECALL_INPUT" in- k|K|keep|KEEP)- :- ;;- o|O|off|OFF)- RECALL_COMPRESS_SETTING="0"- RECALL_COMPRESS_MODEL_SETTING=""- RECALL_COMPRESS_THINKING_SETTING=""- ;;- c|C|custom|CUSTOM)- ask 'Compressor model [gpt-5.3-codex-spark]: '- read -r RECALL_MODEL_INPUT || RECALL_MODEL_INPUT=""- ask 'Compressor thinking/reasoning effort [default]: '- read -r RECALL_THINKING_INPUT || RECALL_THINKING_INPUT=""- RECALL_COMPRESS_SETTING="1"- RECALL_COMPRESS_MODEL_SETTING="$(sanitize_marker_value "${RECALL_MODEL_INPUT:-gpt-5.3-codex-spark}")"- RECALL_COMPRESS_THINKING_SETTING="$(sanitize_marker_value "${RECALL_THINKING_INPUT:-default}")"- ;;- *)- RECALL_COMPRESS_SETTING=""- RECALL_COMPRESS_MODEL_SETTING=""- RECALL_COMPRESS_THINKING_SETTING=""- ;;- esac-fi--# Extra launch commands to wrap besides `codex` — e.g. a custom wrapper-# `codex-custom`, or a multi-word launcher matched on its sub-command.-# Persisted in the rc marker block as OPENVIKING_CODEX_WRAP_EXTRA; the wrapper-# reads it and injects credentials into matching invocations only.-# Seed from this run's env var (automation), else the rc value (re-run). The-# interactive prompt below (TTY only) can override.-WRAP_EXTRA="${OPENVIKING_CODEX_WRAP_EXTRA:-}"-if [ -z "$WRAP_EXTRA" ] && [ -n "$RC" ] && [ -f "$RC" ]; then- WRAP_EXTRA=$(awk -F"'" '/^OPENVIKING_CODEX_WRAP_EXTRA=/{print $2; exit}' "$RC" 2>/dev/null || true)-fi-if [ -z "${OPENVIKING_CODEX_WRAP_EXTRA:-}" ] && [ -t 0 ]; then- info 'Inject OpenViking creds into other launch commands too? e.g. a custom'- info 'wrapper `codex-custom`. A multi-word launcher (a base command plus a'- info 'sub-command) is matched on that sub-command; other uses of the command'- info 'pass through untouched.'- if [ -n "$WRAP_EXTRA" ]; then- info "Currently: $WRAP_EXTRA"- ask 'Commands (;-separated; empty = keep, "-" = clear): '- else- ask 'Commands (;-separated, e.g. "codex-custom"; empty to skip): '- fi- read -r WRAP_INPUT || WRAP_INPUT=""- case "$WRAP_INPUT" in- "") : ;;- -) WRAP_EXTRA="" ;;- *) WRAP_EXTRA="$WRAP_INPUT" ;;- esac-fi-# Normalize each ';'-entry: strip single quotes (keep the rc line safely-# single-quotable), trim, collapse internal whitespace, drop empties.-if [ -n "$WRAP_EXTRA" ]; then- WRAP_EXTRA=$(printf '%s' "$WRAP_EXTRA" | awk -F';' '{- out="";- for (i = 1; i <= NF; i++) {- s = $i; gsub(/\047/, "", s); gsub(/^[ \t]+|[ \t]+$/, "", s); gsub(/[ \t]+/, " ", s);- if (s != "") out = (out == "" ? s : out ";" s);- }- print out;- }')- [ -n "$WRAP_EXTRA" ] && info "Will wrap: $WRAP_EXTRA"-fi--RECALL_ENV_BLOCK=""-if [ -n "$RECALL_COMPRESS_SETTING" ]; then- RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS='$RECALL_COMPRESS_SETTING'-"-fi-if [ -n "$RECALL_COMPRESS_MODEL_SETTING" ]; then- RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS_MODEL='$RECALL_COMPRESS_MODEL_SETTING'-"-fi-if [ -n "$RECALL_COMPRESS_THINKING_SETTING" ]; then- RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS_THINKING='$RECALL_COMPRESS_THINKING_SETTING'-"-fi--# The hook content stays stable across installs (only the absolute path-# matters), so the marker-replacement logic only triggers the legacy cleanup-# path once when upgrading from a pre-rc-split install that inlined the full-# wrapper into the rc.-SOURCE_HOOK="[ -f \"$WRAPPER_SRC\" ] && . \"$WRAPPER_SRC\""-if [ -n "$WRAP_EXTRA" ]; then- SOURCE_BLOCK="$WRAPPER_MARKER_BEGIN-${RECALL_ENV_BLOCK}OPENVIKING_CODEX_WRAP_EXTRA='$WRAP_EXTRA'-$SOURCE_HOOK-$WRAPPER_MARKER_END"-else- SOURCE_BLOCK="$WRAPPER_MARKER_BEGIN-${RECALL_ENV_BLOCK}$SOURCE_HOOK-$WRAPPER_MARKER_END"-fi--if [ -z "$RC" ]; then- warn 'Could not detect a shell rc. Add this snippet to your rc manually:'- warn ''- while IFS= read -r line; do warn " $line"; done <<EOF-$SOURCE_BLOCK-EOF-else- touch "$RC"- if grep -qF "$WRAPPER_MARKER_BEGIN" "$RC"; then- # Strip the existing marker block (whether it's the new one-liner or an- # old inline-wrapper block from a previous version). Both markers must be- # present — refuse the in-place rewrite otherwise.- if grep -qF "$WRAPPER_MARKER_END" "$RC"; then- info "Replacing openviking source hook in $RC"- awk -v b="$WRAPPER_MARKER_BEGIN" -v e="$WRAPPER_MARKER_END" '- $0 == b {skip=1; next}- $0 == e {skip=0; next}- !skip- ' "$RC" > "$RC.tmp" && mv "$RC.tmp" "$RC"- else- warn "$WRAPPER_MARKER_BEGIN found in $RC but $WRAPPER_MARKER_END is missing."- warn 'Refusing to in-place rewrite; appending a fresh source hook instead.'- warn 'Please remove the stray begin marker manually.'- fi- else- info "Appending openviking source hook to $RC"- fi- printf '\n%s\n' "$SOURCE_BLOCK" >> "$RC"-fi--if [ ! -f "$OVCLI_CONF" ] && [ "$HAS_API_KEY" != "1" ]; then- warn "$OVCLI_CONF was not found and no OPENVIKING_API_KEY in env."- warn "Installed in unauthenticated mode targeting $MCP_URL."- warn 'To enable Bearer auth later, create ovcli.conf with an api_key and re-run.'-fi--validate_plugin_install() {- local issues=()- local marketplace_link="$MARKETPLACE_ROOT/$PLUGIN_NAME"- local hooks_json="$CACHE_DIR/hooks/hooks.json"- local mcp_json="$CACHE_DIR/.mcp.json"-- if [ ! -L "$marketplace_link" ] || [ "$(readlink "$marketplace_link" 2>/dev/null || true)" != "$PLUGIN_DIR" ]; then- issues+=("marketplace symlink does not point at $PLUGIN_DIR")- fi- # Codex has printed both `installed, enabled` and `(installed, enabled)`- # across versions; accept either to avoid false-negative install failures.- if ! codex plugin list 2>/dev/null | grep -E -q "${PLUGIN_ID}[[:space:]]+\(?installed, enabled\)?"; then- issues+=("codex plugin list does not show $PLUGIN_ID as installed, enabled")- fi- if [ ! -d "$CACHE_DIR" ]; then- issues+=("plugin cache directory missing: $CACHE_DIR")- fi- if [ ! -f "$hooks_json" ]; then- issues+=("cached hooks.json missing")- else- grep -qF '${PLUGIN_ROOT}' "$hooks_json" && issues+=("cached hooks.json still contains unrendered \${PLUGIN_ROOT}")- grep -q "$CACHE_DIR/scripts/session-start-commit.mjs" "$hooks_json" || issues+=("SessionStart hook path is not rendered to cache dir")- grep -q '"matcher": "clear|startup|resume"' "$hooks_json" || issues+=("SessionStart matcher is not clear|startup|resume")- grep -q '"timeout": 70' "$hooks_json" || issues+=("SessionStart timeout is not 70s")- grep -q '"timeout": 130' "$hooks_json" || issues+=("UserPromptSubmit timeout is not 130s")- fi- if [ ! -f "$mcp_json" ]; then- issues+=("cached .mcp.json missing")- else- grep -q '"url"[[:space:]]*:[[:space:]]*"http' "$mcp_json" || issues+=("cached .mcp.json is missing a concrete http(s) url")- if [ "$HAS_API_KEY" != "1" ] && grep -q "bearer_token_env_var" "$mcp_json"; then- issues+=("cached .mcp.json keeps bearer_token_env_var without configured API key")- fi- if [ "$HAS_PEER_ID" = "1" ] && ! grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json"; then- issues+=("cached .mcp.json is missing X-OpenViking-Actor-Peer header mapping despite configured peer")- fi- if [ "$HAS_PEER_ID" != "1" ] && grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json"; then- issues+=("cached .mcp.json keeps X-OpenViking-Actor-Peer without configured peer")- fi- fi-- for script in \- auto-recall.mjs \- auto-capture.mjs \- pre-compact-capture.mjs \- session-start-commit.mjs \- recall-compressor-profile.mjs \- config.mjs- do- if [ ! -f "$CACHE_DIR/scripts/$script" ]; then- issues+=("cached script missing: scripts/$script")- elif ! node --check "$CACHE_DIR/scripts/$script" >/dev/null 2>&1; then- issues+=("cached script fails node --check: scripts/$script")- fi- done-- if [ "${#issues[@]}" -eq 0 ]; then- return 0- fi- for issue in "${issues[@]}"; do- warn "Install validation: $issue"- done- return 1-}--reset_plugin_cache_setup() {- rm -f "$MARKETPLACE_ROOT/$PLUGIN_NAME"- ln -s "$PLUGIN_DIR" "$MARKETPLACE_ROOT/$PLUGIN_NAME"- codex plugin marketplace add "$MARKETPLACE_ROOT" >/dev/null 2>&1 || true- render_plugin_cache-}--heading '6. Install validation'-if validate_plugin_install; then- info 'Plugin install looks valid.'-else- if [ -t 0 ]; then- ask 'Reset/reinstall plugin symlink/cache and validate again? [Y/n] '- read -r RESET_REPLY || RESET_REPLY=""- case "$RESET_REPLY" in- n|N|no|No|NO)- err 'Plugin install validation failed. Re-run the installer or reset the plugin cache before using Codex.'- exit 1- ;;- *)- info 'Resetting plugin symlink/cache.'- reset_plugin_cache_setup- if validate_plugin_install; then- info 'Plugin install looks valid after reset.'- else- err 'Plugin install validation still failed after reset. Re-run the installer with a clean plugin setup.'- exit 1- fi- ;;- esac- else- err 'Plugin install validation failed in non-interactive mode. Re-run interactively to reset, or clear the plugin cache and reinstall.'- exit 1- fi-fi--# ----- Done -------heading 'Done!'-info "Plugin: $PLUGIN_ID (version $PLUGIN_VERSION)"-info "Config: $OVCLI_CONF"-info "MCP: $MCP_URL ($([ "$HAS_API_KEY" = "1" ] && echo "Bearer auth" || echo "unauthenticated"))"-[ -n "$RC" ] && info "Shell rc: $RC"-printf '\n'-if [ -n "$RC" ]; then- printf '%s%sNext — run this in your shell to pick up the codex() wrapper:%s\n' "$BOLD" "$YELLOW" "$RESET"- printf ' %s%ssource %s%s\n' "$BOLD" "$CYAN" "$RC" "$RESET"- printf ' (or just open a new terminal window)\n\n'-else- printf ' (paste the snippet printed above into your shell rc, then restart your shell)\n\n'-fi-info 'Then:'-info ' codex # start Codex; review /hooks if prompted'+SHARED_URL="${OPENVIKING_SHARED_INSTALL_URL:-https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh}"+tmp="$(mktemp "${TMPDIR:-/tmp}/ov-memory-install.XXXXXX")" || { echo "mktemp failed" >&2; exit 1; }+trap 'rm -f "$tmp"' EXIT+curl -fsSL -o "$tmp" "$SHARED_URL"+exec bash "$tmp" --harness codex "$@"diff --git a/examples/codex-memory-plugin/setup-helper/tos-install.sh b/examples/codex-memory-plugin/setup-helper/tos-install.shindex 4df3125d0..f060ea8cd 100755--- a/examples/codex-memory-plugin/setup-helper/tos-install.sh+++ b/examples/codex-memory-plugin/setup-helper/tos-install.sh@@ -2,28 +2,28 @@## OpenViking Memory Plugin for Codex — TOS bootstrap (China-friendly).#-# For users who can't reach github.com / raw.githubusercontent.com. Pulls both-# the installer and the source archive from Volcengine TOS instead of GitHub,-# then hands off to the standard interactive installer.+# For users who can't reach github.com / raw.githubusercontent.com. Pulls the+# shared installer from Volcengine TOS and runs it with the TOS distribution+# channel preselected (Codex preselected as the harness). Codex installs from+# a TOS-hosted git repo (dumb HTTP) and keeps remote update support.## One-liner:# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)## Env overrides:-# OPENVIKING_TOS_BASE default: https://ovrelease.tos-cn-beijing.volces.com-# OPENVIKING_REPO_ARCHIVE_URL default: $OPENVIKING_TOS_BASE/releases/latest/openviking-source.zip+# OPENVIKING_TOS_BASE default: https://ovrelease.tos-cn-beijing.volces.com# (every install.sh env override applies too.)set -euo pipefailTOS_BASE="${OPENVIKING_TOS_BASE:-https://ovrelease.tos-cn-beijing.volces.com}"TOS_BASE="${TOS_BASE%/}"-export OPENVIKING_REPO_ARCHIVE_URL="${OPENVIKING_REPO_ARCHIVE_URL:-$TOS_BASE/releases/latest/openviking-source.zip}"+export OPENVIKING_TOS_BASE="$TOS_BASE"+export OPENVIKING_SHARED_INSTALL_URL="${OPENVIKING_SHARED_INSTALL_URL:-$TOS_BASE/memory-plugin-shared/install.sh}"# Fetch the real installer to a file (not a pipe) so it keeps the terminal on-# stdin for its interactive prompts. It then sources the repo from the archive-# URL above instead of git clone.+# stdin for its interactive prompts.installer=$(mktemp "${TMPDIR:-/tmp}/ov-codex-install.XXXXXX") || { echo "mktemp failed" >&2; exit 1; }trap 'rm -f "$installer"' EXIT-curl -fsSL -o "$installer" "$TOS_BASE/codex-memory-plugin/install.sh"-bash "$installer"+curl -fsSL -o "$installer" "$OPENVIKING_SHARED_INSTALL_URL"+bash "$installer" --harness codex --dist tos "$@"diff --git a/examples/codex-memory-plugin/setup-helper/wrapper.sh b/examples/codex-memory-plugin/setup-helper/wrapper.shdeleted file mode 100644index 330fa7f00..000000000--- a/examples/codex-memory-plugin/setup-helper/wrapper.sh+++ /dev/null@@ -1,176 +0,0 @@-# OpenViking codex memory plugin shell wrapper.-#-# Sourced from the user's shell rc via a `[ -f ... ] && . ...` hook that the-# installer writes once. Updates land via the installer's `git fetch +-# reset --hard` of the plugin checkout — no need to re-run it to refresh.-#-# This wrapper exists because Codex's MCP runtime reads OPENVIKING_API_KEY-# (and OPENVIKING_ACCOUNT / _USER / _PEER_ID) from the process env at-# codex launch. Rather than asking users to `export` secrets globally, we-# wrap `codex` in a shell function that:-#-# 1. Resolves credentials through the plugin's shared resolver. By default-# active ovcli.conf wins, so `ov config switch` controls hooks, MCP, and-# in-process `ov` commands together. Set OPENVIKING_CREDENTIAL_SOURCE=env-# to force env-var credentials.-#-# 2. Rewrites the cached .mcp.json's URL and bearer_token_env_var to-# match the resolved state. Required because Codex 0.130 hard-fails-# with "Environment variable ... is empty" when bearer_token_env_var-# points at an empty env var; and because the cached URL is otherwise-# install-time-baked, so swapping OPENVIKING_CLI_CONFIG_FILE between-# configs targeting different OV servers would silently keep hitting-# the install-time URL.-#-# 3. Exec's the launcher after stripping stale credential env vars and-# adding only the resolved OPENVIKING_* values (so empty values never-# reach codex as empty strings).-#-# Besides `codex`, any extra launch commands listed in-# $OPENVIKING_CODEX_WRAP_EXTRA (set by the installer in your shell rc, one-# command per ';'-separated entry — e.g. "codex-custom") get the same-# treatment. For a multi-word entry, only invocations whose leading arguments-# match the configured sub-command are wrapped; every other invocation of-# that command passes through untouched.-#-# Targets bash and zsh (the only shells that source ~/.bashrc / ~/.zshrc).--_openviking_codex_plugin_dir() {- local _ov_src- if [ -n "${BASH_SOURCE[0]-}" ]; then- _ov_src="${BASH_SOURCE[0]}"- else- _ov_src="${(%):-%x}"- fi- cd "$(dirname "$_ov_src")/.." >/dev/null 2>&1 && pwd -P-}--# Resolve OpenViking credentials, sync the cached .mcp.json, then exec the-# given launch command with an OPENVIKING_* env prefix. $@ is the command to-# run (e.g. "codex", or a custom launcher like "codex-custom").-_openviking_codex_exec() {- local _ov_conf="${OPENVIKING_CLI_CONFIG_FILE:-$HOME/.openviking/ovcli.conf}"- if ! command -v node >/dev/null 2>&1; then- command "$@"- return- fi-- local _ov_plugin_dir _ov_creds_script- _ov_plugin_dir="$(_openviking_codex_plugin_dir 2>/dev/null || true)"- _ov_creds_script="$_ov_plugin_dir/scripts/ov-credentials.mjs"- if [ ! -f "$_ov_creds_script" ]; then- command "$@"- return- fi-- local _ov_env- _ov_env=$(OPENVIKING_CLI_CONFIG_FILE="$_ov_conf" node "$_ov_creds_script" shell-env 2>/dev/null) || _ov_env=""- if [ -z "$_ov_env" ]; then- command "$@"- return- fi- eval "$_ov_env"-- # Sync cache .mcp.json to current OV connection state: rewrite both the- # URL (so OPENVIKING_CLI_CONFIG_FILE swaps actually change the target)- # and the bearer_token_env_var field (Codex 0.130 hard-fails on empty- # bearer env vars, so the field must be absent in no-auth mode). The- # node script writes only when something actually changes — idempotent- # fast-path so we don't bump file mtime on every codex launch.- local _cache_root _cache_mcp- _cache_root="$HOME/.codex/plugins/cache/openviking-plugins-local/openviking-memory"- if [ -d "$_cache_root" ]; then- while IFS= read -r _cache_mcp; do- [ -f "$_cache_mcp" ] || continue- OPENVIKING_CLI_CONFIG_FILE="${OV_RESOLVED_CLI_CONFIG_FILE:-$_ov_conf}" \- node "$_ov_creds_script" sync-mcp "$_cache_mcp" 2>/dev/null || true- done < <(find "$_cache_root" -mindepth 2 -maxdepth 2 -name .mcp.json -type f 2>/dev/null)- fi-- # Build env-prefix dynamically so empty values are NOT exported as empty- # strings — Codex hard-fails on empty bearer_token_env_var targets.- local -a _env_args=()- [ -n "${OV_RESOLVED_CLI_CONFIG_FILE:-}" ] && _env_args+=("OPENVIKING_CLI_CONFIG_FILE=$OV_RESOLVED_CLI_CONFIG_FILE")- [ -n "${OV_RESOLVED_URL:-}" ] && _env_args+=("OPENVIKING_URL=$OV_RESOLVED_URL")- [ -n "${OV_RESOLVED_API_KEY:-}" ] && _env_args+=("OPENVIKING_API_KEY=$OV_RESOLVED_API_KEY")- [ -n "${OV_RESOLVED_ACCOUNT:-}" ] && _env_args+=("OPENVIKING_ACCOUNT=$OV_RESOLVED_ACCOUNT")- [ -n "${OV_RESOLVED_USER:-}" ] && _env_args+=("OPENVIKING_USER=$OV_RESOLVED_USER")- [ -n "${OV_RESOLVED_PEER_ID:-}" ] && _env_args+=("OPENVIKING_PEER_ID=$OV_RESOLVED_PEER_ID")-- env \- -u OPENVIKING_URL \- -u OPENVIKING_BASE_URL \- -u OPENVIKING_MCP_URL \- -u OPENVIKING_API_KEY \- -u OPENVIKING_BEARER_TOKEN \- -u OPENVIKING_ACCOUNT \- -u OPENVIKING_USER \- -u OPENVIKING_PEER_ID \- "${_env_args[@]}" "$@"-}--# Runtime guard for a wrapped command. $1 = exec helper, $2 = command name,-# $3 = the configured sub-command prefix (empty for single-word commands),-# rest = the actual args. Inject only when the leading args match $3.-_openviking_dispatch() {- local _ov_helper="$1" _ov_cmd="$2" _ov_want="$3"; shift 3- if [ -n "$_ov_want" ]; then- local _ov_rest="$_ov_want" _ov_word _ov_actual _ov_i=1 _ov_ok=1- while [ -n "$_ov_rest" ]; do- case "$_ov_rest" in- *' '*) _ov_word="${_ov_rest%% *}"; _ov_rest="${_ov_rest#* }" ;;- *) _ov_word="$_ov_rest"; _ov_rest="" ;;- esac- eval "_ov_actual=\${$_ov_i-}"- if [ "$_ov_actual" != "$_ov_word" ]; then _ov_ok=0; break; fi- _ov_i=$((_ov_i + 1))- done- if [ "$_ov_ok" != 1 ]; then- command "$_ov_cmd" "$@"- return $?- fi- fi- "$_ov_helper" "$_ov_cmd" "$@"-}--# Define a wrapper function for each ';'-separated entry in $2, routing it-# through the exec helper $1. No subshell (functions must persist in the-# current shell) and no unquoted word splitting (zsh-safe).-_openviking_define_wrappers() {- local _ov_helper="$1" _ov_list="$2" _ov_entry _ov_head _ov_sub- [ -n "$_ov_list" ] || return 0- while [ -n "$_ov_list" ]; do- case "$_ov_list" in- *';'*) _ov_entry="${_ov_list%%;*}"; _ov_list="${_ov_list#*;}" ;;- *) _ov_entry="$_ov_list"; _ov_list="" ;;- esac- _ov_entry="${_ov_entry#"${_ov_entry%%[![:space:]]*}"}"- _ov_entry="${_ov_entry%"${_ov_entry##*[![:space:]]}"}"- [ -n "$_ov_entry" ] || continue- # Allow only word-like characters so a value can never smuggle shell- # metacharacters (" $ ` \ ;, …) into the eval below.- case "$_ov_entry" in- *[!A-Za-z0-9\ ._-]*) continue ;;- esac- _ov_head="${_ov_entry%% *}"- if [ "$_ov_head" = "$_ov_entry" ]; then _ov_sub=""; else _ov_sub="${_ov_entry#* }"; fi- # Reject empty, leading-`-` (would be misread as an option by `alias`- # below and `command` in the dispatcher), or any non-word-char head.- case "$_ov_head" in- ''|-*|*[!A-Za-z0-9_-]*) continue ;;- esac- # A same-named shell alias (e.g. `alias cx=codex`) already routes through- # the base `codex` wrapper once it expands, so it needs no function here —- # and defining one is actively harmful: bash expands the alias mid-eval and- # clobbers the real wrapper, while zsh aborts with a parse error on every- # shell start. Skip alias names; they're covered for free.- if alias "$_ov_head" >/dev/null 2>&1; then- continue- fi- eval "${_ov_head}() { _openviking_dispatch \"$_ov_helper\" \"$_ov_head\" \"$_ov_sub\" \"\$@\"; }"- done-}--codex() { _openviking_codex_exec codex "$@"; }--_openviking_define_wrappers _openviking_codex_exec "${OPENVIKING_CODEX_WRAP_EXTRA:-}"diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shnew file mode 100644index 000000000..39087fd1d--- /dev/null+++ b/examples/memory-plugin-shared/install.sh@@ -0,0 +1,1196 @@+#!/usr/bin/env bash+#+# OpenViking Memory Plugin shared installer for Claude Code and Codex.+#+# One-liner (GitHub):+# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)+# One-liner (TOS mirror, for regions where GitHub is unreachable):+# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos+# Non-interactive:+# bash install.sh --harness claude,codex --dist github --lang en --url http://127.0.0.1:1933 --api-key ''+# Fork / branch verification:+# OPENVIKING_REPO_URL=https://github.com/you/OpenViking.git \+# OPENVIKING_REPO_REF=my-branch bash install.sh --source remote+#+# Distribution channels (--dist, prompted interactively):+# github Remote marketplaces straight from GitHub (default). Claude Code+# uses a synthesized git-subdir manifest; Codex adds the repo as a+# git marketplace. No repo clone, updates via plugin/marketplace+# update commands.+# tos Volcengine TOS mirror, zero GitHub access. Codex adds a TOS-hosted+# git repo (dumb HTTP) and CAN update remotely; Claude Code uses a+# downloaded archive as a local directory marketplace and must+# re-run this installer to update (git dumb HTTP can't serve Claude+# Code's shallow clones).+#+# Source modes (--source, advanced override; auto-detected when omitted):+# remote Remote marketplaces (see --dist). Default.+# archive Download the marketplace archive and register it as a local+# directory marketplace for both harnesses.+# dev Register this checkout's examples/ directory as the marketplace.+# Auto-selected when running from a repo checkout.+#+# Legacy Claude Code (< 2.0, no `claude plugin`) is still supported: the+# installer falls back to `claude mcp add` (stdio proxy) + a hooks merge into+# ~/.claude/settings.json. That path needs a local copy of the plugin, so it+# fetches the source even in remote mode.+#+# Targets bash 3.2+ (macOS /bin/bash) and Linux.++set -euo pipefail++OV_HOME="${OPENVIKING_HOME:-$HOME/.openviking}"+REPO_URL="${OPENVIKING_REPO_URL:-https://github.com/volcengine/OpenViking.git}"+REPO_DIR="${OPENVIKING_REPO_DIR:-$OV_HOME/openviking-repo}"+REPO_REF="${OPENVIKING_REPO_REF:-${OPENVIKING_REPO_BRANCH:-main}}"+REPO_ARCHIVE_URL="${OPENVIKING_REPO_ARCHIVE_URL:-}"+MKT_ARCHIVE_URL="${OPENVIKING_MARKETPLACE_ARCHIVE_URL:-}"+TOS_BASE="${OPENVIKING_TOS_BASE:-https://ovrelease.tos-cn-beijing.volces.com}"+TOS_BASE="${TOS_BASE%/}"+CODEX_TOS_GIT_URL="${OPENVIKING_CODEX_TOS_GIT_URL:-$TOS_BASE/plugins/memory-plugins.git}"+ARCHIVE_MARKER='.openviking-archive-source'+OVCLI_CONF="${OPENVIKING_CLI_CONFIG_FILE:-$OV_HOME/ovcli.conf}"++# One marketplace name everywhere. Claude Code and Codex keep separate+# registries, and within one harness the source modes are alternative channels+# for the same plugin — a single name keeps the plugin id+# (openviking-memory@openviking) and its per-id config stable across modes.+MARKETPLACE_NAME="${OPENVIKING_MARKETPLACE_NAME:-openviking}"+PLUGIN_NAME="openviking-memory"+PLUGIN_ID="${PLUGIN_NAME}@${MARKETPLACE_NAME}"++# Pre-unification names, cleaned up on upgrade.+OLD_MARKETPLACE_NAME='openviking-plugins-local'+CC_OLD_IDS="claude-code-memory-plugin@${OLD_MARKETPLACE_NAME} ${PLUGIN_NAME}@${OLD_MARKETPLACE_NAME}"+CODEX_OLD_ID="${PLUGIN_NAME}@${OLD_MARKETPLACE_NAME}"+CODEX_OLD_MARKETPLACE_ROOT="$HOME/.codex/${OLD_MARKETPLACE_NAME}-marketplace"++CODEX_CONFIG="${CODEX_CONFIG_FILE:-$HOME/.codex/config.toml}"+CC_SETTINGS="$HOME/.claude/settings.json"+CC_KNOWN_MARKETPLACES="$HOME/.claude/plugins/known_marketplaces.json"+MKT_DIR_ARCHIVE="$OV_HOME/memory-plugin-marketplace"+# Directory-shaped on purpose: Claude Code's file-type marketplaces+# mis-derive installLocation and fail `marketplace update` with EISDIR.+CC_REMOTE_MKT_DIR="$OV_HOME/marketplaces/openviking-claude"+CC_REMOTE_MANIFEST="$CC_REMOTE_MKT_DIR/.claude-plugin/marketplace.json"++REQUESTED_HARNESSES=""+SOURCE_ARG=""+DIST_ARG=""+LANG_ARG=""+URL_ARG=""+API_KEY_ARG="__OPENVIKING_UNSET__"+ACCOUNT_ARG="__OPENVIKING_UNSET__"+USER_ARG="__OPENVIKING_UNSET__"+STATUSLINE_ARG="" # "", yes, no+YES=0++CHECKOUT_DIR="" # repo checkout the script itself lives in, when applicable+SRC_ROOT="" # local source root once ensured (checkout or $REPO_DIR)+MKT_DIR="" # directory marketplace root for archive/dev modes+SOURCE_MODE=""+DIST="github"+UI_LANG="en"++if [ -t 1 ]; then+ CYAN=$'\033[0;36m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'; RED=$'\033[0;31m'; BOLD=$'\033[1m'; RESET=$'\033[0m'+else+ CYAN=''; GREEN=''; YELLOW=''; RED=''; BOLD=''; RESET=''+fi+info() { printf '%s==>%s %s\n' "$GREEN" "$RESET" "$*"; }+warn() { printf '%s!!%s %s\n' "$YELLOW" "$RESET" "$*"; }+err() { printf '%sxx%s %s\n' "$RED" "$RESET" "$*" >&2; }+ask() { printf '%s??%s %s' "$CYAN" "$RESET" "$*"; }+heading() { printf '\n%s%s%s\n' "$BOLD" "$*" "$RESET"; }++# t <english> <chinese> — pick the UI language variant.+t() { if [ "$UI_LANG" = "zh" ]; then printf '%s' "$2"; else printf '%s' "$1"; fi; }++# Pure-bash substring test. Never pipe `claude/codex plugin list` into+# `grep -q`: with pipefail, grep exiting early SIGPIPEs the producer and the+# pipeline reads as a miss even though the entry is there.+str_contains() { case "$1" in *"$2"*) return 0 ;; *) return 1 ;; esac; }++usage() {+ cat <<EOF+Usage: install.sh [options]++Options:+ --harness LIST Comma-separated harnesses: claude, codex, or both.+ --dist CHANNEL github (default) | tos (mirror for GitHub-blocked regions).+ --lang LANG en | zh (interactive prompts language; auto-detected).+ --source MODE Advanced: remote | archive | dev (default: auto-detect).+ --url URL OpenViking server base URL.+ --api-key KEY OpenViking API key. Pass '' for unauthenticated local mode.+ --account ID Optional OpenViking account.+ --user ID Optional OpenViking user.+ --statusline Register the Claude Code statusline without asking.+ --no-statusline Skip the statusline prompt.+ --yes, -y Use defaults for prompts when possible.+EOF+}++while [ "$#" -gt 0 ]; do+ case "$1" in+ --harness) REQUESTED_HARNESSES="${2:-}"; shift 2 ;;+ --dist) DIST_ARG="${2:-}"; shift 2 ;;+ --lang) LANG_ARG="${2:-}"; shift 2 ;;+ --source) SOURCE_ARG="${2:-}"; shift 2 ;;+ --url) URL_ARG="${2:-}"; shift 2 ;;+ --api-key) API_KEY_ARG="${2-}"; shift 2 ;;+ --account) ACCOUNT_ARG="${2-}"; shift 2 ;;+ --user) USER_ARG="${2-}"; shift 2 ;;+ --statusline) STATUSLINE_ARG="yes"; shift ;;+ --no-statusline) STATUSLINE_ARG="no"; shift ;;+ --yes|-y) YES=1; shift ;;+ --help|-h) usage; exit 0 ;;+ *) err "Unknown argument: $1"; usage; exit 2 ;;+ esac+done++# Interactive prompts read from /dev/tty (fd 3) so `bash <(curl ...)` and even+# `curl | bash` keep their prompts. No tty -> non-interactive defaults.+# Probe in a subshell first: a failed `exec` redirection would abort the script.+INTERACTIVE=0+if [ "$YES" -ne 1 ] && ( exec 3</dev/tty ) 2>/dev/null; then+ exec 3</dev/tty+ INTERACTIVE=1+fi++read_tty() { # read_tty <varname> [-s]+ local __var="$1" __val=""+ if [ "${2:-}" = "-s" ]; then+ if IFS= read -rs __val <&3 2>/dev/null; then printf '\n'; else __val=""; fi+ else+ IFS= read -r __val <&3 || __val=""+ fi+ eval "$__var=\$__val"+}++# ---------------------------------------------------------------------------+# Single-select TUI menu (arrow keys + digit shortcuts; numbered fallback when+# /dev/tty can't be drawn on; default choice when non-interactive)+# ---------------------------------------------------------------------------++TUI_MENU_CHOICE=0++tui_menu() { # tui_menu <title> <default-index> <option...> -> TUI_MENU_CHOICE+ local title="$1" def="$2"+ shift 2+ local opts+ opts=("$@")+ local n=${#opts[@]} cursor="$def" key rest reply i lines=0+ TUI_MENU_CHOICE="$def"+ [ "$INTERACTIVE" -eq 1 ] || return 0+ if [ ! -w /dev/tty ]; then+ printf '%s%s%s\n' "$BOLD" "$title" "$RESET"+ i=0+ while [ "$i" -lt "$n" ]; do+ printf ' %d) %s\n' $((i + 1)) "${opts[$i]}"+ i=$((i + 1))+ done+ ask "[1-$n, $(t 'default' '默认') $((def + 1))]: "+ read_tty reply+ case "$reply" in+ ''|*[!0-9]*) ;;+ *) [ "$reply" -ge 1 ] && [ "$reply" -le "$n" ] && TUI_MENU_CHOICE=$((reply - 1)) ;;+ esac+ return 0+ fi+ printf '%s%s%s\n' "$BOLD" "$title" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+ trap 'printf "\033[?25h" >/dev/tty' EXIT+ while :; do+ [ "$lines" -gt 0 ] && printf '\033[%dA' "$lines" >/dev/tty+ i=0+ while [ "$i" -lt "$n" ]; do+ if [ "$i" -eq "$cursor" ]; then+ printf '\r\033[K %s>%s (%s•%s) %s\n' "$CYAN" "$RESET" "$GREEN" "$RESET" "${opts[$i]}" >/dev/tty+ else+ printf '\r\033[K ( ) %s\n' "${opts[$i]}" >/dev/tty+ fi+ i=$((i + 1))+ done+ printf '\r\033[K %s%s%s\n' "$CYAN" "$(t '↑/↓ move · 1-9 jump · enter confirm' '↑/↓ 移动 · 数字直选 · 回车确认')" "$RESET" >/dev/tty+ lines=$((n + 1))+ IFS= read -rsn1 key <&3 || key=""+ case "$key" in+ $'\x1b')+ rest=""+ IFS= read -rsn2 -t 1 rest <&3 || rest=""+ case "$rest" in+ '[A') cursor=$(( (cursor + n - 1) % n )) ;;+ '[B') cursor=$(( (cursor + 1) % n )) ;;+ esac+ ;;+ k) cursor=$(( (cursor + n - 1) % n )) ;;+ j) cursor=$(( (cursor + 1) % n )) ;;+ [1-9])+ if [ "$key" -le "$n" ]; then+ cursor=$((key - 1))+ break+ fi+ ;;+ ''|$'\n'|$'\r') break ;;+ q|Q) cursor="$def"; break ;;+ esac+ done+ printf '\033[?25h' >/dev/tty+ trap - EXIT+ TUI_MENU_CHOICE="$cursor"+}++# ---------------------------------------------------------------------------+# UI language+# ---------------------------------------------------------------------------++detect_lang_default() {+ case "${OPENVIKING_LANG:-${LC_ALL:-${LANG:-}}}" in+ zh*|*zh_CN*|*zh_TW*|*zh_HK*) printf 'zh' ;;+ *) printf 'en' ;;+ esac+}++select_language() {+ local detected def+ detected="$(detect_lang_default)"+ if [ -n "$LANG_ARG" ]; then+ UI_LANG="$LANG_ARG"+ elif [ "$INTERACTIVE" -eq 1 ]; then+ def=0+ [ "$detected" = "zh" ] && def=1+ tui_menu "Language / 语言" "$def" "English" "中文"+ if [ "$TUI_MENU_CHOICE" -eq 1 ]; then UI_LANG="zh"; else UI_LANG="en"; fi+ else+ UI_LANG="$detected"+ fi+ case "$UI_LANG" in+ en|zh) ;;+ *) err "Invalid --lang: $UI_LANG (expected en or zh)"; exit 2 ;;+ esac+}++split_harnesses() {+ printf '%s\n' "$1" | tr ',' '\n' | while IFS= read -r h; do+ h=$(printf '%s' "$h" | tr '[:upper:]' '[:lower:]' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')+ [ -n "$h" ] && printf '%s\n' "$h"+ done+}++contains_harness() {+ local want="$1" h+ while IFS= read -r h; do+ [ "$h" = "$want" ] && return 0+ done <<EOF+$(split_harnesses "$SELECTED_HARNESSES")+EOF+ return 1+}++json_get() {+ local file="$1" key="$2"+ [ -f "$file" ] || return 0+ node -e '+ try {+ const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));+ const v = c[process.argv[2]];+ if (v != null && v !== "") process.stdout.write(String(v));+ } catch {}+ ' "$file" "$key" 2>/dev/null || true+}++mask_secret() {+ local s="$1"+ if [ -z "$s" ]; then printf '%s' "$(t '(not set)' '(未设置)')"; return; fi+ if [ "${#s}" -le 8 ]; then printf '****'; return; fi+ printf '%s…%s (%s)' "$(printf '%s' "$s" | cut -c1-4)" "$(printf '%s' "$s" | tail -c 4)" "${#s}"+}++json_merge_ovcli() {+ local file="$1" url="$2" key="$3" account="$4" user="$5"+ node - "$file" "$url" "$key" "$account" "$user" <<'NODE'+const fs = require("node:fs");+const [file, url, apiKey, account, user] = process.argv.slice(2);+let c = {};+try { c = JSON.parse(fs.readFileSync(file, "utf8")); } catch {}+if (url) c.url = url;+if (apiKey !== "__OPENVIKING_KEEP__") c.api_key = apiKey;+if (account !== "__OPENVIKING_KEEP__") {+ if (account) c.account = account; else delete c.account;+}+if (user !== "__OPENVIKING_KEEP__") {+ if (user) c.user = user; else delete c.user;+}+fs.mkdirSync(require("node:path").dirname(file), { recursive: true });+fs.writeFileSync(file, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });+NODE+ chmod 600 "$file" 2>/dev/null || true+}++# ---------------------------------------------------------------------------+# Harness selection (checkbox TUI on a tty, text fallback otherwise)+# ---------------------------------------------------------------------------++HAVE_CLAUDE=0; HAVE_CODEX=0+command -v claude >/dev/null 2>&1 && HAVE_CLAUDE=1+command -v codex >/dev/null 2>&1 && HAVE_CODEX=1++SEL_CLAUDE=0; SEL_CODEX=0; TUI_CURSOR=0; TUI_LINES=0++tui_item_line() { # tui_item_line <index> <selected> <label> <detected>+ local mark='[ ]' cur=' ' note=''+ [ "$2" -eq 1 ] && mark="[${GREEN}x${RESET}]"+ [ "$TUI_CURSOR" -eq "$1" ] && cur="${CYAN}>${RESET} "+ if [ "$4" -eq 1 ]; then+ note=" ${GREEN}$(t '(detected)' '(已检测到)')${RESET}"+ else+ note=" ${YELLOW}$(t '(not found in PATH)' '(PATH 中未找到)')${RESET}"+ fi+ printf '\r\033[K %s%s %s%s\n' "$cur" "$mark" "$3" "$note" >/dev/tty+}++tui_draw() {+ [ "$TUI_LINES" -gt 0 ] && printf '\033[%dA' "$TUI_LINES" >/dev/tty+ tui_item_line 0 "$SEL_CLAUDE" "Claude Code" "$HAVE_CLAUDE"+ tui_item_line 1 "$SEL_CODEX" "Codex" "$HAVE_CODEX"+ printf '\r\033[K %s%s%s\n' "$CYAN" "$(t '↑/↓ move · space toggle · a all · enter confirm' '↑/↓ 移动 · 空格勾选 · a 全选 · 回车确认')" "$RESET" >/dev/tty+ TUI_LINES=3+}++tui_select_harnesses() {+ local key rest+ SEL_CLAUDE=$HAVE_CLAUDE; SEL_CODEX=$HAVE_CODEX+ if [ "$SEL_CLAUDE$SEL_CODEX" = "00" ]; then SEL_CLAUDE=1; SEL_CODEX=1; fi+ printf '%s%s%s\n' "$BOLD" "$(t 'Select the harnesses to install for:' '选择要安装的 harness:')" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+ trap 'printf "\033[?25h" >/dev/tty' EXIT+ TUI_LINES=0+ tui_draw+ while :; do+ IFS= read -rsn1 key <&3 || key=""+ case "$key" in+ $'\x1b')+ rest=""+ IFS= read -rsn2 -t 1 rest <&3 || rest=""+ case "$rest" in+ '[A') TUI_CURSOR=0 ;;+ '[B') TUI_CURSOR=1 ;;+ esac+ ;;+ k) TUI_CURSOR=0 ;;+ j) TUI_CURSOR=1 ;;+ ' ')+ if [ "$TUI_CURSOR" -eq 0 ]; then SEL_CLAUDE=$((1 - SEL_CLAUDE)); else SEL_CODEX=$((1 - SEL_CODEX)); fi+ ;;+ a|A) SEL_CLAUDE=1; SEL_CODEX=1 ;;+ ''|$'\n'|$'\r')+ if [ $((SEL_CLAUDE + SEL_CODEX)) -eq 0 ]; then continue; fi+ break+ ;;+ q|Q) break ;;+ esac+ tui_draw+ done+ printf '\033[?25h' >/dev/tty+ trap - EXIT+ SELECTED_HARNESSES=""+ [ "$SEL_CLAUDE" -eq 1 ] && SELECTED_HARNESSES="claude"+ [ "$SEL_CODEX" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}codex"+ [ -n "$SELECTED_HARNESSES" ] || SELECTED_HARNESSES="claude,codex"+}++select_harnesses() {+ local detected="" reply default+ [ "$HAVE_CLAUDE" -eq 1 ] && detected="claude"+ [ "$HAVE_CODEX" -eq 1 ] && detected="${detected:+$detected,}codex"++ if [ -n "$REQUESTED_HARNESSES" ]; then+ SELECTED_HARNESSES="$REQUESTED_HARNESSES"+ return+ fi+ default="${detected:-claude,codex}"+ if [ "$INTERACTIVE" -eq 1 ] && [ -w /dev/tty ]; then+ tui_select_harnesses+ elif [ "$INTERACTIVE" -eq 1 ]; then+ info "$(t 'Detected harnesses:' '检测到的 harness:') ${detected:-none}"+ ask "$(t 'Install harnesses' '要安装的 harness') [${default}]: "+ read_tty reply+ SELECTED_HARNESSES="${reply:-$default}"+ else+ SELECTED_HARNESSES="$default"+ fi+}++validate_selected_harnesses() {+ local h bad=0+ while IFS= read -r h; do+ case "$h" in+ claude|codex) ;;+ *) err "Unsupported harness: $h"; bad=1 ;;+ esac+ done <<EOF+$(split_harnesses "$SELECTED_HARNESSES")+EOF+ [ "$bad" -eq 0 ] || exit 2+}++# ---------------------------------------------------------------------------+# Distribution channel (github vs tos mirror)+# ---------------------------------------------------------------------------++select_dist() {+ if [ -n "$DIST_ARG" ]; then+ DIST="$DIST_ARG"+ elif [ "$INTERACTIVE" -eq 1 ] && [ -z "$SOURCE_ARG" ]; then+ if [ -n "$CHECKOUT_DIR" ]; then+ tui_menu "$(t 'Install source' '安装源模式')" 2 \+ "GitHub $(t '(remote marketplace; supports remote updates)' '(远程 marketplace;支持远程更新)')" \+ "$(t 'Volcengine TOS mirror (use when GitHub is unreachable)' '火山引擎 TOS 镜像(无法访问 GitHub 时使用)')" \+ "$(t 'This checkout (development; edits take effect live)' '当前 checkout(开发模式;改动即时生效)')"+ case "$TUI_MENU_CHOICE" in+ 0) DIST="github" ;;+ 1) DIST="tos" ;;+ *) SOURCE_ARG="dev" ;;+ esac+ else+ tui_menu "$(t 'Install source' '安装源模式')" 0 \+ "GitHub $(t '(default; supports remote updates)' '(默认;支持远程更新)')" \+ "$(t 'Volcengine TOS mirror (use when GitHub is unreachable)' '火山引擎 TOS 镜像(无法访问 GitHub 时使用)')"+ if [ "$TUI_MENU_CHOICE" -eq 1 ]; then DIST="tos"; else DIST="github"; fi+ fi+ fi+ case "$DIST" in+ github|tos) ;;+ *) err "Invalid --dist: $DIST (expected github or tos)"; exit 2 ;;+ esac+}++# ---------------------------------------------------------------------------+# ovcli.conf wizard+# ---------------------------------------------------------------------------++prompt_connection() { # sets WIZ_URL / WIZ_KEY (WIZ_KEY may stay __OPENVIKING_KEEP__)+ local current_url="$1" current_key="$2" url_input reply+ tui_menu "$(t 'Where do you connect to OpenViking?' '连接到哪个 OpenViking 服务?')" 2 \+ "$(t 'Self-hosted / local' '自建 / 本地') [http://127.0.0.1:1933]" \+ "$(t 'Volcengine OpenViking Cloud' '火山引擎 OpenViking 云服务') [api.vikingdb.cn-beijing.volces.com]" \+ "$(t 'Custom URL / keep current' '自定义 URL / 保持当前') [${current_url:-http://127.0.0.1:1933}]"+ case "$TUI_MENU_CHOICE" in+ 0) WIZ_URL="http://127.0.0.1:1933" ;;+ 1) WIZ_URL="https://api.vikingdb.cn-beijing.volces.com/openviking" ;;+ *)+ ask "$(t 'Server URL' '服务地址') [${current_url:-http://127.0.0.1:1933}]: "+ read_tty url_input+ WIZ_URL="${url_input:-${current_url:-http://127.0.0.1:1933}}"+ ;;+ esac++ if [ -n "$current_key" ]; then+ ask "$(t "API key [enter = keep $(mask_secret "$current_key"), '-' = clear]: " "API key [回车 = 保留 $(mask_secret "$current_key"),输入 '-' 清空]: ")"+ else+ ask "$(t 'API key (leave empty for unauthenticated local mode): ' 'API key(本地免鉴权模式请直接回车): ')"+ fi+ read_tty reply -s+ if [ "$reply" = "-" ]; then+ WIZ_KEY=""+ elif [ -n "$reply" ]; then+ WIZ_KEY="$reply"+ else+ WIZ_KEY="__OPENVIKING_KEEP__"+ [ -z "$current_key" ] && WIZ_KEY=""+ fi+}++configure_ovcli() {+ local current_url current_key current_account current_user url key account user reply+ heading "$(t '2. OpenViking credentials' '2. OpenViking 凭据配置') ($OVCLI_CONF)"+ mkdir -p "$OV_HOME"+ chmod 700 "$OV_HOME" 2>/dev/null || true++ current_url="$(json_get "$OVCLI_CONF" url)"+ current_key="$(json_get "$OVCLI_CONF" api_key)"+ current_account="$(json_get "$OVCLI_CONF" account)"+ current_user="$(json_get "$OVCLI_CONF" user)"++ url="$current_url"+ key="__OPENVIKING_KEEP__"+ account="__OPENVIKING_KEEP__"+ user="__OPENVIKING_KEEP__"++ [ -n "$URL_ARG" ] && url="$URL_ARG"+ [ "$API_KEY_ARG" != "__OPENVIKING_UNSET__" ] && key="$API_KEY_ARG"+ [ "$ACCOUNT_ARG" != "__OPENVIKING_UNSET__" ] && account="$ACCOUNT_ARG"+ [ "$USER_ARG" != "__OPENVIKING_UNSET__" ] && user="$USER_ARG"++ # Show what is configured today, then offer to keep or reconfigure.+ if [ -n "$current_url" ] || [ -n "$current_key" ]; then+ info "$(t 'Current config:' '当前配置:')"+ info " url: ${current_url:-$(t '(not set)' '(未设置)')}"+ info " api_key: $(mask_secret "$current_key")"+ [ -n "$current_account" ] && info " account: $current_account"+ [ -n "$current_user" ] && info " user: $current_user"+ else+ info "$(t 'No existing config found.' '未找到已有配置。')"+ fi++ if [ "$INTERACTIVE" -eq 1 ] && [ -z "$URL_ARG" ] && [ "$API_KEY_ARG" = "__OPENVIKING_UNSET__" ]; then+ if [ -n "$current_url" ] || [ -n "$current_key" ]; then+ tui_menu "$(t 'Existing credentials found — what next?' '检测到已有凭据——如何处理?')" 0 \+ "$(t 'Keep current credentials' '沿用当前凭据')" \+ "$(t 'Reconfigure (server URL / API key)' '重新配置(服务地址 / API key)')"+ if [ "$TUI_MENU_CHOICE" -eq 1 ]; then+ prompt_connection "$current_url" "$current_key"+ url="$WIZ_URL"; key="$WIZ_KEY"+ fi+ else+ prompt_connection "" ""+ url="$WIZ_URL"; key="$WIZ_KEY"+ fi+ fi+ [ -z "$url" ] && url="${current_url:-http://127.0.0.1:1933}"++ if [ -f "$OVCLI_CONF" ]; then+ cp "$OVCLI_CONF" "$OVCLI_CONF.bak.$(date +%s)"+ fi+ json_merge_ovcli "$OVCLI_CONF" "$url" "$key" "$account" "$user"+ if [ "$url" != "$current_url" ] || { [ "$key" != "__OPENVIKING_KEEP__" ] && [ "$key" != "$current_key" ]; }; then+ info "$(t 'Updated:' '已更新:') url: ${current_url:-—} -> $url"+ fi+ info "$(t 'Credentials ready:' '凭据已就绪:') $OVCLI_CONF"+ info "$(t 'Reconfigure later: node <plugin>/scripts/setup.mjs (or re-run this installer)' '之后可用 node <插件目录>/scripts/setup.mjs 或重跑本脚本重新配置')"+}++# ---------------------------------------------------------------------------+# Source acquisition+# ---------------------------------------------------------------------------++fetch_archive() { # fetch_archive <url> <dest> <required-subpath>+ local url="$1" dest="$2" need="$3" tmp_zip tmp_dir top+ command -v unzip >/dev/null 2>&1 || { err 'unzip not found; required to install from an archive.'; exit 1; }+ tmp_zip=$(mktemp "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; exit 1; }+ tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/ov-src.XXXXXX") || { err 'mktemp failed'; rm -f "$tmp_zip"; exit 1; }+ info "$(t 'Downloading archive' '下载归档')"+ info " $url"+ curl -fsSL -o "$tmp_zip" "$url" || { rm -rf "$tmp_zip" "$tmp_dir"; return 1; }+ unzip -q "$tmp_zip" -d "$tmp_dir" || { err 'unzip failed'; rm -rf "$tmp_zip" "$tmp_dir"; exit 1; }+ top=$(find "$tmp_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)+ if [ -n "$top" ] && [ ! -e "$top/$need" ] && [ -e "$tmp_dir/$need" ]; then+ top="$tmp_dir"+ fi+ if [ -z "$top" ] || [ ! -e "$top/$need" ]; then+ err "unexpected archive layout (missing $need)"+ rm -rf "$tmp_zip" "$tmp_dir"; exit 1+ fi+ if [ -e "$dest" ] && [ ! -f "$dest/$ARCHIVE_MARKER" ] && [ ! -d "$dest/.git" ]; then+ err "$dest exists and is not an OpenViking checkout/archive."+ rm -rf "$tmp_zip" "$tmp_dir"; exit 1+ fi+ rm -rf "$dest"+ mkdir -p "$(dirname "$dest")"+ if [ "$top" = "$tmp_dir" ]; then+ mkdir -p "$dest"+ ( shopt -s dotglob; mv "$tmp_dir"/* "$dest"/ )+ else+ mv "$top" "$dest"+ fi+ : > "$dest/$ARCHIVE_MARKER"+ rm -rf "$tmp_zip" "$tmp_dir"+}++resolve_self_checkout() {+ local src dir+ src="${BASH_SOURCE[0]}"+ dir="$(cd "$(dirname "$src")" >/dev/null 2>&1 && pwd -P)" || return 0+ if [ -d "$dir/../../.git" ] && [ -d "$dir/../claude-code-memory-plugin" ]; then+ CHECKOUT_DIR="$(cd "$dir/../.." >/dev/null 2>&1 && pwd -P)"+ fi+}++resolve_source_mode() {+ if [ -n "$SOURCE_ARG" ]; then+ SOURCE_MODE="$SOURCE_ARG"+ elif [ "$DIST" = "tos" ]; then+ SOURCE_MODE="archive"+ elif [ -n "$MKT_ARCHIVE_URL" ] || [ -n "$REPO_ARCHIVE_URL" ]; then+ SOURCE_MODE="archive"+ elif [ -n "$CHECKOUT_DIR" ]; then+ SOURCE_MODE="dev"+ else+ SOURCE_MODE="remote"+ fi+ case "$SOURCE_MODE" in+ remote|archive|dev) ;;+ *) err "Invalid --source: $SOURCE_MODE (expected remote, archive, or dev)"; exit 2 ;;+ esac+ info "$(t 'Source mode:' '安装源模式:') $SOURCE_MODE ($(t 'channel' '渠道'): $DIST)"+ if [ "$SOURCE_MODE" = "archive" ] && [ "$HAVE_CLAUDE" -eq 1 ] && contains_harness claude; then+ warn "$(t 'TOS/archive installs cannot auto-update Claude Code (local directory marketplace); re-run this installer to update. Codex keeps remote updates via its TOS git marketplace.' 'TOS/归档方式安装的 Claude Code 插件无法自动更新(本地目录 marketplace),更新请重跑本安装脚本;Codex 走 TOS git marketplace 仍可远程更新。')"+ fi+}++# Ensure a local copy of the plugin sources exists (legacy Claude Code and the+# statusline need real files on disk even in remote mode).+ensure_checkout() {+ [ -n "$SRC_ROOT" ] && return 0+ if [ -n "$CHECKOUT_DIR" ]; then+ SRC_ROOT="$CHECKOUT_DIR"+ info "$(t 'Using current checkout:' '使用当前 checkout:') $SRC_ROOT"+ return 0+ fi+ if [ "$SOURCE_MODE" = "archive" ] && [ -n "$MKT_DIR" ]; then+ # The marketplace archive already contains the plugin sources.+ SRC_ROOT=""+ return 1+ fi+ if [ -n "$REPO_ARCHIVE_URL" ]; then+ fetch_archive "$REPO_ARCHIVE_URL" "$REPO_DIR" "examples" || { err "source archive download failed"; exit 1; }+ elif [ -d "$REPO_DIR/.git" ]; then+ info "$(t 'Refreshing checkout' '刷新 checkout') ($REPO_REF)"+ git -C "$REPO_DIR" fetch --depth 1 origin "$REPO_REF"+ git -C "$REPO_DIR" reset --hard FETCH_HEAD+ else+ if [ -e "$REPO_DIR" ] && [ ! -f "$REPO_DIR/$ARCHIVE_MARKER" ]; then+ err "$REPO_DIR exists but is not a git checkout."+ exit 1+ fi+ command -v git >/dev/null 2>&1 || { err "git not found (needed to fetch sources)."; exit 1; }+ info "$(t 'Cloning' '克隆') $REPO_URL (ref $REPO_REF)"+ rm -rf "$REPO_DIR"+ mkdir -p "$(dirname "$REPO_DIR")"+ git clone --depth 1 --branch "$REPO_REF" "$REPO_URL" "$REPO_DIR"+ fi+ SRC_ROOT="$REPO_DIR"+}++# Locate the plugin dir with real files on disk (for legacy / statusline).+# Callers capture stdout ($(...)), so any progress output from the fetch has+# to stay on stderr or it corrupts the captured path.+plugin_dir_on_disk() { # plugin_dir_on_disk <plugin-subdir>+ if [ -n "$MKT_DIR" ] && [ -d "$MKT_DIR/$1" ]; then+ printf '%s' "$MKT_DIR/$1"+ return 0+ fi+ ensure_checkout 1>&2 || true+ if [ -n "$SRC_ROOT" ] && [ -d "$SRC_ROOT/examples/$1" ]; then+ printf '%s' "$SRC_ROOT/examples/$1"+ return 0+ fi+ return 1+}++prepare_marketplace_dir() {+ case "$SOURCE_MODE" in+ dev)+ MKT_DIR="$CHECKOUT_DIR/examples"+ ;;+ archive)+ heading "$(t '3. Marketplace archive' '3. Marketplace 归档')"+ [ -z "$MKT_ARCHIVE_URL" ] && [ "$DIST" = "tos" ] && MKT_ARCHIVE_URL="$TOS_BASE/releases/latest/memory-plugin-marketplace.zip"+ [ -z "$REPO_ARCHIVE_URL" ] && [ "$DIST" = "tos" ] && REPO_ARCHIVE_URL="$TOS_BASE/releases/latest/openviking-source.zip"+ if [ -n "$MKT_ARCHIVE_URL" ] && fetch_archive "$MKT_ARCHIVE_URL" "$MKT_DIR_ARCHIVE" ".claude-plugin/marketplace.json"; then+ MKT_DIR="$MKT_DIR_ARCHIVE"+ elif [ -n "$REPO_ARCHIVE_URL" ]; then+ [ -n "$MKT_ARCHIVE_URL" ] && warn "$(t 'marketplace archive unavailable; falling back to the full source archive' 'marketplace 归档不可用,回退到完整源码归档')"+ fetch_archive "$REPO_ARCHIVE_URL" "$REPO_DIR" "examples" || { err "source archive download failed"; exit 1; }+ SRC_ROOT="$REPO_DIR"+ MKT_DIR="$REPO_DIR/examples"+ else+ err "archive mode needs OPENVIKING_MARKETPLACE_ARCHIVE_URL or OPENVIKING_REPO_ARCHIVE_URL"+ exit 1+ fi+ ;;+ esac+ if [ -n "$MKT_DIR" ] && [ ! -f "$MKT_DIR/.claude-plugin/marketplace.json" ]; then+ err "marketplace dir $MKT_DIR is missing .claude-plugin/marketplace.json"+ exit 1+ fi+}++# ---------------------------------------------------------------------------+# Legacy wrapper cleanup (pre-stdio installs)+# ---------------------------------------------------------------------------++strip_rc_block() {+ local rc="$1" begin="$2" end="$3"+ [ -n "$rc" ] && [ -f "$rc" ] || return 0+ grep -qF "$begin" "$rc" || return 0+ if ! grep -qF "$end" "$rc"; then+ warn "Found $begin in $rc but missing end marker; leaving it untouched."+ return 0+ fi+ awk -v b="$begin" -v e="$end" '+ $0 == b {skip=1; next}+ $0 == e {skip=0; next}+ !skip+ ' "$rc" > "$rc.tmp" && mv "$rc.tmp" "$rc"+ info "$(t 'Removed legacy rc block from' '已移除旧的 rc 注入块:') $rc"+}++cleanup_rc_wrappers() {+ local rc+ for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do+ strip_rc_block "$rc" '# >>> openviking claude-code memory plugin >>>' '# <<< openviking claude-code memory plugin <<<'+ strip_rc_block "$rc" '# >>> openviking-codex-plugin >>>' '# <<< openviking-codex-plugin <<<'+ done+}++# ---------------------------------------------------------------------------+# Claude Code+# ---------------------------------------------------------------------------++has_plugin_subcommand() {+ command claude plugin --help >/dev/null 2>&1+}++# Current registered source string for our Claude marketplace ("" if absent).+claude_marketplace_current_source() {+ node -e '+ try {+ const m = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))[process.argv[2]];+ const s = m && m.source ? m.source : null;+ if (s) process.stdout.write(String(s.path || s.repo || s.url || ""));+ } catch {}+ ' "$CC_KNOWN_MARKETPLACES" "$MARKETPLACE_NAME" 2>/dev/null || true+}++migrate_claude_legacy_marketplace() {+ local id plugin_list marketplace_list+ plugin_list="$(command claude plugin list 2>/dev/null || true)"+ for id in $CC_OLD_IDS; do+ if str_contains "$plugin_list" "$id"; then+ info "$(t 'Removing pre-unification plugin install' '移除旧命名的插件安装') ($id)"+ command claude plugin uninstall "$id" >/dev/null 2>&1 || true+ fi+ done+ marketplace_list="$(command claude plugin marketplace list 2>/dev/null || true)"+ if str_contains "$marketplace_list" "$OLD_MARKETPLACE_NAME"; then+ info "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"+ command claude plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+}++write_claude_remote_manifest() {+ mkdir -p "$(dirname "$CC_REMOTE_MANIFEST")"+ # Pre-directory-layout leftover (a bare .json registered as a file-type+ # marketplace); superseded by the directory registration below.+ rm -f "$OV_HOME/marketplaces/openviking-claude.json"+ node - "$CC_REMOTE_MANIFEST" "$MARKETPLACE_NAME" "$REPO_URL" "$REPO_REF" <<'NODE'+const fs = require("node:fs");+const [file, name, url, ref] = process.argv.slice(2);+const manifest = {+ name,+ description: `OpenViking plugins for Claude Code (remote: ${url} @ ${ref}).`,+ owner: { name: "OpenViking" },+ plugins: [+ {+ name: "openviking-memory",+ description: "Long-term semantic memory for Claude Code, powered by OpenViking",+ source: { source: "git-subdir", url, path: "examples/claude-code-memory-plugin", ref },+ category: "productivity",+ },+ ],+};+fs.writeFileSync(file, JSON.stringify(manifest, null, 2) + "\n");+NODE+}++claude_marketplace_sync() { # claude_marketplace_sync <add-target> <expected-source>+ local target="$1" needle="$2" current+ current="$(claude_marketplace_current_source)"+ if [ -n "$current" ] && [ "$current" = "$needle" ]; then+ info "claude plugin marketplace update ($MARKETPLACE_NAME)"+ command claude plugin marketplace update "$MARKETPLACE_NAME" || \+ warn 'marketplace update returned non-zero — continuing'+ return 0+ fi+ if [ -n "$current" ]; then+ info "$(t 'Marketplace points elsewhere; re-registering' 'marketplace 指向其他来源,重新注册') ($current)"+ command claude plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ command claude plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+ info "claude plugin marketplace add ($target)"+ command claude plugin marketplace add "$target" || {+ err 'claude plugin marketplace add failed'+ return 1+ }+}++install_claude_modern() {+ case "$SOURCE_MODE" in+ remote)+ write_claude_remote_manifest+ claude_marketplace_sync "$CC_REMOTE_MKT_DIR" "$CC_REMOTE_MKT_DIR" || return 1+ ;;+ archive|dev)+ claude_marketplace_sync "$MKT_DIR" "$MKT_DIR" || return 1+ ;;+ esac+ if str_contains "$(command claude plugin list 2>/dev/null || true)" "$PLUGIN_ID"; then+ info "claude plugin update ($PLUGIN_ID)"+ command claude plugin update "$PLUGIN_ID" || warn 'claude plugin update returned non-zero'+ else+ info "claude plugin install ($PLUGIN_ID)"+ command claude plugin install "$PLUGIN_ID" || { err 'claude plugin install failed'; return 1; }+ fi+ command claude plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true+ info "$(t 'Claude plugin installed:' 'Claude 插件已安装:') $PLUGIN_ID"+}++install_claude_legacy() {+ local plugin_dir hooks_src ts+ plugin_dir="$(plugin_dir_on_disk claude-code-memory-plugin)" || {+ err 'legacy install needs the plugin sources on disk and none could be fetched'+ return 1+ }+ hooks_src="$plugin_dir/hooks/hooks.json"+ ts=$(date +%Y%m%d-%H%M%S)++ info "Legacy mode: claude mcp add (stdio proxy) + merging hooks into $CC_SETTINGS"+ command claude mcp remove openviking -s user >/dev/null 2>&1 || true+ command claude mcp add --scope user openviking -- node "$plugin_dir/servers/mcp-proxy.mjs" || {+ err 'claude mcp add failed'+ return 1+ }++ [ -f "$hooks_src" ] || { err "hooks source not found: $hooks_src"; return 1; }+ mkdir -p "$HOME/.claude"+ [ -f "$CC_SETTINGS" ] || echo '{}' > "$CC_SETTINGS"+ cp -p "$CC_SETTINGS" "$CC_SETTINGS.bak.$ts"+ info "Backup: $CC_SETTINGS.bak.$ts"+ node - "$hooks_src" "$CC_SETTINGS" "$plugin_dir" <<'NODE' || { err "merging hooks into $CC_SETTINGS failed; original untouched"; return 1; }+const fs = require("node:fs");+const [hooksSrc, settingsPath, pluginDir] = process.argv.slice(2);+const expand = (v) => {+ if (typeof v === "string") return v.split("${CLAUDE_PLUGIN_ROOT}").join(pluginDir);+ if (Array.isArray(v)) return v.map(expand);+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, expand(x)]));+ return v;+};+const hooks = expand(JSON.parse(fs.readFileSync(hooksSrc, "utf8")));+const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));+settings.hooks = { ...(settings.hooks || {}), ...(hooks.hooks || {}) };+fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");+NODE+ info 'hooks merged'+}++register_statusline() {+ [ "$STATUSLINE_ARG" = "no" ] && return 0+ local plugin_dir cmd existing reply ts+ if [ "$STATUSLINE_ARG" != "yes" ]; then+ [ "$INTERACTIVE" -eq 1 ] || return 0+ heading "$(t 'Statusline (optional)' 'Statusline 状态栏(可选)')"+ info "$(t 'OpenViking can show a one-line server/recall status under the input box.' 'OpenViking 可以在输入框下方显示一行服务/召回状态。')"+ info 'Sample: "OV ✓ │ Fable 5 · ctx 42% │ ↩ 6 mem (0.92) · 50ms │ ✎ 573/20k · 2 arch │ +3 today"'+ tui_menu "$(t 'Enable the OpenViking statusline?' '启用 OpenViking statusline?')" 1 \+ "$(t 'Enable' '启用')" \+ "$(t 'Skip' '跳过')"+ if [ "$TUI_MENU_CHOICE" -ne 0 ]; then+ info "$(t 'Skipped statusline registration. Re-run the installer to enable it later.' '跳过 statusline 注册,之后重跑安装脚本可启用。')"+ return 0+ fi+ fi+ plugin_dir="$(plugin_dir_on_disk claude-code-memory-plugin)" || {+ warn 'statusline needs the plugin sources on disk and none could be fetched; skipping'+ return 0+ }+ cmd="node \"$plugin_dir/scripts/statusline.mjs\""+ mkdir -p "$HOME/.claude"+ [ -f "$CC_SETTINGS" ] || echo '{}' > "$CC_SETTINGS"+ existing=$(node -e '+ try {+ const s = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));+ if (s.statusLine && s.statusLine.command) process.stdout.write(String(s.statusLine.command));+ } catch {}+ ' "$CC_SETTINGS" 2>/dev/null || true)+ if [ "$existing" = "$cmd" ]; then+ info "$(t 'Statusline already registered.' 'Statusline 已注册。')"+ return 0+ fi+ if [ -n "$existing" ] && [ "$STATUSLINE_ARG" != "yes" ]; then+ warn "$(t 'Existing statusline detected:' '检测到已有 statusline:') $existing"+ tui_menu "$(t 'Replace it with the OpenViking statusline?' '替换为 OpenViking statusline?')" 1 \+ "$(t 'Replace' '替换')" \+ "$(t 'Keep existing' '保留现有')"+ if [ "$TUI_MENU_CHOICE" -ne 0 ]; then+ info "$(t 'Kept the existing statusline.' '保留了已有 statusline。')"+ return 0+ fi+ fi+ ts=$(date +%Y%m%d-%H%M%S)+ cp -p "$CC_SETTINGS" "$CC_SETTINGS.bak.$ts"+ node - "$CC_SETTINGS" "$cmd" <<'NODE' || { err "writing statusline into $CC_SETTINGS failed"; return 1; }+const fs = require("node:fs");+const [settingsPath, cmd] = process.argv.slice(2);+const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));+settings.statusLine = { type: "command", command: cmd, padding: 0 };+fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");+NODE+ info "statusline registered (backup: $CC_SETTINGS.bak.$ts)"+ info 'Silence it anytime with: export OPENVIKING_STATUSLINE=off'+}++install_claude() {+ heading "$(t '4. Claude Code plugin' '4. Claude Code 插件')"+ if [ "$HAVE_CLAUDE" -ne 1 ]; then+ warn "$(t 'claude CLI not found; skipping Claude Code install.' '未找到 claude 命令,跳过 Claude Code 安装。')"+ return 0+ fi+ if has_plugin_subcommand; then+ migrate_claude_legacy_marketplace+ install_claude_modern || return 1+ else+ warn "$(t "This Claude Code build doesn't expose 'claude plugin' (introduced in 2.0)." '当前 Claude Code 版本没有 claude plugin 子命令(2.0 引入)。')"+ if [ "$INTERACTIVE" -eq 1 ]; then+ tui_menu "$(t 'Use legacy compatibility mode (claude mcp add + settings.json merge)?' '使用旧版兼容模式(claude mcp add + settings.json 合并)?')" 0 \+ "$(t 'Yes, install in legacy mode' '是,用兼容模式安装')" \+ "$(t 'Skip Claude Code' '跳过 Claude Code')"+ if [ "$TUI_MENU_CHOICE" -eq 1 ]; then+ info "$(t 'Skipped Claude Code install.' '跳过 Claude Code 安装。')"+ return 0+ fi+ fi+ install_claude_legacy || return 1+ fi+ register_statusline || true+}++# ---------------------------------------------------------------------------+# Codex+# ---------------------------------------------------------------------------++codex_marketplace_current_source() {+ command codex plugin marketplace list --json 2>/dev/null | node -e '+ let raw = "";+ process.stdin.on("data", (d) => { raw += d; });+ process.stdin.on("end", () => {+ try {+ const list = JSON.parse(raw).marketplaces || [];+ const m = list.find((x) => x.name === process.argv[1]);+ if (m && m.marketplaceSource) process.stdout.write(String(m.marketplaceSource.source || ""));+ } catch {}+ });+ ' "$MARKETPLACE_NAME" 2>/dev/null || true+}++migrate_codex_legacy_marketplace() {+ command codex plugin remove "$CODEX_OLD_ID" >/dev/null 2>&1 || true+ if str_contains "$(command codex plugin marketplace list 2>/dev/null || true)" "$OLD_MARKETPLACE_NAME"; then+ info "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"+ command codex plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+ [ -d "$CODEX_OLD_MARKETPLACE_ROOT" ] && rm -rf "$CODEX_OLD_MARKETPLACE_ROOT"+ [ -d "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME" ] && rm -rf "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME"+ # Drop the old plugin id's config.toml section; the unified id gets its own.+ if [ -f "$CODEX_CONFIG" ] && grep -qF "plugins.\"$CODEX_OLD_ID\"" "$CODEX_CONFIG"; then+ node - "$CODEX_CONFIG" "$CODEX_OLD_ID" <<'NODE' || true+const fs = require("node:fs");+const [path, oldId] = process.argv.slice(2);+const lines = fs.readFileSync(path, "utf8").split(/\n/);+const out = [];+let skip = false;+for (const line of lines) {+ const trimmed = line.trim();+ if (/^\[/.test(trimmed)) skip = trimmed.startsWith(`[plugins."${oldId}"`);+ if (!skip) out.push(line);+}+fs.writeFileSync(path, out.join("\n").replace(/\n*$/, "\n"));+NODE+ info "Removed old config.toml section for $CODEX_OLD_ID"+ fi+}++codex_marketplace_sync() { # codex_marketplace_sync <expected-source> <add-args...>+ local needle="$1" current+ shift+ current="$(codex_marketplace_current_source)"+ if [ -n "$current" ] && [ "$current" = "$needle" ]; then+ info "codex plugin marketplace upgrade ($MARKETPLACE_NAME)"+ command codex plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ return 0+ fi+ if [ -n "$current" ]; then+ info "$(t 'Marketplace points elsewhere; re-registering' 'marketplace 指向其他来源,重新注册') ($current)"+ command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+ info "codex plugin marketplace add $*"+ command codex plugin marketplace add "$@" >/dev/null || {+ err 'codex plugin marketplace add failed'+ return 1+ }+}++ensure_codex_config() {+ node - "$CODEX_CONFIG" "$PLUGIN_ID" <<'NODE'+const fs = require("node:fs");+const path = process.argv[2];+const pluginId = process.argv[3];+let text = "";+try { text = fs.readFileSync(path, "utf8"); } catch {}+function ensureSectionLine(src, section, key, value) {+ const lines = src.split(/\n/);+ const header = `[${section}]`;+ const start = lines.findIndex((line) => line.trim() === header);+ if (start === -1) {+ const prefix = src.trimEnd();+ return `${prefix}${prefix ? "\n\n" : ""}${header}\n${key} = ${value}\n`;+ }+ let end = lines.length;+ for (let i = start + 1; i < lines.length; i += 1) if (/^\s*\[/.test(lines[i])) { end = i; break; }+ for (let i = start + 1; i < end; i += 1) {+ if (new RegExp(`^\\s*${key}\\s*=`).test(lines[i])) {+ lines[i] = `${key} = ${value}`;+ return lines.join("\n").replace(/\n*$/, "\n");+ }+ }+ lines.splice(end, 0, `${key} = ${value}`);+ return lines.join("\n").replace(/\n*$/, "\n");+}+text = ensureSectionLine(text, `plugins."${pluginId}"`, "enabled", "true");+text = ensureSectionLine(text, "features", "plugin_hooks", "true");+fs.mkdirSync(require("node:path").dirname(path), { recursive: true });+fs.writeFileSync(path, text);+NODE+}++install_codex() {+ heading "$(t '4. Codex plugin' '4. Codex 插件')"+ if [ "$HAVE_CODEX" -ne 1 ]; then+ warn "$(t 'codex CLI not found; skipping Codex install.' '未找到 codex 命令,跳过 Codex 安装。')"+ return 0+ fi+ migrate_codex_legacy_marketplace+ case "$SOURCE_MODE" in+ remote)+ # Codex doesn't expose which --ref a registered git marketplace is+ # pinned to (`marketplace upgrade` silently refreshes the OLD ref), so+ # a matching URL is not enough — re-register deterministically.+ command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ info "codex plugin marketplace add $REPO_URL --ref $REPO_REF"+ # Sparse must include .agents/ — the marketplace manifest lives there,+ # and a plugin-dir-only sparse checkout fails manifest resolution.+ command codex plugin marketplace add "$REPO_URL" --ref "$REPO_REF" \+ --sparse examples/codex-memory-plugin --sparse .agents >/dev/null 2>&1 || \+ command codex plugin marketplace add "$REPO_URL" --ref "$REPO_REF" >/dev/null || {+ err 'codex plugin marketplace add failed'+ return 1+ }+ ;;+ archive)+ if [ "$DIST" = "tos" ] && install_codex_tos_git; then+ :+ else+ codex_marketplace_sync "$MKT_DIR" "$MKT_DIR" || return 1+ fi+ ;;+ dev)+ codex_marketplace_sync "$MKT_DIR" "$MKT_DIR" || return 1+ ;;+ esac+ if ! command codex plugin add "$PLUGIN_ID" >/dev/null 2>&1; then+ command codex plugin install "$PLUGIN_ID" >/dev/null 2>&1 || \+ warn "codex plugin add/install returned non-zero for $PLUGIN_ID; config was still updated"+ fi+ ensure_codex_config+ info "$(t 'Codex plugin enabled in' 'Codex 插件已在配置中启用:') $CODEX_CONFIG"+}++# Codex can clone git repos served over dumb HTTP from static hosting, so the+# TOS mirror hosts a slim marketplace git repo — unlike Claude Code, Codex+# keeps remote update support (`codex plugin marketplace upgrade`) on TOS.+install_codex_tos_git() {+ info "codex plugin marketplace add $CODEX_TOS_GIT_URL"+ local current+ current="$(codex_marketplace_current_source)"+ if [ -n "$current" ] && [ "$current" = "$CODEX_TOS_GIT_URL" ]; then+ command codex plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ return 0+ fi+ if [ -n "$current" ]; then+ command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+ if ! command codex plugin marketplace add "$CODEX_TOS_GIT_URL" >/dev/null 2>&1; then+ warn "$(t 'TOS git marketplace unavailable; falling back to the archive directory.' 'TOS git marketplace 不可用,回退到归档目录方式。')"+ return 1+ fi+}++# ---------------------------------------------------------------------------+# Validation+# ---------------------------------------------------------------------------++validate_install() {+ heading "$(t '5. Validation' '5. 安装校验')"+ local ok=1 cached codex_list+ if contains_harness claude && [ "$HAVE_CLAUDE" -eq 1 ] && has_plugin_subcommand; then+ if str_contains "$(command claude plugin list 2>/dev/null || true)" "$PLUGIN_NAME"; then+ info "claude: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ else+ warn "claude: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ ok=0+ fi+ fi+ if contains_harness codex && [ "$HAVE_CODEX" -eq 1 ]; then+ codex_list="$(command codex plugin list 2>/dev/null || true)"+ if str_contains "$codex_list" "$PLUGIN_NAME"; then+ info "codex: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ else+ warn "codex: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ ok=0+ fi+ cached=$(find "$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME" -name 'mcp-proxy.mjs' -path '*/servers/*' 2>/dev/null | sort | tail -n 1)+ if [ -n "$cached" ]; then+ node --check "$cached" && info "codex: $(t 'cached stdio proxy parses' '缓存中的 stdio 代理语法正常') ($cached)" || ok=0+ fi+ fi+ if [ -n "$MKT_DIR" ] && [ -f "$MKT_DIR/claude-code-memory-plugin/scripts/marketplace.test.mjs" ] && [ -d "$MKT_DIR/../.git" ]; then+ node --test "$MKT_DIR/claude-code-memory-plugin/scripts/marketplace.test.mjs" \+ "$MKT_DIR/codex-memory-plugin/scripts/marketplace.test.mjs" || ok=0+ fi+ if [ "$ok" -ne 1 ]; then+ warn "$(t 'Validation reported issues — the install may still work; check the messages above.' '校验发现问题——安装可能仍然可用,请检查上方输出。')"+ fi+}++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------++select_language++heading "$(t '1. Environment check' '1. 环境检查')"+case "$(uname -s)" in+ Darwin|Linux) info "OS: $(uname -s)" ;;+ *) err "Unsupported OS: $(uname -s). Only macOS and Linux are supported."; exit 1 ;;+esac+command -v node >/dev/null 2>&1 || { err "$(t 'node not found. Install Node.js 18+.' '未找到 node,请先安装 Node.js 18+。')"; exit 1; }+NODE_MAJOR="$(node -p 'Number(process.versions.node.split(".")[0])')"+[ "$NODE_MAJOR" -ge 18 ] || { err "Node.js 18+ required; found $(node --version)."; exit 1; }+command -v curl >/dev/null 2>&1 || warn "curl not found; archive installs may fail."++resolve_self_checkout+select_harnesses+validate_selected_harnesses+info "$(t 'Selected harnesses:' '已选择:') $(printf '%s' "$SELECTED_HARNESSES" | tr ',' ' ')"+select_dist++configure_ovcli+resolve_source_mode+prepare_marketplace_dir+cleanup_rc_wrappers++if contains_harness claude; then install_claude; fi+if contains_harness codex; then install_codex; fi+validate_install++heading "$(t 'Done' '完成')"+info "$(t 'Credentials:' '凭据:') $OVCLI_CONF"+case "$SOURCE_MODE" in+ remote) info "Marketplace: remote ($REPO_URL @ $REPO_REF)" ;;+ *) info "Marketplace: ${MKT_DIR:-$CODEX_TOS_GIT_URL}" ;;+esac+if contains_harness claude; then info "Claude: $PLUGIN_ID"; fi+if contains_harness codex; then info "Codex: $PLUGIN_ID"; fidiff --git a/examples/memory-plugin-shared/lib/capture-utils.mjs b/examples/memory-plugin-shared/lib/capture-utils.mjsnew file mode 100644index 000000000..005175bad--- /dev/null+++ b/examples/memory-plugin-shared/lib/capture-utils.mjs@@ -0,0 +1,328 @@+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/memory-plugin-shared/lib/credentials.mjs b/examples/memory-plugin-shared/lib/credentials.mjsnew file mode 100644index 000000000..dd94e089a--- /dev/null+++ b/examples/memory-plugin-shared/lib/credentials.mjs@@ -0,0 +1,193 @@+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;+ }+}++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 deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");+ if (!useCli && 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 useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, 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 = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : (mode === "env" ? "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/examples/memory-plugin-shared/lib/debug-log.mjs b/examples/memory-plugin-shared/lib/debug-log.mjsnew file mode 100644index 000000000..3a547ddcf--- /dev/null+++ b/examples/memory-plugin-shared/lib/debug-log.mjs@@ -0,0 +1,57 @@+/**+ * 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/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs b/examples/memory-plugin-shared/lib/mcp-proxy-core.mjsnew file mode 100644index 000000000..9d3325c95--- /dev/null+++ b/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs@@ -0,0 +1,450 @@+/**+ * 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,+} = {}) {+ 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 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, message = null) {+ const headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": message?.params?.protocolVersion || 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;+ 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, message),+ 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 (!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 = message.params?.protocolVersion || protocolVersion || DEFAULT_PROTOCOL_VERSION;+ sessionId = "";+ }+ if (message.method === "notifications/initialized") {+ initializedNotification = cloneMessage(message);+ }++ try {+ 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(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/examples/memory-plugin-shared/lib/pending-queue.mjs b/examples/memory-plugin-shared/lib/pending-queue.mjsnew file mode 100644index 000000000..bae9a1981--- /dev/null+++ b/examples/memory-plugin-shared/lib/pending-queue.mjs@@ -0,0 +1,438 @@+/**+ * Local pending queue for offline resilience.+ *+ * When the OpenViking server is temporarily unreachable, write operations+ * (addMessage, commitSession) serialize their payloads to+ * `~/.openviking/pending/` as JSON files. On the next session-start, the+ * queue is replayed in small batches. This is a session-start-triggered retry+ * path with maxRetries/TTL, not a long-running background worker.+ *+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }+ *+ * Config (env vars):+ * OPENVIKING_PENDING_DIR pending queue directory+ * (default: ~/.openviking/pending)+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup+ * (default: 7)+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start+ * (default: 50)+ */++import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join } from "node:path";+import { homedir } from "node:os";++const DEFAULT_MAX_RETRIES = 3;+const DEFAULT_TTL_DAYS = 7;+const DEFAULT_REPLAY_LIMIT = 50;+const PROCESSING_STALE_MS = 10 * 60 * 1000;+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");++// Pending queue files may contain raw memory payload / transcript content.+// Use restrictive permissions explicitly so we don't depend on umask.+// - dir: 0o700 (owner: rwx; group/other: none)+// - file: 0o600 (owner: rw; group/other: none)+const PENDING_DIR_MODE = 0o700;+const PENDING_FILE_MODE = 0o600;++/**+ * Ensure the pending directory exists with 0o700 permissions. If the+ * directory was created by a previous version of this code (or by hand)+ * with looser permissions, best-effort chmod it on first use.+ */+async function ensurePendingDir(dir) {+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });+ try {+ await chmod(dir, PENDING_DIR_MODE);+ } catch {+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.+ }+}++function getPendingDir() {+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();+}++function getMaxRetries() {+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;+}++function getTTLDays() {+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;+}++function getReplayLimit() {+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;+}++function stableStringify(value) {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;+}++function makeDedupKey(type, sessionId, payload) {+ return createHash("sha256")+ .update(type)+ .update("\n")+ .update(sessionId)+ .update("\n")+ .update(stableStringify(payload))+ .digest("hex");+}++function pendingFilename(dedupKey, retries = 0) {+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;+}++function retryFilename(filename, retries) {+ const bare = filename.replace(/\.(json|processing)$/, "");+ const nextBare = /_\d+$/.test(bare)+ ? bare.replace(/_\d+$/, `_${retries}`)+ : `${bare}_${retries}`;+ return `${nextBare}.json`;+}++function processingFilename(filename) {+ return filename.replace(/\.json$/, ".processing");+}++function pendingFromProcessingFilename(filename) {+ return filename.replace(/\.processing$/, ".json");+}++function isRetryableReplayFailure(res) {+ if (!res || res.ok) return false;+ const status = Number(res.status || 0);+ return !status || status >= 500 || status === 408 || status === 429;+}++async function readEntry(dir, filename) {+ const raw = await readFile(join(dir, filename), "utf-8");+ return JSON.parse(raw);+}++async function findExistingByDedupKey(dir, dedupKey) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return null;+ }++ // Fast path: filenames are `${dedupKey}_${retries}.json` (or+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.+ // Filter on prefix BEFORE opening the file to avoid readFile ++ // JSON.parse on every entry in the directory on every enqueue call —+ // the previous implementation was O(n²) in queue size. Worst case here+ // is O(n) readdir entries, but only the (typically single) prefix+ // match actually gets opened and parsed.+ const prefix = `${dedupKey}_`;++ for (const f of files) {+ if (!f.startsWith(prefix)) continue;+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;+ try {+ const entry = await readEntry(dir, f);+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };+ } catch {+ // Corrupted file - ignore for dedup lookup.+ }+ }+ return null;+}++async function recoverStaleProcessing(dir) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return 0;+ }++ const now = Date.now();+ let recovered = 0;+ for (const f of files) {+ if (!f.endsWith(".processing")) continue;+ const from = join(dir, f);+ try {+ const s = await stat(from);+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;+ const to = join(dir, pendingFromProcessingFilename(f));+ await rename(from, to);+ recovered++;+ } catch {+ // Best effort. A concurrent process may have already handled it.+ }+ }+ return recovered;+}++/**+ * Enqueue a failed operation to local disk.+ *+ * @param {string} type - "addMessage" or "commitSession"+ * @param {string} sessionId - OV session ID+ * @param {object} payload - the data that failed to send+ */+export async function enqueue(type, sessionId, payload) {+ const dir = getPendingDir();+ const now = Date.now();+ const dedupKey = makeDedupKey(type, sessionId, payload);+ const filename = pendingFilename(dedupKey, 0);+ const entry = {+ type,+ sessionId,+ payload,+ createdAt: now,+ retries: 0,+ dedupKey,+ };++ try {+ await ensurePendingDir(dir);+ } catch (err) {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }++ const existing = await findExistingByDedupKey(dir, dedupKey);+ if (existing) {+ return { ok: true, path: existing.filename, deduped: true, dedupKey };+ }++ try {+ await writeFile(join(dir, filename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ return { ok: true, path: filename, dedupKey };+ } catch (err) {+ if (err?.code !== "EEXIST") {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }+ }++ const duplicate = await findExistingByDedupKey(dir, dedupKey);+ if (duplicate) {+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };+ }+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };+}++/**+ * List all pending queue entries.+ * Returns array of { filename, entry } sorted by createdAt ascending.+ */+export async function listPending() {+ const dir = getPendingDir();+ let files;+ try {+ await recoverStaleProcessing(dir);+ files = await readdir(dir);+ } catch {+ return [];+ }++ const entries = [];+ for (const f of files) {+ if (!f.endsWith(".json")) continue;+ try {+ const entry = await readEntry(dir, f);+ entries.push({ filename: f, entry });+ } catch {+ // Corrupted file - skip.+ }+ }++ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));+ return entries;+}++/**+ * Atomically claim a pending file for replay. Only the process that successfully+ * renames the file may send the HTTP replay.+ */+export async function claimForReplay(filename) {+ if (!filename.endsWith(".json")) return null;+ const dir = getPendingDir();+ const claimed = processingFilename(filename);+ try {+ await rename(join(dir, filename), join(dir, claimed));+ return claimed;+ } catch {+ return null;+ }+}++/**+ * Remove a pending entry after successful replay.+ */+export async function dequeue(filename) {+ const dir = getPendingDir();+ try {+ await unlink(join(dir, filename));+ return true;+ } catch {+ return false;+ }+}++/**+ * Increment retry count on a pending entry. Returns false if max retries exceeded.+ */+export async function incrementRetry(filename, entry) {+ const dir = getPendingDir();+ const maxRetries = getMaxRetries();+ entry.retries = (entry.retries || 0) + 1;++ if (entry.retries > maxRetries) {+ try {+ await unlink(join(dir, filename));+ } catch {+ // Best effort.+ }+ return false;+ }++ const newFilename = retryFilename(filename, entry.retries);+ // Atomic write: write to a unique temp file in the same directory, then+ // rename into place. Avoids leaving a half-written JSON if the process+ // crashes mid-write.+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ await rename(join(dir, tmpFilename), join(dir, newFilename));+ await unlink(join(dir, filename)).catch(() => {});+ return true;+ } catch {+ await unlink(join(dir, tmpFilename)).catch(() => {});+ return false;+ }+}++/**+ * Clean up stale entries older than TTL.+ */+export async function cleanStale() {+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;+ const now = Date.now();+ const pending = await listPending();+ let cleaned = 0;++ for (const { filename, entry } of pending) {+ const age = now - (entry.createdAt || 0);+ if (age > ttlMs) {+ await dequeue(filename);+ cleaned++;+ }+ }+ return cleaned;+}++/**+ * Replay pending entries. Call this during session-start when the server is+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so+ * a just-recovered server is not hit with an unbounded replay burst.+ *+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON+ * @param {Function} log - logger function+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}+ */+export async function replayPending(fetchJSON, log) {+ const pending = await listPending();++ if (pending.length === 0) {+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };+ }++ const replayLimit = getReplayLimit();+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });++ let replayed = 0;+ let failed = 0;+ let skipped = 0;+ let deferred = 0;+ let processed = 0;++ for (const { filename, entry } of pending) {+ if (processed >= replayLimit) {+ deferred++;+ continue;+ }++ if ((entry.retries || 0) >= getMaxRetries()) {+ await dequeue(filename);+ skipped++;+ continue;+ }++ const claimedFilename = await claimForReplay(filename);+ if (!claimedFilename) {+ skipped++;+ continue;+ }+ processed++;++ let res;+ try {+ const encodedSid = encodeURIComponent(entry.sessionId);+ if (entry.type === "addMessage") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {+ method: "POST",+ body: JSON.stringify(entry.payload),+ });+ } else if (entry.type === "commitSession") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {+ method: "POST",+ body: JSON.stringify({}),+ });+ } else {+ await dequeue(claimedFilename);+ skipped++;+ continue;+ }+ } catch {+ res = { ok: false };+ }++ if (res?.ok) {+ await dequeue(claimedFilename);+ replayed++;+ } else if (!isRetryableReplayFailure(res)) {+ await dequeue(claimedFilename);+ skipped++;+ } else {+ await incrementRetry(claimedFilename, entry);+ failed++;+ if (entry.type === "addMessage") {+ deferred += Math.max(0, pending.length - processed);+ break;+ }+ }+ }++ const cleaned = await cleanStale();++ log("pending-queue", {+ action: "replay-done",+ replayed,+ failed,+ skipped,+ deferred,+ cleaned,+ });++ return { replayed, failed, skipped, deferred };+}diff --git a/examples/memory-plugin-shared/lib/session-model.mjs b/examples/memory-plugin-shared/lib/session-model.mjsnew file mode 100644index 000000000..c55820455--- /dev/null+++ b/examples/memory-plugin-shared/lib/session-model.mjs@@ -0,0 +1,56 @@+/**+ * Shared OpenViking session-id helpers for memory plugin harnesses.+ */++/**+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.+ */+function globToRe(glob) {+ let re = "^";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i];+ if (c === "*") {+ if (glob[i + 1] === "*") { re += ".*"; i++; }+ else re += "[^/]*";+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {+ re += "\\" + c;+ } else {+ re += c;+ }+ }+ re += "$";+ return new RegExp(re);+}++export function isBypassed(cfg, { sessionId, cwd } = {}) {+ if (cfg.bypassSession) return true;+ const patterns = cfg.bypassSessionPatterns || [];+ if (patterns.length === 0) return false;+ const haystacks = [sessionId, cwd].filter(Boolean);+ for (const pat of patterns) {+ const re = globToRe(pat);+ if (haystacks.some((h) => re.test(h))) return true;+ }+ return false;+}++function safeId(value, replacement = "_") {+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);+}++export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {+ if (!prefix || typeof prefix !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");+ }+ if (!sessionId || typeof sessionId !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");+ }+ const base = `${prefix}${sessionId}`;+ if (!suffix) return base;+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");+ return `${base}__${normalized}`;+}++export function deriveCodexSessionId(codexSessionId) {+ return `cx-${safeId(codexSessionId, "_")}`;+}diff --git a/examples/memory-plugin-shared/lib/setup-wizard.mjs b/examples/memory-plugin-shared/lib/setup-wizard.mjsnew file mode 100644index 000000000..9e594f850--- /dev/null+++ b/examples/memory-plugin-shared/lib/setup-wizard.mjs@@ -0,0 +1,110 @@+/**+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.+ *+ * Lets a pure-marketplace install (no installer script) configure the server+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:+ *+ * node <plugin>/scripts/setup.mjs+ *+ * Conventions: show current values, keep existing secrets on empty input,+ * merge-write (never drop unknown fields), back up the previous file, 0600.+ */++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline/promises";+import { loadCredentialFiles } from "./credentials.mjs";++const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";+const LOCAL_URL = "http://127.0.0.1:1933";++function maskSecret(value) {+ const s = String(value || "");+ if (!s) return "(not set)";+ if (s.length <= 8) return "****";+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;+}++function readJsonSafe(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return {};+ }+}++export async function runSetupWizard({+ input = process.stdin,+ output = process.stdout,+ env = process.env,+} = {}) {+ const { cliPath } = loadCredentialFiles(env);+ const current = readJsonSafe(cliPath);+ const rl = createInterface({ input, output });+ const say = (line = "") => output.write(`${line}\n`);++ try {+ say("OpenViking memory plugin setup");+ say(`Config file: ${cliPath}`);+ say("");+ say("Current values:");+ say(` url: ${current.url || "(not set)"}`);+ say(` api_key: ${maskSecret(current.api_key)}`);+ if (current.account) say(` account: ${current.account}`);+ if (current.user) say(` user: ${current.user}`);+ say("");++ const defaultUrl = current.url || LOCAL_URL;+ say("Where do you connect to OpenViking?");+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);+ say(` 3) Custom URL / keep current [${defaultUrl}]`);+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();+ let url = defaultUrl;+ if (mode === "1") {+ url = LOCAL_URL;+ } else if (mode === "2") {+ url = CLOUD_URL;+ } else {+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();+ if (answer) url = answer;+ }++ const keyPrompt = current.api_key+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `+ : "API key (leave empty for unauthenticated local mode): ";+ const keyAnswer = await rl.question(keyPrompt);+ let apiKey = current.api_key || "";+ if (keyAnswer === "-") apiKey = "";+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();+ else if (!current.api_key) apiKey = "";++ const next = { ...current, url, api_key: apiKey };++ say("");+ say("Changes:");+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();+ if (confirm === "n" || confirm === "no") {+ say("Aborted; nothing written.");+ return { written: false, path: cliPath };+ }++ mkdirSync(dirname(cliPath), { recursive: true });+ if (existsSync(cliPath)) {+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);+ }+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(cliPath, 0o600);+ } catch {+ /* best effort on platforms without chmod semantics */+ }+ say(`Written: ${cliPath}`);+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");+ return { written: true, path: cliPath };+ } finally {+ rl.close();+ }+}diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsnew file mode 100644index 000000000..b992b2d04--- /dev/null+++ b/examples/memory-plugin-shared/sync.mjs@@ -0,0 +1,42 @@+#!/usr/bin/env node++import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";+import { dirname, join, relative } from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");+const SHARED_DIR = join(ROOT, "examples", "memory-plugin-shared", "lib");+const TARGETS = [+ join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"),+ join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"),+];++const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";++async function listSharedFiles() {+ const files = await readdir(SHARED_DIR);+ return files.filter((file) => file.endsWith(".mjs")).sort();+}++async function copySharedFile(file, targetDir) {+ await mkdir(targetDir, { recursive: true });+ const source = join(SHARED_DIR, file);+ const target = join(targetDir, file);+ const body = await readFile(source, "utf-8");+ await writeFile(target, `${GENERATED_HEADER}${body}`, "utf-8");+}++async function main() {+ const files = await listSharedFiles();+ for (const targetDir of TARGETS) {+ for (const file of files) {+ await copySharedFile(file, targetDir);+ process.stdout.write(`synced ${file} -> ${relative(ROOT, targetDir)}\n`);+ }+ }+}++main().catch((err) => {+ process.stderr.write(`${err?.stack || err}\n`);+ process.exit(1);+});diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjsnew file mode 100644index 000000000..d2d2454ff--- /dev/null+++ b/examples/memory-plugin-shared/sync.test.mjs@@ -0,0 +1,30 @@+import assert from "node:assert/strict";+import { readFile, readdir } from "node:fs/promises";+import { dirname, join, relative } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");+const SHARED_DIR = join(ROOT, "examples", "memory-plugin-shared", "lib");+const TARGETS = [+ join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"),+ join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"),+];+const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";++test("vendored shared modules are synchronized", async () => {+ const files = (await readdir(SHARED_DIR)).filter((file) => file.endsWith(".mjs")).sort();+ assert.ok(files.length > 0, "expected shared modules");++ for (const targetDir of TARGETS) {+ for (const file of files) {+ const expected = `${GENERATED_HEADER}${await readFile(join(SHARED_DIR, file), "utf-8")}`;+ const actual = await readFile(join(targetDir, file), "utf-8");+ assert.equal(+ actual,+ expected,+ `${relative(ROOT, join(targetDir, file))} is out of sync; run node examples/memory-plugin-shared/sync.mjs`,+ );+ }+ }+});diff --git a/openviking/retrieve/type_quota_recall.py b/openviking/retrieve/type_quota_recall.pynew file mode 100644index 000000000..dd5c07c77--- /dev/null+++ b/openviking/retrieve/type_quota_recall.py@@ -0,0 +1,347 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Type-quota memory recall helpers.++This module centralizes the recall strategy previously embedded in VikingBot:+search memory subtrees independently by type, then render a bounded context+block that degrades from full content to summary to URI-only entries.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from typing import Any, Mapping++from openviking.core.namespace import canonical_user_root+from openviking.server.identity import RequestContext++TYPE_ORDER = ("events", "entities", "preferences", "experiences")+DEFAULT_QUOTAS = {"events": 10, "entities": 10, "preferences": 3, "experiences": 0}+DEFAULT_MAX_CHARS = 6500+DEFAULT_MIN_SCORE = 0.1+EVENTS_BUDGET_RATIO = 0.75+PREFERENCE_FULL_LIMIT = 3+++@dataclass+class RecallEntry:+ uri: str+ score: float+ type: str+ mode: str+ content: str = ""+ summary: str = ""+ rank: int = 0+ abstract: str = ""++ def to_dict(self) -> dict[str, Any]:+ data: dict[str, Any] = {+ "uri": self.uri,+ "score": self.score,+ "type": self.type,+ "mode": self.mode,+ "rank": self.rank,+ }+ if self.content:+ data["content"] = self.content+ if self.summary:+ data["summary"] = self.summary+ if self.abstract:+ data["abstract"] = self.abstract+ return data+++@dataclass+class RecallResult:+ entries: list[RecallEntry] = field(default_factory=list)+ rendered: str = ""+ stats: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ return {+ "entries": [entry.to_dict() for entry in self.entries],+ "rendered": self.rendered,+ "stats": self.stats,+ }+++def normalize_quotas(quotas: Mapping[str, Any] | None) -> dict[str, int]:+ merged = {**DEFAULT_QUOTAS}+ for key, value in (quotas or {}).items():+ if key not in DEFAULT_QUOTAS:+ continue+ try:+ merged[key] = max(0, int(value))+ except (TypeError, ValueError):+ merged[key] = 0+ return merged+++def memory_target_roots(ctx: RequestContext) -> list[str]:+ user_root = canonical_user_root(ctx)+ targets = [f"{user_root}/memories"]+ if ctx.actor_peer_id:+ targets.append(f"{user_root}/peers/{ctx.actor_peer_id}/memories")+ return targets+++def _type_target(root: str, memory_type: str) -> str:+ return f"{root.rstrip('/')}/{memory_type}"+++def _get_attr(obj: Any, name: str, default: Any = None) -> Any:+ if isinstance(obj, Mapping):+ return obj.get(name, default)+ return getattr(obj, name, default)+++def _uri(item: Any) -> str:+ return str(_get_attr(item, "uri", "") or "")+++def _score(item: Any) -> float:+ try:+ return float(_get_attr(item, "score", 0.0) or 0.0)+ except (TypeError, ValueError):+ return 0.0+++def _abstract(item: Any) -> str:+ return str(_get_attr(item, "abstract", "") or _get_attr(item, "overview", "") or "")+++def _extract_memories(result: Any) -> list[Any]:+ if result is None:+ return []+ if isinstance(result, Mapping):+ return list(result.get("memories") or [])+ return list(getattr(result, "memories", []) or [])+++def _dedupe(items: list[Any]) -> list[Any]:+ seen: set[str] = set()+ out: list[Any] = []+ for item in items:+ uri = _uri(item)+ if not uri or uri in seen:+ continue+ seen.add(uri)+ out.append(item)+ return out+++def _limit(items: list[Any], limit: int) -> list[Any]:+ return sorted(items, key=_score, reverse=True)[: max(0, limit)]+++def _filename_from_uri(uri: str) -> str:+ return uri.rstrip("/").rsplit("/", 1)[-1] if uri else ""+++def _extract_event_summary(content: str, fallback: str = "") -> str:+ if content:+ match = re.search(+ r"(?is)^\s*Summary:\s*(.*?)(?:\n\s*\d{4}-\d{2}-\d{2}"+ r"(?:\s*\([^)]+\))?\s*ChatLog:|\n\s*ChatLog:|\n\s*<!--\s*MEMORY_FIELDS|$)",+ content,+ )+ if match:+ return re.sub(r"\s+", " ", match.group(1)).strip()+ return fallback.strip()+++def type_char_budgets(max_chars: int) -> dict[str, int]:+ max_chars = max(1, int(max_chars))+ return {+ "events": int(max_chars * EVENTS_BUDGET_RATIO),+ "entities": max_chars,+ "preferences": max_chars,+ "experiences": max_chars,+ }+++def _full_fragment(index: int, uri: str, score: float, content: str) -> str:+ return (+ f'<memory index="{index}" type="full">\n'+ f" <uri>{uri}</uri>\n"+ f" <filename>{_filename_from_uri(uri)}</filename>\n"+ f" <score>{score}</score>\n"+ f" <content>{content}</content>\n"+ f"</memory>"+ )+++def _summary_fragment(index: int, uri: str, score: float, summary: str) -> str:+ return (+ f'<memory index="{index}" type="summary">\n'+ f" <uri>{uri}</uri>\n"+ f" <filename>{_filename_from_uri(uri)}</filename>\n"+ f" <score>{score}</score>\n"+ f" <summary>{summary}</summary>\n"+ f"</memory>"+ )+++def _uri_fragment(index: int, uri: str, score: float) -> str:+ return (+ f'<memory index="{index}" type="uri">\n'+ f" <uri>{uri}</uri>\n"+ f" <filename>{_filename_from_uri(uri)}</filename>\n"+ f" <score>{score}</score>\n"+ f"</memory>"+ )+++def _group_fragment(memory_type: str, fragments: list[str]) -> str:+ return (+ f'<memory_group type="{memory_type}" count="{len(fragments)}">\n'+ + "\n".join(fragments)+ + "\n</memory_group>"+ )+++async def search_type_quota_recall(+ *,+ service: Any,+ ctx: RequestContext,+ query: str,+ quotas: Mapping[str, Any] | None = None,+ max_chars: int = DEFAULT_MAX_CHARS,+ min_score: float = DEFAULT_MIN_SCORE,+ render: bool = True,+) -> RecallResult:+ normalized_quotas = normalize_quotas(quotas)+ roots = memory_target_roots(ctx)+ raw_by_type: dict[str, list[Any]] = {}+ selected: list[tuple[str, Any, int]] = []++ for memory_type in TYPE_ORDER:+ quota = normalized_quotas.get(memory_type, 0)+ if quota <= 0:+ raw_by_type[memory_type] = []+ continue+ found: list[Any] = []+ for root in roots:+ result = await service.search.find(+ query=query,+ ctx=ctx,+ target_uri=_type_target(root, memory_type),+ limit=quota,+ score_threshold=min_score,+ level=None,+ )+ found.extend(_extract_memories(result))+ found = _limit(_dedupe(found), quota)+ raw_by_type[memory_type] = found+ selected.extend((memory_type, item, rank) for rank, item in enumerate(found, start=1))++ entries: list[RecallEntry] = []+ fragments_by_type: dict[str, list[str]] = {key: [] for key in TYPE_ORDER}+ budgets = type_char_budgets(max_chars)+ used_by_type = dict.fromkeys(TYPE_ORDER, 0)+ total_chars = 0+ preference_full_count = 0+ dropped = 0+ seen_content: set[int] = set()++ for index, (memory_type, item, rank) in enumerate(selected, start=1):+ uri = _uri(item)+ if not uri or uri.rstrip("/").endswith("/profile.md"):+ continue+ score = _score(item)+ abstract = _abstract(item)+ content = ""+ try:+ content = await service.fs.read(uri, ctx=ctx)+ except Exception:+ content = ""++ content_key = content or abstract or uri+ if content_key:+ content_hash = hash(content_key)+ if content_hash in seen_content:+ continue+ seen_content.add(content_hash)++ mode = "uri"+ summary = ""+ entry_content = ""+ fragment = _uri_fragment(index, uri, score)++ if content:+ full = _full_fragment(index, uri, score, content)+ full_chars = len(full) + (1 if total_chars else 0)+ can_try_full = memory_type in budgets+ if memory_type == "preferences":+ can_try_full = preference_full_count < PREFERENCE_FULL_LIMIT+ preference_full_count += 1+ if (+ can_try_full+ and used_by_type.get(memory_type, 0) + full_chars+ <= budgets.get(memory_type, max_chars)+ and total_chars + full_chars <= max_chars+ ):+ mode = "full"+ entry_content = content+ fragment = full+ used_by_type[memory_type] = used_by_type.get(memory_type, 0) + full_chars+ total_chars += full_chars+ elif memory_type == "events":+ summary = _extract_event_summary(content, fallback=abstract)+ if summary:+ mode = "summary"+ fragment = _summary_fragment(index, uri, score, summary)+ elif abstract:+ summary = abstract++ # VikingBot's heuristic only budgets full fragments, but max_chars is+ # this API's contract: every rendered fragment counts. Fallbacks keep+ # degrading (summary -> uri) and drop entirely once nothing fits.+ if mode != "full":+ fragment_chars = len(fragment) + (1 if total_chars else 0)+ if total_chars + fragment_chars > max_chars and mode == "summary":+ mode = "uri"+ fragment = _uri_fragment(index, uri, score)+ fragment_chars = len(fragment) + (1 if total_chars else 0)+ if total_chars + fragment_chars > max_chars:+ dropped += 1+ continue+ total_chars += fragment_chars++ entries.append(+ RecallEntry(+ uri=uri,+ score=score,+ type=memory_type,+ mode=mode,+ content=entry_content,+ summary=summary,+ rank=rank,+ abstract=abstract,+ )+ )+ fragments_by_type.setdefault(memory_type, []).append(fragment)++ rendered = ""+ if render:+ rendered_groups = [+ _group_fragment(memory_type, fragments_by_type[memory_type])+ for memory_type in TYPE_ORDER+ if fragments_by_type.get(memory_type)+ ]+ rendered = "\n".join(rendered_groups)++ return RecallResult(+ entries=entries,+ rendered=rendered,+ stats={+ "quotas": normalized_quotas,+ "roots": roots,+ "searched": {key: len(value) for key, value in raw_by_type.items()},+ "returned": len(entries),+ "dropped": dropped,+ "max_chars": max_chars,+ "min_score": min_score,+ },+ )diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex da36f1314..1798d0b5b 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -38,6 +38,12 @@ from openviking.parse.parsers.code.ast.code_tools import (outline_file,search_symbols,)+from openviking.retrieve.type_quota_recall import (+ DEFAULT_MAX_CHARS,+ DEFAULT_MIN_SCORE,+ DEFAULT_QUOTAS,+ search_type_quota_recall,+)from openviking.server.auth import resolve_actor_peer_headers, resolve_identityfrom openviking.server.dependencies import get_server_config, get_servicefrom openviking.server.identity import RequestContext@@ -293,6 +299,29 @@ def _format_search_result(result) -> str:)+async def recall(+ query: str,+ quotas: Optional[dict[str, int]] = None,+ max_chars: int = DEFAULT_MAX_CHARS,+ min_score: float = DEFAULT_MIN_SCORE,+) -> str:+ """Type-quota memory recall. Searches events, entities, preferences, and experiences separately, then returns a bounded memory_group block."""+ service = get_service()+ result = await search_type_quota_recall(+ service=service,+ ctx=_get_ctx(),+ query=query,+ quotas=quotas or DEFAULT_QUOTAS,+ max_chars=max(1, int(max_chars)),+ min_score=min_score,+ render=True,+ )+ if result.rendered.strip():+ return result.rendered+ return "No relevant memories found."++# -- read ------------------------------------------------------------------diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 5ab6d1453..7155e955b 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -10,6 +10,12 @@ from pydantic import BaseModel, ConfigDictfrom openviking.core.path_variables import resolve_path_variablesfrom openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError+from openviking.retrieve.type_quota_recall import (+ DEFAULT_MAX_CHARS,+ DEFAULT_MIN_SCORE,+ DEFAULT_QUOTAS,+ search_type_quota_recall,+)from openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_servicefrom openviking.server.error_mapping import map_exception@@ -133,6 +139,19 @@ class SearchRequest(BaseModel):telemetry: TelemetryRequest = False+class RecallRequest(BaseModel):+ """Request model for type-quota memory recall."""++ model_config = ConfigDict(extra="forbid")++ query: str+ quotas: Dict[str, int] = DEFAULT_QUOTAS.copy()+ max_chars: int = DEFAULT_MAX_CHARS+ min_score: float = DEFAULT_MIN_SCORE+ render: bool = True+ telemetry: TelemetryRequest = False++class GrepRequest(BaseModel):"""Request model for grep."""@@ -243,6 +262,33 @@ async def search().model_dump(exclude_none=True)[email protected]("/recall")+async def recall(+ request: RecallRequest,+ _ctx: RequestContext = Depends(get_request_context),+):+ """Type-quota memory recall with bounded rendering."""+ service = get_service()+ execution = await run_operation(+ operation="search.recall",+ telemetry=request.telemetry,+ fn=lambda: search_type_quota_recall(+ service=service,+ ctx=_ctx,+ query=request.query,+ quotas=request.quotas,+ max_chars=max(1, int(request.max_chars)),+ min_score=request.min_score,+ render=request.render,+ ),+ )+ return Response(+ status="ok",+ result=_sanitize_floats(execution.result.to_dict()),+ telemetry=execution.telemetry,+ ).model_dump(exclude_none=True)++@router.post("/grep")async def grep(request: GrepRequest,diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 702621b0c..089795eb4 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -16,6 +16,7 @@ from fastapi import FastAPIfrom starlette.routing import Routeimport openviking.server.mcp_endpoint as mcp_endpoint+from openviking.server.auth.plugins import DevAuthPluginfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import AuthMode, RequestContext, Rolefrom openviking.server.mcp_endpoint import (@@ -31,6 +32,7 @@ from openviking.server.mcp_endpoint import (health,list_watches,read,+ recall,remember,search,)@@ -187,6 +189,38 @@ async def test_search_tool_calls_context_aware_search_with_session(service, monkassert captured["score_threshold"] == 0.1+async def test_recall_tool_returns_type_quota_memory_groups(service, monkeypatch):+ async def fake_find(**kwargs):+ if kwargs["target_uri"].endswith("/events"):+ return SimpleNamespace(+ memories=[+ SimpleNamespace(+ uri="viking://user/test_user/memories/events/e.md",+ score=0.9,+ abstract="event abstract",+ )+ ]+ )+ return SimpleNamespace(memories=[])++ async def fake_read(uri, **kwargs):+ del uri, kwargs+ return "Summary: MCP recall event.\n2026-07-06 ChatLog: details"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ result = await recall(+ query="what happened",+ quotas={"events": 1, "entities": 0, "preferences": 0, "experiences": 0},+ max_chars=200,+ min_score=0.1,+ )++ assert '<memory_group type="events"' in result+ assert "MCP recall event." in result++async def test_mcp_middleware_sets_actor_peer_context():async def downstream(scope, receive, send):ctx = _get_ctx()@@ -203,6 +237,7 @@ async def test_mcp_middleware_sets_actor_peer_context():app = FastAPI()app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)+ app.state.auth_plugin = DevAuthPlugin()app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))transport = httpx.ASGITransport(app=app)@@ -222,6 +257,7 @@ async def test_mcp_middleware_rejects_invalid_actor_peer_header():app = FastAPI()app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)+ app.state.auth_plugin = DevAuthPlugin()app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))transport = httpx.ASGITransport(app=app)diff --git a/tests/server/test_recall_endpoint.py b/tests/server/test_recall_endpoint.pynew file mode 100644index 000000000..7227a37d7--- /dev/null+++ b/tests/server/test_recall_endpoint.py@@ -0,0 +1,223 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+++import httpx++from openviking_cli.retrieve import ContextType, MatchedContext+++class _FakeFindResult:+ def __init__(self, memories):+ self.memories = memories+++def _memory(uri: str, score: float = 0.9, abstract: str = ""):+ return MatchedContext(+ uri=uri,+ context_type=ContextType.MEMORY,+ level=2,+ score=score,+ abstract=abstract,+ category=uri.split("/memories/", 1)[-1].split("/", 1)[0],+ )+++async def test_recall_endpoint_searches_by_type_quota_and_renders(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ calls = []++ async def fake_find(**kwargs):+ calls.append(kwargs)+ target_uri = kwargs["target_uri"]+ if target_uri.endswith("/events"):+ return _FakeFindResult(+ [+ _memory(+ "viking://user/test_user/memories/events/launch.md",+ 0.91,+ "Launch decision",+ )+ ]+ )+ if target_uri.endswith("/entities"):+ return _FakeFindResult(+ [+ _memory(+ "viking://user/test_user/memories/entities/openviking.md",+ 0.82,+ "OpenViking project",+ )+ ]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ if uri.endswith("/launch.md"):+ # Too large for the full-content budget -> degrades to summary.+ return "Summary: Ship stdio MCP proxy.\n2026-07-06 ChatLog: " + "x" * 2000+ return "OpenViking is the target project."++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ json={+ "query": "what should I remember",+ "quotas": {"events": 1, "entities": 1, "preferences": 0, "experiences": 0},+ "max_chars": 400,+ "min_score": 0.1,+ "render": True,+ },+ )++ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ result = body["result"]+ assert result["stats"]["returned"] == 2+ assert [entry["type"] for entry in result["entries"]] == ["events", "entities"]+ assert '<memory_group type="events"' in result["rendered"]+ assert "<summary>Ship stdio MCP proxy.</summary>" in result["rendered"]+ assert "viking://user/test_user/memories/entities/openviking.md" in result["rendered"]+ assert [call["target_uri"].rsplit("/", 1)[-1] for call in calls] == ["events", "entities"]+++async def test_recall_endpoint_respects_max_chars_budget(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ async def fake_find(**kwargs):+ if kwargs["target_uri"].endswith("/events"):+ return _FakeFindResult(+ [+ _memory("viking://user/test_user/memories/events/big.md", 0.9, "big event"),+ _memory("viking://user/test_user/memories/events/big2.md", 0.8, "second"),+ ]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ del kwargs+ # Full content and even its summary are far beyond the budget below.+ return "Summary: " + ("s" * 500) + "\ndetails: " + ("x" * 2000) + f"\n{uri}"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ # Budget fits the URI fallback but not full content or the summary:+ # the entry must degrade all the way to a uri fragment.+ resp = await client.post(+ "/api/v1/search/recall",+ json={+ "query": "budget",+ "quotas": {"events": 2, "entities": 0, "preferences": 0},+ "max_chars": 120,+ "min_score": 0.1,+ "render": True,+ },+ )+ assert resp.status_code == 200+ result = resp.json()["result"]+ assert "<summary>" not in result["rendered"]+ assert all(entry["mode"] == "uri" for entry in result["entries"])+ fragment_chars = sum(len(e["uri"]) for e in result["entries"])+ assert fragment_chars <= 120+ assert result["stats"]["returned"] + result["stats"]["dropped"] == 2++ # Budget too small for even one uri fragment: everything is dropped+ # instead of rendering past the contract.+ resp = await client.post(+ "/api/v1/search/recall",+ json={+ "query": "budget",+ "quotas": {"events": 2, "entities": 0, "preferences": 0},+ "max_chars": 10,+ "min_score": 0.1,+ "render": True,+ },+ )+ assert resp.status_code == 200+ result = resp.json()["result"]+ assert result["rendered"] == ""+ assert result["entries"] == []+ assert result["stats"]["dropped"] == 2+++async def test_recall_endpoint_sanitizes_nonfinite_scores(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ async def fake_find(**kwargs):+ if kwargs["target_uri"].endswith("/events"):+ return _FakeFindResult(+ [+ _memory(+ "viking://user/test_user/memories/events/inf.md",+ float("inf"),+ "bad score",+ )+ ]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ del uri, kwargs+ return "small content"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ json={"query": "inf", "quotas": {"events": 1, "entities": 0, "preferences": 0}},+ )++ assert resp.status_code == 200+ entries = resp.json()["result"]["entries"]+ assert entries and entries[0]["score"] == 0.0+++async def test_recall_endpoint_rejects_unknown_fields(client: httpx.AsyncClient):+ resp = await client.post(+ "/api/v1/search/recall",+ json={"query": "hello", "unexpected": "value"},+ )++ assert resp.status_code == 400+++async def test_recall_endpoint_filters_profile_and_duplicates(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ async def fake_find(**kwargs):+ del kwargs+ duplicate = _memory("viking://user/test_user/memories/events/dup.md", 0.8, "same")+ profile = _memory("viking://user/test_user/memories/profile.md", 0.99, "profile")+ return _FakeFindResult([profile, duplicate, duplicate])++ async def fake_read(uri, **kwargs):+ del kwargs+ if uri.endswith("profile.md"):+ return "profile"+ return "duplicate content"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ json={"query": "hello", "quotas": {"events": 3, "entities": 0, "preferences": 0}},+ )++ assert resp.status_code == 200+ entries = resp.json()["result"]["entries"]+ assert [entry["uri"] for entry in entries] == ["viking://user/test_user/memories/events/dup.md"]