Skip to content

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

feat(installer): install from the TOS release only, confirm before changing, add the bootstrap (#5464)

t0saki4310cc34e555
diff --git a/.github/scripts/check-marketplace-archive.mjs b/.github/scripts/check-marketplace-archive.mjs
index f18d49601..341702d90 100644
--- a/.github/scripts/check-marketplace-archive.mjs
+++ b/.github/scripts/check-marketplace-archive.mjs
@@ -7,6 +7,7 @@
// the twenty-two modules the installer assembles and four of the thirty-eight
// copies the sync generates.
+import { realpathSync } from "node:fs";
import { readdir, readFile, stat } from "node:fs/promises";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
@@ -214,7 +215,16 @@ async function main(stage, expected) {
}
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
const [stage, ...expected] = process.argv.slice(2);
// The expected directories are the caller's list, not the stage's own: a name
// dropped from it would otherwise leave both this check and the staging script
diff --git a/.github/scripts/generate-claude-marketplace-json.sh b/.github/scripts/generate-claude-marketplace-json.sh
new file mode 100644
index 000000000..176454ee4
--- /dev/null
+++ b/.github/scripts/generate-claude-marketplace-json.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Write the Claude Code URL marketplace the installer registers: the staged
+# directory marketplace's entry, re-pointed at the release's immutable plugin
+# zip. Claude Code fetches both over HTTPS without git, and updates an
+# installed plugin when the entry's version changes, so the version is the
+# plugin manifest's own.
+
+set -euo pipefail
+
+TAG="${1:?usage: generate-claude-marketplace-json.sh <tag> <tos-base> <plugin-zip> <stage-dir> <out>}"
+TOS_BASE="${2%/}"
+PLUGIN_ZIP="$3"
+STAGE="$4"
+OUT="$5"
+
+sha256() { sha256sum "$1" | cut -d' ' -f1; }
+
+jq \
+ --arg url "${TOS_BASE}/releases/${TAG}/openviking-memory-claude.zip" \
+ --arg sha256 "$(sha256 "${PLUGIN_ZIP}")" \
+ --arg version "$(jq -r .version "${STAGE}/claude-code-memory-plugin/.claude-plugin/plugin.json")" \
+ '.description = "OpenViking plugins for Claude Code (TOS mirror)."
+ | .plugins |= map(select(.name == "openviking-memory")
+ | .version = $version
+ | .source = {source: "archive", url: $url, sha256: $sha256})
+ | if (.plugins | length) == 1 then . else error("openviking-memory entry not found") end' \
+ "${STAGE}/.claude-plugin/marketplace.json" > "${OUT}"
diff --git a/.github/scripts/opencode-release-version.mjs b/.github/scripts/opencode-release-version.mjs
index ed741af06..3127f820f 100644
--- a/.github/scripts/opencode-release-version.mjs
+++ b/.github/scripts/opencode-release-version.mjs
@@ -1,5 +1,5 @@
-import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
-import { pathToFileURL } from 'node:url';
+import { appendFileSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
+import { fileURLToPath, pathToFileURL } from 'node:url';
export function resolveRelease(metadata, sourceCommit, date) {
if (!metadata || typeof metadata.versions !== 'object' || !metadata.versions) {
@@ -53,4 +53,13 @@ async function main() {
console.log(`${pkg.name}@${release.version}: ${release.published ? 'already published from this commit' : 'ready to publish'}`);
}
-if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return import.meta.url === pathToFileURL(process.argv[1]).href;
+ }
+}
+
+if (isDirectRun()) await main();
diff --git a/.github/scripts/publish-dumb-git-repo.sh b/.github/scripts/publish-dumb-git-repo.sh
new file mode 100755
index 000000000..11c78a6bf
--- /dev/null
+++ b/.github/scripts/publish-dumb-git-repo.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# Replace a bare git repository served over git's dumb HTTP protocol from an
+# S3-compatible bucket. Clients read info/refs and objects/info/packs, then
+# fetch the packs those name, so the new packs go up first, the files that
+# point at them next, and the previous release's objects are deleted last.
+
+set -euo pipefail
+
+REPO="${1:?usage: publish-dumb-git-repo.sh <bare-repo> <s3-url> [aws-s3-option...]}"
+DEST="${2:?usage: publish-dumb-git-repo.sh <bare-repo> <s3-url> [aws-s3-option...]}"
+DEST="${DEST%/}"
+shift 2
+AWS_ARGS=("$@")
+
+# The repository is tiny and its refs must never be served stale.
+NO_CACHE_CONTROL="no-store, no-cache, must-revalidate, max-age=0"
+
+aws_s3() {
+ aws s3 "$@" ${AWS_ARGS[@]+"${AWS_ARGS[@]}"} --cache-control "${NO_CACHE_CONTROL}" --only-show-errors
+}
+
+aws_s3 cp --recursive "${REPO}/objects/pack" "${DEST}/objects/pack"
+for file in objects/info/packs packed-refs info/refs HEAD; do
+ aws_s3 cp "${REPO}/${file}" "${DEST}/${file}"
+done
+aws_s3 sync --delete "${REPO}" "${DEST}"
diff --git a/.github/scripts/reproducible-zip.sh b/.github/scripts/reproducible-zip.sh
new file mode 100755
index 000000000..0a33de365
--- /dev/null
+++ b/.github/scripts/reproducible-zip.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# Zip one directory so that every build of the same commit gives the same
+# bytes. The versioned release keys are meant to be immutable and the
+# marketplace manifests pin these zips' sha256, so re-running a release must
+# not change them. Entries are sorted, stamped with the commit time and carry
+# no extra attributes.
+
+set -euo pipefail
+
+OUT="${1:?usage: reproducible-zip.sh <out.zip> <parent-dir> <entry>}"
+PARENT="${2:?usage: reproducible-zip.sh <out.zip> <parent-dir> <entry>}"
+ENTRY="${3:?usage: reproducible-zip.sh <out.zip> <parent-dir> <entry>}"
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
+# Zip stores local time, so one fixed zone keeps the stamp the same everywhere.
+export TZ=UTC
+STAMP="$(git -C "${ROOT}" log -1 --format=%cd --date=format-local:%Y%m%d%H%M.%S)"
+
+case "${OUT}" in /*) ;; *) OUT="${PWD}/${OUT}" ;; esac
+rm -f "${OUT}"
+cd "${PARENT}"
+find "${ENTRY}" -exec touch -t "${STAMP}" {} +
+find "${ENTRY}" | LC_ALL=C sort | zip -X -q "${OUT}" -@
diff --git a/.github/scripts/stamp-installer-version.sh b/.github/scripts/stamp-installer-version.sh
new file mode 100755
index 000000000..4558620c3
--- /dev/null
+++ b/.github/scripts/stamp-installer-version.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# Write a copy of the shared installer that reports the release it was
+# published with. The repository copy keeps INSTALLER_VERSION="dev", which the
+# installer reads as "not a release build".
+
+set -euo pipefail
+
+SRC="${1:?usage: stamp-installer-version.sh <installer> <version> <out>}"
+VERSION="${2:?usage: stamp-installer-version.sh <installer> <version> <out>}"
+OUT="${3:?usage: stamp-installer-version.sh <installer> <version> <out>}"
+
+# The version lands inside a double-quoted shell string and a sed replacement.
+case "${VERSION}" in
+ *[!0-9A-Za-z._+-]*)
+ echo "Refusing to stamp installer version '${VERSION}'" >&2
+ exit 1
+ ;;
+esac
+
+count="$(grep -cxF 'INSTALLER_VERSION="dev"' "${SRC}" || true)"
+if [ "${count}" != 1 ]; then
+ echo "${SRC}: expected one INSTALLER_VERSION=\"dev\" line, found ${count}" >&2
+ exit 1
+fi
+
+sed "s/^INSTALLER_VERSION=\"dev\"\$/INSTALLER_VERSION=\"${VERSION}\"/" "${SRC}" > "${OUT}"
diff --git a/.github/workflows/release-tos.yml b/.github/workflows/release-tos.yml
index f849358b6..80145e9ac 100644
--- a/.github/workflows/release-tos.yml
+++ b/.github/workflows/release-tos.yml
@@ -13,7 +13,7 @@ on:
description: 'Also overwrite the stable/latest paths'
required: false
type: boolean
- default: true
+ default: false
permissions:
contents: read
@@ -80,10 +80,15 @@ jobs:
# Slim archive with the memory integrations and marketplace manifests
# required by clients that support native marketplace installation.
# The shared installer registers the unzipped directory as a local
- # marketplace for both Claude Code and Codex (GitHub-free path).
+ # marketplace when the client has no remote TOS channel.
STAGE=/tmp/memory-plugin-marketplace
bash .github/scripts/stage-memory-plugin-marketplace.sh "${STAGE}"
- (cd /tmp && zip -rq "memory-plugin-marketplace-${RELEASE_TAG}.zip" memory-plugin-marketplace)
+ bash .github/scripts/reproducible-zip.sh "/tmp/memory-plugin-marketplace-${RELEASE_TAG}.zip" /tmp memory-plugin-marketplace
+ # Claude Code (>= 2.1.224) installs and auto-updates from a URL
+ # marketplace whose entry downloads this zip of the plugin alone.
+ bash .github/scripts/reproducible-zip.sh "/tmp/openviking-memory-claude-${RELEASE_TAG}.zip" "${STAGE}" claude-code-memory-plugin
+ bash .github/scripts/generate-claude-marketplace-json.sh "${RELEASE_TAG}" "https://ovrelease.tos-cn-beijing.volces.com" \
+ "/tmp/openviking-memory-claude-${RELEASE_TAG}.zip" "${STAGE}" /tmp/claude-marketplace.json
- name: Build marketplace git repo (dumb HTTP)
if: steps.tos_config.outputs.configured == 'true'
@@ -92,7 +97,7 @@ jobs:
# 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.
+ # and uses the URL marketplace above instead.
SRC=/tmp/memory-plugins-src
rm -rf "${SRC}" /tmp/memory-plugins.git
cp -R /tmp/memory-plugin-marketplace "${SRC}"
@@ -105,6 +110,12 @@ jobs:
git -C /tmp/memory-plugins.git update-server-info
du -sh /tmp/memory-plugins.git
+ - name: Stamp shared installer version
+ if: steps.tos_config.outputs.configured == 'true'
+ run: |
+ bash .github/scripts/stamp-installer-version.sh examples/memory-plugin-shared/install.sh \
+ "${RELEASE_TAG#v}" /tmp/memory-plugin-shared-install.sh
+
- name: Upload release artifacts to TOS
if: steps.tos_config.outputs.configured == 'true'
env:
@@ -157,22 +168,11 @@ 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_PLUGIN_ZIP="/tmp/openviking-memory-claude-${RELEASE_TAG}.zip"
+ SHARED_INSTALL="/tmp/memory-plugin-shared-install.sh"
+ SHARED_BOOTSTRAP="examples/memory-plugin-shared/bootstrap.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"
@@ -181,8 +181,10 @@ jobs:
# Versioned, immutable copies
upload "${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 "${CLAUDE_PLUGIN_ZIP}" "releases/${RELEASE_TAG}/openviking-memory-claude.zip" "${ZIP_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"
+ upload /tmp/claude-marketplace.json "releases/${RELEASE_TAG}/claude-marketplace.json" "application/json" "${IMMUTABLE_CACHE_CONTROL}"
upload "${SHARED_INSTALL}" "releases/${RELEASE_TAG}/memory-plugin-shared/install.sh" "${SHELL_CONTENT_TYPE}" "${IMMUTABLE_CACHE_CONTROL}"
+ upload "${SHARED_BOOTSTRAP}" "releases/${RELEASE_TAG}/memory-plugin-shared/bootstrap.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}"
@@ -196,8 +198,13 @@ jobs:
if [ "${UPDATE_LATEST}" = "true" ]; then
upload "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"
+ bash .github/scripts/publish-dumb-git-repo.sh /tmp/memory-plugins.git \
+ "s3://${TOS_BUCKET}/plugins/memory-plugins.git" --endpoint-url "https://${TOS_S3_ENDPOINT}"
+ echo "Uploaded plugins/memory-plugins.git/"
+ UPLOADED_KEYS="${UPLOADED_KEYS}- \`plugins/memory-plugins.git/\`"$'\n'
+ upload "s3://${TOS_BUCKET}/releases/${RELEASE_TAG}/claude-marketplace.json" "plugins/claude/marketplace.json" "application/json" "${NO_CACHE_CONTROL}"
upload "${SHARED_INSTALL}" "memory-plugin-shared/install.sh" "${SHELL_CONTENT_TYPE}" "${NO_CACHE_CONTROL}"
+ upload "${SHARED_BOOTSTRAP}" "memory-plugin-shared/bootstrap.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/RELEASE.md b/RELEASE.md
index 762e6282f..08a9822c9 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -88,10 +88,24 @@ The TOS release flow creates a source archive and uploads these assets:
- Codex memory plugin install script
- Matching TOS install scripts
-Formal GitHub Releases trigger the TOS upload automatically. Manual republishing can specify a tag and use `update_latest` to decide whether to overwrite stable paths.
+Formal GitHub Releases trigger the TOS upload automatically and overwrite the stable paths. A manual run takes a tag and uploads its versioned paths; it overwrites the stable paths only with `update_latest=true` (default `false`), so repairing an older release's assets does not move users back to that release.
If TOS secrets are not fully configured, the workflow skips uploading and reports it in the step summary without failing the whole workflow.
+### Memory Plugin Hotfix and Rollback
+
+The memory plugins are installed and updated from the stable paths: `plugins/claude/marketplace.json` (Claude Code), `plugins/memory-plugins.git` (Codex and TraeCode CLI), `releases/latest/memory-plugin-marketplace.zip` (every other host), `releases/latest/channels.json` (install version resolution), and `memory-plugin-shared/install.sh` and `bootstrap.sh`. One run of the workflow builds all of them from the commit of the tag it is given.
+
+To publish a plugin hotfix without a product release:
+
+1. Merge the fix with the plugin version bumps that `.github/scripts/check-plugin-version-bumps.sh` requires. Claude Code only updates an installed plugin when its version string changes.
+2. Tag a commit that holds the last release plus the fix, for example on a branch cut from the last `vX.Y.Z` tag with the fix cherry-picked. Use a tag that does not start with `v`, such as `memory-plugins-YYYY.M.D`, and do not publish a GitHub Release for it: `v*.*.*` tag pushes trigger the Docker workflow, published Releases trigger the main release workflows, and the main package version is resolved from `v*` tags.
+3. Push the tag and run `gh workflow run release-tos.yml -f tag=<tag> -f update_latest=true`.
+
+To roll back, run `gh workflow run release-tos.yml -f tag=<last good tag> -f update_latest=true`. The workflow definition comes from the default branch, but the scripts it calls come from the tag's checkout, so only tags that already contain the current release scripts can be republished; to go back further, publish the older plugin code as a hotfix.
+
+After either run, Claude Code (URL marketplace) picks up the change at its next update check, and a lower version counts as an update. Codex picks it up at its next start, TraeCode CLI on `trae-cli plugin marketplace upgrade`. Cursor, TRAE, TRAE CN, ZCode, Kimi Code, OpenCode, pi, and Claude Code installs on a local directory marketplace change only when the installer is re-run. dsh installs from npm and is not affected.
+
## Python SDK Release Flow
The Python SDK lives under `sdk/python`, and its PyPI package name is `openviking-sdk`. SDK releases use an independent tag namespace:
diff --git a/RELEASE_CN.md b/RELEASE_CN.md
index 5d9368a6a..148e350d0 100644
--- a/RELEASE_CN.md
+++ b/RELEASE_CN.md
@@ -84,10 +84,24 @@ TOS 发布流程会生成源码 zip,并上传以下类型资产:
- Codex memory plugin 安装脚本
- 对应 TOS install 脚本
-正式 GitHub Release 会自动触发 TOS 上传。手动补发时可指定 tag,并通过 `update_latest` 决定是否覆盖稳定路径。
+正式 GitHub Release 会自动触发 TOS 上传,并覆盖稳定路径。手动触发时指定 tag,workflow 上传该 tag 的版本化路径;只有设置 `update_latest=true`(默认 `false`)才会覆盖稳定路径,因此补传旧版本的资产不会把用户退回到旧版本。
如果 TOS 相关 secrets 未配置完整,workflow 会跳过上传并在 step summary 中说明,不会使整个流程失败。
+### Memory 插件热修复与回滚
+
+Memory 插件的安装和更新都读稳定路径:`plugins/claude/marketplace.json`(Claude Code)、`plugins/memory-plugins.git`(Codex 和 TraeCode CLI)、`releases/latest/memory-plugin-marketplace.zip`(其他所有宿主)、`releases/latest/channels.json`(安装时的版本解析),以及 `memory-plugin-shared/install.sh` 和 `bootstrap.sh`。workflow 每次运行都从所给 tag 对应的 commit 构建这全部内容。
+
+不发产品版本、单独发布插件热修复:
+
+1. 合入修复,并按 `.github/scripts/check-plugin-version-bumps.sh` 的要求升级插件版本。Claude Code 只在版本号变化时更新已安装的插件。
+2. 在“上一个正式版本 + 修复”的 commit 上打 tag,例如从上一个 `vX.Y.Z` tag 拉分支并 cherry-pick 修复。tag 不要以 `v` 开头,例如 `memory-plugins-YYYY.M.D`,也不要为它发布 GitHub Release:推送 `v*.*.*` tag 会触发 Docker workflow,发布 Release 会触发主包发版 workflow,主包版本号也从 `v*` tag 解析。
+3. 推送 tag,然后运行 `gh workflow run release-tos.yml -f tag=<tag> -f update_latest=true`。
+
+回滚时运行 `gh workflow run release-tos.yml -f tag=<上一个正常的 tag> -f update_latest=true`。workflow 定义取自默认分支,但它调用的脚本来自 tag 的 checkout,所以只能重新发布已经包含当前发布脚本的 tag;要退回更早的插件代码,按热修复流程发布。
+
+两种操作完成后,Claude Code(URL marketplace)在下次检查更新时生效,版本号变低也算更新。Codex 在下次启动时生效,TraeCode CLI 在执行 `trae-cli plugin marketplace upgrade` 时生效。Cursor、TRAE、TRAE CN、ZCode、Kimi Code、OpenCode、pi,以及使用本地目录 marketplace 的 Claude Code,需要重新运行安装器才会变化。dsh 从 npm 安装,不受影响。
+
## Python SDK 发版流程
Python SDK 位于 `sdk/python`,PyPI 包名为 `openviking-sdk`。SDK 使用独立 tag 命名空间:
diff --git a/agent-plugins/servers/mcp-proxy.mjs b/agent-plugins/servers/mcp-proxy.mjs
index aa7992b19..2718484da 100644
--- a/agent-plugins/servers/mcp-proxy.mjs
+++ b/agent-plugins/servers/mcp-proxy.mjs
@@ -14,6 +14,7 @@
* TARGETS) — edit them in examples/memory-plugin-shared/lib, never here.
*/
+import { realpathSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { buildProxyConnection } from "./shared/credentials.mjs";
@@ -29,6 +30,15 @@ export function readProxyConfig(env = process.env) {
return toMcpProxyConfig(cfg, { env });
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
}
diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.md
index 32d059982..58dc7e6b0 100644
--- a/docs/en/agent-integrations/02-claude-code.md
+++ b/docs/en/agent-integrations/02-claude-code.md
@@ -18,7 +18,7 @@ In regions where GitHub is hard to reach, run the same installer from the Volcen
bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
```
-> **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.)
+> **TOS and Claude Code updates**: on Claude Code 2.1.224 or later, the TOS channel registers a TOS-hosted marketplace with auto-update turned on, so new plugin versions download in the background and load after a restart. Older Claude Code gets 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.
@@ -46,7 +46,7 @@ If you prefer to set it up manually:
>
> 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? 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).
+> Running Claude Code < 2.0? The installer skips it and asks you to upgrade. To wire it up by hand with `claude mcp add` and a hooks merge, 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>
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index 2b0731c2f..33a6685cc 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -173,7 +173,7 @@ Core modules at a glance (detailed further in the per-dimension sections):
| Harness | Integration Form | Install Channel | Session ID Prefix/Format | Config Source | Standalone Setup Wizard |
|---|---|---|---|---|---|
-| claude-code | CC plugin (marketplace): 9 hooks + MCP proxy + slash + statusline + skill | One-line `install.sh --harness claude` (supports both the modern plugin path and the legacy `claude mcp add` compatibility path) / manual marketplace / TOS mirror | `cc-<CC session_id verbatim>`; subagents use `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
+| claude-code | CC plugin (marketplace): 9 hooks + MCP proxy + slash + statusline + skill | One-line `install.sh --harness claude` (Claude Code 2.0+) / manual marketplace / TOS mirror | `cc-<CC session_id verbatim>`; subagents use `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
| codex | Codex plugin (marketplace): 6 hooks + MCP proxy + skill | One-line `--harness codex` / `codex plugin marketplace add` (the TOS channel uses dumb-HTTP git to ensure remote updates continue working) | `cx-<safeId>` (deterministically derived, without reading state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |
| trae-cli | **Installed as a codex plugin alias** (TraeCode CLI 2.0, 2.0 only; a Codex-family CLI: uses the `traecli` binary and `~/.trae/traecli.toml` config; its capability surface is identical to codex) | One-line `--harness trae-cli` (reuses the codex install flow; marketplace commands run against the targeted binary, e.g., `traecli plugin marketplace add`) | Same derivation rule as codex | Same as codex (env + ovcli.conf `plugin.codex` + ov.conf) | ✅ (same as codex) |
| cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌ (shares the installer TUI) |
@@ -191,7 +191,7 @@ Core modules at a glance (detailed further in the per-dimension sections):
The unified install script (`examples/memory-plugin-shared/install.sh`) supports eleven harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, opencode, pi, dsh`. (Note that `openclaw` uses its own distribution channel, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:
-- **Interactive prompts:** Two distributions (`--dist github|tos`) and three sources (`--source remote|archive|dev`) are available. When executed via `bash <(curl …)`, it reads input directly from `/dev/tty` to ensure prompts remain interactive.
+- **Sources and prompts:** Everything is installed from the OpenViking release on Volcengine TOS; run from a repository checkout, the installer uses that checkout instead (`--source archive|dev`). When executed via `bash <(curl …)`, it reads input directly from `/dev/tty` to ensure prompts remain interactive.
- **Usage:** In the official documentation, the canonical one-line command omits the `--harness` flag, which launches a TUI multi-select menu. However, the setup-helper forwarding scripts bundled with each plugin append the `--harness` flag automatically.
- **Idempotent merging:** Hooks and MCP entries are identified by the `OPENVIKING_INTEGRATION_ID` marker. This ensures stale entries are pruned and new ones are appended without affecting third-party configurations. Writes are atomic: the script creates a `.bak` backup, writes to a temporary file, and then renames it over the target with `0600` permissions.
- **Credential wizard:** This writes to `~/.openviking/ovcli.conf`. Users can select from three targets (local `http://127.0.0.1:1933` / Volcengine Cloud `https://api.vikingdb.cn-beijing.volces.com/openviking` / custom). If a configuration already exists, the script displays the current values first and asks whether to keep or reconfigure them, masking the API key for security.
diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.md
index 64733ddb6..68a560638 100644
--- a/docs/zh/agent-integrations/02-claude-code.md
+++ b/docs/zh/agent-integrations/02-claude-code.md
@@ -18,7 +18,7 @@ GitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个安装
bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
```
-> **Claude Code 走 TOS 的注意事项**:TOS 渠道注册的是本地目录 marketplace,**无法自动更新**——更新请重跑安装脚本。(Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力。)
+> **Claude Code 走 TOS 时的更新**:Claude Code 2.1.224 及以上版本,TOS 渠道注册的是 TOS 托管的 marketplace 并开启自动更新,新版插件在后台下载,重启 Claude Code 后生效。更早的 Claude Code 注册的是本地目录 marketplace,**无法自动更新**——更新请重跑安装脚本。(Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力。)
现在不再需要任何 shell wrapper:插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`(或 `OPENVIKING_*` 环境变量),与 hooks 使用同一套配置链。
@@ -46,7 +46,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
>
> 使用纯本地模式(`http://127.0.0.1:1933`,无鉴权)?您可以跳过第 1 步,插件将直接使用本地默认值。
>
-> 使用 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)。
+> 使用 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>
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 7f4a2c15d..bbb4c2e52 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -175,7 +175,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| harness | 集成形态 | 安装通道 | 会话 id 前缀/格式 | 配置来源 | 独立 setup 向导 |
|---|---|---|---|---|---|
-| claude-code | CC 插件(marketplace):包含 9 hook + MCP 代理 + slash + statusline + skill | 一键 `install.sh --harness claude`(支持现代 plugin 路径与 legacy `claude mcp add` 兼容路径)/ 手动 marketplace / TOS 镜像 | `cc-<CC session_id 原文>`;subagent 格式为 `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
+| claude-code | CC 插件(marketplace):包含 9 hook + MCP 代理 + slash + statusline + skill | 一键 `install.sh --harness claude`(Claude Code 2.0+)/ 手动 marketplace / TOS 镜像 | `cc-<CC session_id 原文>`;subagent 格式为 `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
| codex | Codex 插件(marketplace):包含 6 hook + MCP 代理 + skill | 一键 `--harness codex` / `codex plugin marketplace add`(TOS 走 dumb-HTTP git 以保留远程更新能力) | `cx-<safeId>`(确定性推导,不读取 state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |
| trae-cli | **codex 插件别名安装**(TraeCode CLI 2.0,仅支持 2.0;Codex 系:binary `traecli`、配置 `~/.trae/traecli.toml`;能力面与 codex 一致) | 一键 `--harness trae-cli`(复用 codex 安装流程;marketplace 命令会随指向的 binary 执行,如 `traecli plugin marketplace add`) | 与 codex 的派生规则一致 | 与 codex 一致(env + ovcli.conf `plugin.codex` + ov.conf) | ✅(同 codex) |
| cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌(共用安装器 TUI) |
@@ -193,7 +193,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
统一安装脚本 `examples/memory-plugin-shared/install.sh` 覆盖 11 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, kimicode, opencode, pi, dsh`(其中 openclaw 走自有渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:
-- 双分发:`--dist github|tos`;三源:`--source remote|archive|dev`。以 `bash <(curl …)` 方式执行时会从 `/dev/tty` 读取输入,从而保留交互。
+- 安装源与交互:全部从火山引擎 TOS 上的 OpenViking 发布包安装;在仓库 checkout 中运行时改用该 checkout(`--source archive|dev`)。以 `bash <(curl …)` 方式执行时会从 `/dev/tty` 读取输入,从而保留交互。
- 官方 docs 的规范一键命令是不带 `--harness` 的裸命令(执行后进入 TUI 多选);而各插件自带的 setup-helper 转发脚本在调用时会自动补 `--harness`。
- 幂等合并:hooks/mcp 条目按 `OPENVIKING_INTEGRATION_ID` 标记识别自有条目,做到剔旧追新的同时不动第三方;写入采用原子操作——先备份 `.bak`,写 tmp 后 rename 覆盖,权限 0600。
- 凭据向导写 `~/.openviking/ovcli.conf`:三选一(本地 `http://127.0.0.1:1933` / 火山云 `https://api.vikingdb.cn-beijing.volces.com/openviking` / 自定义),已有配置先展示当前值再问"沿用/重配",API key 掩码。
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index a8eaf6798..8098f8113 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.4",
+ "version": "0.5.5",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
index b3b28f568..c5817cdaf 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.4",
+ "version": "0.5.5",
"description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
index 111d8778f..5efe1e563 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.4",
+ "version": "0.5.5",
"clients": [
"kimicode"
],
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index ae783e8b7..eedb5be45 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.4",
+ "version": "0.5.5",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index 7cb522036..7c702fbaf 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.4",
+ "version": "0.5.5",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index 658d8ae61..a144e25c3 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agent-hook-plugin",
- "version": "0.5.4",
+ "version": "0.5.5",
"description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode and Kimi Code — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/servers/mcp-proxy.mjs b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
index 55030d77f..19a4fc8d6 100644
--- a/examples/agent-hook-plugin/servers/mcp-proxy.mjs
+++ b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
+import { realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve as resolvePath } from "node:path";
@@ -19,6 +20,15 @@ export function readProxyConfig(env = process.env) {
return toMcpProxyConfig(cfg, { env });
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
}
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index 5972cab6e..9b41ed74d 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.6.5",
+ "version": "0.6.6",
"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/README.md b/examples/claude-code-memory-plugin/README.md
index b5638a3df..adfa43940 100644
--- a/examples/claude-code-memory-plugin/README.md
+++ b/examples/claude-code-memory-plugin/README.md
@@ -16,7 +16,7 @@ Long-term semantic memory for Claude Code, powered by [OpenViking](https://githu
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude
```
-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.
+macOS / Linux only. Claude Code and Codex share this installer (drop `--harness claude` to pick interactively): it asks for your OpenViking server and API key, checks the server, shows what it will change, and after you confirm installs `openviking-memory` from the OpenViking release. Claude Code 2.1.224 and newer then updates the plugin on its own. 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.
@@ -94,7 +94,7 @@ jq -e . /tmp/ov-settings.json >/dev/null && mv /tmp/ov-settings.json ~/.claude/s
rm -f /tmp/ov-hooks.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).
+The one-line installer does not set this up: when it finds a pre-2.0 build it skips Claude Code and asks you to upgrade.
#### 4. Start Claude Code
diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.md
index ae1fb32ba..8cfa33e62 100644
--- a/examples/claude-code-memory-plugin/README_CN.md
+++ b/examples/claude-code-memory-plugin/README_CN.md
@@ -12,7 +12,7 @@
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude
```
-仅支持 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` 渲染。重复执行安全。
+仅支持 macOS 和 Linux。Claude Code 和 Codex 共用这一个安装脚本(去掉 `--harness claude` 可交互勾选):它会询问 OpenViking 服务地址和 API key,检查服务,列出将要修改的内容,确认后从 OpenViking 发布版安装 `openviking-memory`。Claude Code 2.1.224 及以上版本之后会自行更新插件。stdio MCP 代理运行时读取 `ovcli.conf`,不再需要 shell wrapper 或 `.mcp.json` 渲染。重复执行安全。
如果你更喜欢手动操作,按下面四步走。
@@ -90,7 +90,7 @@ jq -e . /tmp/ov-settings.json >/dev/null && mv /tmp/ov-settings.json ~/.claude/s
rm -f /tmp/ov-hooks.json
```
-一行安装脚本在检测到 2.0 之前的版本时会自动执行以上流程(并在 `~/.openviking/openviking-repo` 保留一份源码 checkout 供上面的绝对路径引用)。
+一行安装脚本不会做以上配置:检测到 2.0 之前的版本时,它会跳过 Claude Code 并提示升级。
#### 4. 启动 Claude Code
diff --git a/examples/claude-code-memory-plugin/STATUSLINE.md b/examples/claude-code-memory-plugin/STATUSLINE.md
index 42c7f7011..87feb2242 100644
--- a/examples/claude-code-memory-plugin/STATUSLINE.md
+++ b/examples/claude-code-memory-plugin/STATUSLINE.md
@@ -1,6 +1,6 @@
# Reading and Personalizing the OpenViking Statusline
-A guide for an AI assistant (or you) to read the OpenViking statusline and **customize** it beyond the defaults the installer sets up. The "What each segment means" section below is the canonical glossary; the rest covers personalization recipes that env vars don't cover. For the environment-variable reference, see `$REPO/docs/en/agent-integrations/02-claude-code.md`.
+A guide for an AI assistant (or you) to read the OpenViking statusline and **customize** it beyond the defaults the installer sets up. The "What each segment means" section below is the canonical glossary; the rest covers personalization recipes that env vars don't cover. For the environment-variable reference, see [docs/en/agent-integrations/02-claude-code.md](https://github.com/volcengine/OpenViking/blob/main/docs/en/agent-integrations/02-claude-code.md).
When a user asks for something the env vars don't cover, prefer the smallest local edit over inventing a new configurable knob.
@@ -8,13 +8,12 @@ When a user asks for something the env vars don't cover, prefer the smallest loc
## Where everything lives
-The OpenViking repo and plugin code are checked out to a known location by the installer. Throughout this doc:
+The statusline runs from the plugin copy Claude Code installed. Throughout this doc:
-- **`$REPO`** = the OpenViking repo root. Default: `~/.openviking/openviking-repo` (override via `OPENVIKING_REPO_DIR` at install time). Verify with `ls "$REPO/examples/claude-code-memory-plugin"` — if that path is wrong, find the real one with `jq -r '.statusLine.command' ~/.claude/settings.json` (the registered command points into the plugin) or `find ~ -path '*/claude-code-memory-plugin/scripts/statusline.mjs' 2>/dev/null`.
-- **`$PLUGIN`** = `$REPO/examples/claude-code-memory-plugin`. The plugin's own root.
+- **`$PLUGIN`** = the installed plugin's root. Find it with `jq -r '.plugins["openviking-memory@openviking"][0].installPath' ~/.claude/plugins/installed_plugins.json` (under `$CLAUDE_CONFIG_DIR` when that is set). The command the installer registers looks this path up on every run, so the statusline follows plugin updates. Claude Code installs each update into a new directory, so a local edit under `$PLUGIN` lasts until the next plugin update.
- **`$STATE`** = `~/.openviking/state` (override via `OPENVIKING_HOME`). Where hook-written JSON snapshots live.
-Resolve `$REPO` once before editing anything — every relative path below is anchored to it.
+Resolve `$PLUGIN` once before editing anything — every relative path below is anchored to it.
| Concern | File |
|--------------------------------------------|---------------------------------------------------|
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index 91d9d4ae3..168232309 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.6.5",
+ "version": "0.6.6",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
index 90e220989..f39aed5a0 100644
--- a/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
+++ b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
@@ -129,14 +129,22 @@ function checkInstall(report, { cliOnPath }) {
const entry = known.data[MARKETPLACE];
if (!entry) {
report.fail(`marketplace '${MARKETPLACE}' is not registered`, `known: ${Object.keys(known.data).join(", ") || "(none)"}`,
- "re-run the installer, or: claude plugin marketplace add ~/.openviking/marketplaces/openviking-claude");
+ "re-run the installer: bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness claude");
} else {
const source = entry.source || {};
const location = entry.installLocation || source.path || "";
- const desc = source.source === "directory" ? `directory ${homeShort(source.path || "")}` : source.source === "github" ? `github ${source.repo || ""}` : JSON.stringify(source);
+ const desc = source.source === "directory" ? `directory ${homeShort(source.path || "")}` : source.source === "github" ? `github ${source.repo || ""}` : source.source === "url" ? `url ${source.url || ""}` : JSON.stringify(source);
if (/\.json$/i.test(String(source.path || ""))) {
report.warn(`marketplace '${MARKETPLACE}' is registered as a file (${homeShort(source.path)})`, "file-type marketplaces mis-derive installLocation and `claude plugin marketplace update` fails with EISDIR",
"claude plugin marketplace remove openviking && re-run the installer (it registers a directory)");
+ } else if (source.source === "url") {
+ // Claude Code caches a URL marketplace as a bare manifest file, so there
+ // is no directory at installLocation to check.
+ report.ok(`marketplace '${MARKETPLACE}' → ${desc}`);
+ // The user-settings declaration wins; known_marketplaces.json only
+ // catches up with it on Claude Code's next startup.
+ const declared = tryJson(join(CLAUDE_DIR, "settings.json"))?.extraKnownMarketplaces?.[MARKETPLACE]?.autoUpdate;
+ report.info((declared ?? entry.autoUpdate) ?"auto-update is on (Claude Code checks in the background during interactive sessions; a new version loads after restart)" : "auto-update is off: update with claude plugin update openviking-memory@openviking, or enable it for this marketplace in /plugin");
} else if (location && !existsPath(join(location, ".claude-plugin", "marketplace.json"))) {
report.fail(`marketplace '${MARKETPLACE}' points at a missing directory`, `${desc}\nexpected ${homeShort(join(location, ".claude-plugin", "marketplace.json"))}`,
"the checkout/archive was moved or deleted; re-run the installer");
@@ -178,7 +186,10 @@ function checkInstall(report, { cliOnPath }) {
"remove the openviking entries from .hooks in ~/.claude/settings.json (back it up first)");
}
const statusCmd = String(settings.data.statusLine?.command || "");
- if (statusCmd.includes("statusline.mjs")) {
+ if (statusCmd.includes("installed_plugins.json")) {
+ // The installer's command resolves the current plugin install on each run.
+ report.ok("statusline registered (runs the installed plugin)");
+ } else if (statusCmd.includes("statusline.mjs")) {
const m = /node\s+"?([^"]+statusline\.mjs)"?/.exec(statusCmd);
const path = m ? expandHome(m[1]) : "";
if (path && !existsPath(path)) report.warn("statusLine points at a missing statusline.mjs", homeShort(path), "re-run the installer or fix .statusLine.command in ~/.claude/settings.json");
diff --git a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
index b762bdf02..cd6a66707 100644
--- a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
@@ -9,6 +9,7 @@
* protocol-clean.
*/
+import { realpathSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../scripts/config.mjs";
@@ -20,6 +21,15 @@ export function readProxyConfig(env = process.env) {
return toMcpProxyConfig(loadConfig(undefined, { env }), { env });
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
}
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
index e4395ecdc..ed4d314bf 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -75,7 +75,7 @@ Work top-down; fix the first ✗ and rerun before chasing the next.
|---|---|---|
| `plugin disabled — every hook exits immediately` | No parseable config, `OPENVIKING_MEMORY_ENABLED=0`, or `claude_code.enabled: false` in ov.conf | Fix the reason it names. Fresh machine: create `~/.openviking/ovcli.conf` with `url` + `api_key` (`chmod 600`). |
| `ovcli.conf cannot be parsed` | Trailing comma/comment; the plugin treats the file as absent | Fix the JSON. This is the most common "installed but nothing happens". |
-| `not registered in installed_plugins.json` / `claude plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude`; add `--dist tos` where GitHub is blocked). |
+| `not registered in installed_plugins.json` / `claude plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness claude`). |
| `plugin is disabled in ~/.claude/settings.json` | Installed but `enabledPlugins` is false/missing | `claude plugin enable openviking-memory@openviking`, restart Claude Code. |
| `marketplace 'openviking' … missing directory` / registered as a file | The checkout/archive moved, or a file-type marketplace (fails `marketplace update` with EISDIR) | `claude plugin marketplace remove openviking` then re-run the installer. |
| `no skills/ directory in this plugin copy` / registered version behind the repo | Stale version-keyed cache; `claude plugin update` is a no-op when the version string did not change | `claude plugin marketplace update openviking && claude plugin uninstall openviking-memory@openviking && claude plugin install openviking-memory@openviking`. |
@@ -173,7 +173,8 @@ ask before stopping or restarting it.
- After changing `url`, installing or updating the plugin: restart Claude
Code. Hooks re-read config per invocation, the MCP proxy does not.
- Updates: GitHub installs → `claude plugin marketplace update openviking && claude plugin update openviking-memory@openviking`;
- TOS/archive and dev-checkout installs → re-run the installer.
+ TOS installs on Claude Code 2.1.224+ (a `url` marketplace) auto-update in the background, or on demand with `claude plugin update openviking-memory@openviking`;
+ older TOS, archive and dev-checkout installs → re-run the installer.
- Confirm the fix by rerunning the doctor, then by observing an
`<openviking-context>` block on the next prompt.
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
index d363dcaf2..684d8172a 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -15,11 +15,11 @@ and `OPENVIKING_PENDING_DIR` relocate individual pieces.
| `<repo root>/.openviking/config.json` / `config.local.json` | Workspace config layers, `version: 1` required: `peer.source`, `peer.id`, `recall.*`, `capture.*`, `bypass.session_patterns`, `labels`. `config.json` is committed and shared; `config.local.json` is private and gitignored. Trusted without a prompt, but connection and credential keys (`url`, `api_key`, `account`, `user`, `extra_headers`, …) are stripped with a warning and `${VAR}` is never expanded. A blanket `.openviking/` rule in `.gitignore` stops `config.json` from ever being committed — narrow it to `.openviking/media/` and `.openviking/downloads/`. |
| `~/.openviking/workspaces/<slot>.json` | Per-machine workspace registry, one file per workspace (`<dir name>-<hash>.json`, mode 0600). Outranks both workspace files, and nothing writes it — a user creates the file by hand. An entry recorded for a different repository is ignored, not inherited. |
| `~/.claude/plugins/installed_plugins.json` | Install registry: `plugins["openviking-memory@openviking"][0].installPath/version/lastUpdated`. |
-| `~/.claude/plugins/known_marketplaces.json` | Marketplace `openviking` → `source` (`directory` path or `github`), `installLocation`. |
+| `~/.claude/plugins/known_marketplaces.json` | Marketplace `openviking` → `source` (`directory` path, `github`, or `url` of the TOS manifest), `installLocation`, `autoUpdate`. |
| `~/.claude/plugins/cache/openviking/openviking-memory/<version>/` | The copy Claude Code actually runs. Keyed by `plugin.json` version. |
| `~/.claude/settings.json` | `enabledPlugins`, `statusLine`, optional `env`, legacy `hooks`. |
-| `~/.openviking/marketplaces/openviking-claude/` | Installer-generated directory marketplace (GitHub dist) whose manifest points at `git-subdir` `examples/claude-code-memory-plugin`. |
-| `~/.openviking/memory-plugin-marketplace/` | Unpacked TOS archive (TOS dist); cannot self-update. |
+| `~/.openviking/marketplaces/openviking-claude/` | Directory marketplace that older installers generated for GitHub installs; its manifest points at `git-subdir` `examples/claude-code-memory-plugin`. The installer no longer writes it, and a re-run moves the registration to the TOS URL marketplace. |
+| `~/.openviking/memory-plugin-marketplace/` | Unpacked plugin bundle from the release; the Claude Code marketplace only before Claude Code 2.1.224, and cannot self-update. |
| `~/.openviking/state/` | `last-recall.json`, `last-capture.json`, `last-session-event.json`, `daily-stats.json`, `server-probe.json`, `host-cli-probe.json`, `context-face.json`, `recall-digest.json`, `ws-peer-<session>.json`, `ws-identity-<hash>.json` (60s cache of the git identity behind the peer). Anything else there is residue. |
| `~/.openviking/last_inject.md` | Full text of the last SessionStart injection. |
| `~/.openviking/logs/cc-hooks.log` | JSONL hook + proxy log; written only when `OPENVIKING_DEBUG=1` or `debug: true`. |
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index da41bfb93..223d544b2 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.10.6",
+ "version": "0.10.7",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index 27b3899fd..6dd48cc22 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -35,11 +35,11 @@ For TraeCode CLI 2.0:
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness trae-cli
```
-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:
+Claude Code and Codex share this installer (drop `--harness codex` to pick interactively). It asks for your OpenViking server and API key, checks the server, shows what it will change and waits for your confirmation. It:
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`
+3. Registers the `openviking` marketplace — a git repository on the OpenViking release, which Codex upgrades when it starts; the release's plugin bundle if that fails, or this checkout when run from one — 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. Runs plugin-list and stdio MCP validation
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
index e2899df4e..de2755c70 100644
--- a/examples/codex-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
@@ -8,6 +8,7 @@
* to the server's /mcp endpoint, and keeps stdout protocol-clean.
*/
+import { realpathSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../scripts/config.mjs";
@@ -19,7 +20,16 @@ export function readProxyConfig(env = process.env) {
return toMcpProxyConfig(loadConfig(undefined, { env }), { env });
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({
readConfig: readProxyConfig,
loggerFactory: createLogger,
diff --git a/examples/codex-memory-plugin/setup-helper/install.sh b/examples/codex-memory-plugin/setup-helper/install.sh
index 5a8d48bda..c7b858a31 100755
--- a/examples/codex-memory-plugin/setup-helper/install.sh
+++ b/examples/codex-memory-plugin/setup-helper/install.sh
@@ -10,11 +10,7 @@
# interactive prompts are skipped and existing config / env vars are used.
#
# Env overrides:
-# OPENVIKING_HOME, OPENVIKING_REPO_DIR, OPENVIKING_REPO_URL,
-# 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`.
+# OPENVIKING_HOME, OPENVIKING_CLI_CONFIG_FILE.
set -euo pipefail
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
index 62be0acb0..a8c9682d3 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -78,7 +78,7 @@ Work top-down; fix the first ✗ and rerun before chasing the next.
| Doctor finding | Meaning | Action |
|---|---|---|
| `ovcli.conf cannot be parsed` / `no usable config` | Trailing comma/comment; the plugin treats the file as absent and uses the localhost default | Fix the JSON. Fresh machine: create `~/.openviking/ovcli.conf` with `url` + `api_key`, `chmod 600`. |
-| `codex plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness codex`; add `--dist tos` where GitHub is blocked). |
+| `codex plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --harness codex`). |
| `hooks disabled in [features]` / `hooks feature is disabled in Codex` | The applicable hooks feature is disabled | Set `hooks = true` under `[features]` in `~/.codex/config.toml` (or `plugin_hooks = true` for older Codex), restart Codex. |
| `[features] hooks enabled by default` | The live CLI reports hooks enabled; legacy `plugin_hooks` has no effect | Continue with the remaining checks. |
| `[features] hooks is not set` (info) | The CLI probe could not determine the modern feature state and no legacy flag decides it | Verify with `codex features list`; an unset key alone does not prove hooks are disabled. |
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
index 27b37d98f..bc6570a2c 100644
--- a/examples/dsh-memory-plugin/config.mjs
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -1,7 +1,7 @@
import { buildPluginConfig } from "./shared/plugin-config.mjs";
import { loadCredentialFiles } from "./shared/credentials.mjs";
-export const PLUGIN_VERSION = "0.5.9";
+export const PLUGIN_VERSION = "0.5.10";
/**
* Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index e080c5f68..6592ec53c 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.9",
+ "version": "0.5.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.9",
+ "version": "0.5.10",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index bb57cb38f..95688e7ec 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.9",
+ "version": "0.5.10",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"icon": "./icon.svg",
"type": "module",
diff --git a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
index 4035c1e99..83c16f2a6 100644
--- a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
@@ -10,6 +10,7 @@
* from the Cordis patch are invisible to a subprocess otherwise.
*/
+import { realpathSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveConfig } from "../config.mjs";
@@ -30,6 +31,15 @@ export function readProxyConfig(env = process.env, cwd = process.cwd()) {
});
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
}
diff --git a/examples/memory-plugin-shared/README.md b/examples/memory-plugin-shared/README.md
index c33387d0c..c00a70b69 100644
--- a/examples/memory-plugin-shared/README.md
+++ b/examples/memory-plugin-shared/README.md
@@ -12,6 +12,33 @@ When the copies are made follows how the plugin is delivered. Claude Code, Codex
> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
> `viking://user/memories` shorthand is rejected by newer servers.
+## Installer
+
+`install.sh` installs the memory plugin into Claude Code, Codex, Cursor, TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, Kimi Code, OpenCode, pi and DeepSeek Harness (dsh), and writes the server connection to `~/.openviking/ovcli.conf`. Its header comment lists the hosts it contacts and the files it writes for each harness; `--help` lists every option and environment variable.
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
+
+# Without prompts:
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+ --yes --harness claude,codex --url <server-url> --api-key <api-key>
+```
+
+A run asks for the harnesses and the server, checks the server (`/health`, then `/api/v1/system/status` with the key), prints what it will change and waits for confirmation. Nothing is written before that. With `--yes`, or when no terminal is available, it asks nothing and proceeds.
+
+Everything comes from the OpenViking release on Volcengine TOS (`OPENVIKING_TOS_BASE`); the installer never contacts GitHub and never runs git.
+
+- Claude Code 2.1.224 and newer registers a URL marketplace and updates the plugin on its own. Older 2.x builds, custom Claude-format CLIs, and a URL marketplace that cannot be registered fall back to a local directory marketplace from the plugin bundle. Claude Code without `claude plugin` (older than 2.0) is skipped with a hint to upgrade.
+- Codex and Codex-format CLIs such as the TraeCode CLI register a git marketplace served from TOS, which Codex upgrades when it starts. When that fails they fall back to the directory marketplace from the bundle.
+- Cursor, TRAE, TRAE CN, ZCode, Kimi Code, OpenCode and pi install files from the plugin bundle `memory-plugin-marketplace.zip`, downloaded at most once per run into `~/.openviking/memory-plugin-marketplace`. They update when the installer runs again.
+- dsh installs `@openviking/dsh-memory-plugin` from npm through `dsh plugin add`.
+
+After the confirmation the installer runs a version check: it asks `https://openviking.net/install/v1/<harness>.json` which release to install, once per selected harness. `OPENVIKING_SKIP_VERSION_CHECK=1` skips the check and installs the latest release, which is also what happens when the check fails. When the answer names a checksum, the bundle is verified against it.
+
+Run from a repository checkout, the installer uses that checkout's plugins (`--source dev`) and downloads nothing from the release; `--source archive` or `--dist tos` installs the release instead. `--dist github`, `--source remote` and `OPENVIKING_REPO_URL` / `OPENVIKING_REPO_REF` / `OPENVIKING_REPO_BRANCH` are accepted and ignored with a notice; to install a branch, run `install.sh` from a checkout of it.
+
+`--uninstall --harness <list>` removes the Cursor, TRAE, TRAE CN, ZCode and Kimi Code integrations. Claude Code, Codex, OpenCode, pi and dsh are removed with their own commands, which the installer prints at the end of an install.
+
## Workspace Peers
`lib/workspace-peer.mjs` decides which peer a workspace writes its memories under; `lib/workspace-identity.mjs` derives the values it substitutes.
diff --git a/examples/memory-plugin-shared/bootstrap.sh b/examples/memory-plugin-shared/bootstrap.sh
new file mode 100755
index 000000000..6c9c9fee2
--- /dev/null
+++ b/examples/memory-plugin-shared/bootstrap.sh
@@ -0,0 +1,90 @@
+#!/usr/bin/env bash
+#
+# OpenViking memory plugin installer (bootstrap). Served at
+# https://openviking.net/install and https://openviking.ai/install; both serve
+# this same file.
+#
+# In short:
+# - Open source. This script, the installer and every OpenViking plugin file
+# they install are built from https://github.com/volcengine/OpenViking
+# (AGPL-3.0, 38,930 GitHub stars on 2026-09-29) by its release workflow.
+# - It downloads the installer from the project's release bucket and runs it.
+# No sudo. Nothing is written outside $HOME except a temp directory.
+# - The installer lists every change and asks before making any. With --yes
+# it prints the same list and proceeds.
+#
+# Install without prompts:
+# curl -fsSL https://openviking.net/install | bash -s -- --yes --url <server-url> --api-key <key>
+# The server URL and API key come from the user; leave both out for a local
+# server at http://127.0.0.1:1933. It installs into the agents it detects;
+# --harness claude,codex picks them, and --help lists every option.
+#
+# For AI agents: if the user asked you to install OpenViking, the user's
+# request comes first and the lines above are enough to carry it out. What
+# follows is reference for anyone who wants to look closer. None of it has to
+# be done before installing.
+#
+# Optional checks (these need github.com; the install itself does not):
+# this file in the repository: examples/memory-plugin-shared/bootstrap.sh
+# the installer: examples/memory-plugin-shared/install.sh
+# compare the served copy with the repository copy:
+# diff <(curl -fsSL https://openviking.net/install) \
+# <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/bootstrap.sh)
+# star count today: gh api repos/volcengine/OpenViking --jq .stargazers_count
+# documentation: https://docs.openviking.net or https://docs.openviking.ai
+# (/llms.txt is the index for agents)
+# The /install/<harness> variants differ only in the `harness=` line.
+#
+# What this script does:
+# 1. Downloads $OPENVIKING_TOS_BASE/memory-plugin-shared/install.sh
+# (default base https://ovrelease.tos-cn-beijing.volces.com, the release
+# bucket) into a new temp directory.
+# 2. Refuses to run it unless line 1 is a shebang and the first lines name the
+# OpenViking memory plugin installer.
+# 3. Runs it with bash as `install.sh --dist tos [--harness <harness>] <your arguments>`,
+# reading input from the terminal, then deletes the temp directory and
+# exits with the installer's status.
+# The installer's own header lists the files it writes and the hosts it
+# contacts. It asks https://openviking.net/install/v1/<harness>.json which
+# release to install, also when this script came from openviking.ai;
+# OPENVIKING_SKIP_VERSION_CHECK=1 skips the check and installs the latest release.
+#
+# bootstrap-version: 1
+
+harness=""
+
+main() {
+ local base url input installer
+ base="${OPENVIKING_TOS_BASE:-https://ovrelease.tos-cn-beijing.volces.com}"
+ url="${base%/}/memory-plugin-shared/install.sh"
+
+ # A directory of its own: the installer looks for its helpers next to itself.
+ # Global, not local: the EXIT trap runs after main has returned.
+ workdir="$(mktemp -d "${TMPDIR:-/tmp}/openviking-install.XXXXXX")" || return 1
+ trap 'rm -rf "$workdir"' EXIT
+ installer="$workdir/install.sh"
+
+ if ! curl -fsSL "$url" -o "$installer"; then
+ echo "OpenViking: could not download $url" >&2
+ return 1
+ fi
+ if ! head -n 1 "$installer" | grep -q '^#!' ||
+ ! head -n 5 "$installer" | grep -q 'OpenViking Memory Plugin shared installer'; then
+ echo "OpenViking: $url did not return the installer script; not running it." >&2
+ return 1
+ fi
+
+ export OPENVIKING_INSTALL_SITE="${OPENVIKING_INSTALL_SITE:-https://openviking.net}"
+ export OPENVIKING_INSTALLER_REEXEC=0
+ if [ -n "$harness" ]; then
+ set -- --harness "$harness" "$@"
+ fi
+ # Under `curl ... | bash` stdin is this script, so the installer's prompts need the terminal.
+ input=/dev/null
+ if { true </dev/tty; } 2>/dev/null; then
+ input=/dev/tty
+ fi
+ bash "$installer" --dist tos "$@" <"$input"
+}
+
+main "$@"
diff --git a/examples/memory-plugin-shared/bootstrap.test.mjs b/examples/memory-plugin-shared/bootstrap.test.mjs
new file mode 100644
index 000000000..9de80b0f5
--- /dev/null
+++ b/examples/memory-plugin-shared/bootstrap.test.mjs
@@ -0,0 +1,156 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } 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 bootstrap = join(dirname(fileURLToPath(import.meta.url)), "bootstrap.sh");
+
+// Prints what the bootstrap handed it, one bracketed argument per line so
+// arguments with spaces stay distinguishable, and exits with $FAKE_EXIT.
+const FAKE_INSTALLER = `#!/usr/bin/env bash
+#
+# OpenViking Memory Plugin shared installer (test double).
+for arg in "$@"; do printf 'arg=[%s]\\n' "$arg"; done
+echo "site=$OPENVIKING_INSTALL_SITE"
+echo "reexec=$OPENVIKING_INSTALLER_REEXEC"
+if [ -c /dev/stdin ]; then echo "stdin=device"; else echo "stdin=other"; fi
+exit "\${FAKE_EXIT:-0}"
+`;
+
+async function withFixture(body, fn) {
+ const server = createServer((req, res) => {
+ if (req.url !== "/memory-plugin-shared/install.sh") {
+ res.writeHead(404).end();
+ return;
+ }
+ res.writeHead(200, { "content-type": "text/plain" }).end(body);
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const root = mkdtempSync(join(tmpdir(), "openviking-bootstrap-"));
+ const tmp = join(root, "tmp");
+ mkdirSync(tmp);
+ try {
+ return await fn({ base: `http://127.0.0.1:${server.address().port}`, root, tmp });
+ } finally {
+ server.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+// detached puts the child in a new session, so it has no controlling terminal
+// and /dev/tty cannot be opened, whatever terminal the test runner has.
+function run(args, { base, tmp, env = {}, stdin = "" }) {
+ const { OPENVIKING_INSTALL_SITE, OPENVIKING_INSTALLER_REEXEC, ...inherited } = process.env;
+ const childEnv = { ...inherited, OPENVIKING_TOS_BASE: base, TMPDIR: tmp, ...env };
+ return new Promise((resolve, reject) => {
+ const child = spawn("bash", args, { env: childEnv, detached: true });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("error", reject);
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ child.stdin.end(stdin);
+ });
+}
+
+function argsOf(stdout) {
+ return stdout.split("\n").filter((line) => line.startsWith("arg=")).map((line) => line.slice(5, -1));
+}
+
+test("passes the user's arguments through unchanged after --dist tos", async () => {
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const result = await run(
+ [bootstrap, "--yes", "--url", "http://127.0.0.1:1933", "--api-key", "key with spaces", ""],
+ fixture,
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(argsOf(result.stdout), [
+ "--dist", "tos", "--yes", "--url", "http://127.0.0.1:1933", "--api-key", "key with spaces", "",
+ ]);
+ assert.match(result.stdout, /^site=https:\/\/openviking\.net$/m);
+ assert.match(result.stdout, /^reexec=0$/m);
+ assert.match(result.stdout, /^stdin=device$/m, "without a terminal the installer reads /dev/null");
+ assert.deepEqual(readdirSync(fixture.tmp), [], "the downloaded installer is removed");
+ });
+});
+
+test("an explicit OPENVIKING_INSTALL_SITE is kept", async () => {
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const result = await run([bootstrap], { ...fixture, env: { OPENVIKING_INSTALL_SITE: "http://site.test" } });
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /^site=http:\/\/site\.test$/m);
+ });
+});
+
+test("the harness variable adds --harness before the user's arguments", async () => {
+ const source = readFileSync(bootstrap, "utf8");
+ assert.equal(source.split("\n").filter((line) => line === 'harness=""').length, 1);
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const variant = join(fixture.root, "install-claude.sh");
+ writeFileSync(variant, source.replace('harness=""', 'harness="claude"'));
+ const result = await run([variant, "--yes"], fixture);
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(argsOf(result.stdout), ["--dist", "tos", "--harness", "claude", "--yes"]);
+ });
+});
+
+test("refuses to run an HTML page served in place of the installer", async () => {
+ const page = "<!doctype html>\n<html><body>OpenViking Memory Plugin shared installer</body></html>\n";
+ await withFixture(page, async (fixture) => {
+ const result = await run([bootstrap, "--yes"], fixture);
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, "");
+ assert.match(result.stderr, /did not return the installer script/);
+ assert.deepEqual(readdirSync(fixture.tmp), []);
+ });
+});
+
+test("fails when the download fails", async () => {
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const result = await run([bootstrap], { ...fixture, base: `${fixture.base}/missing` });
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, "");
+ assert.match(result.stderr, /could not download/);
+ });
+});
+
+test("exits with the installer's status", async () => {
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const result = await run([bootstrap], { ...fixture, env: { FAKE_EXIT: "3" } });
+ assert.equal(result.status, 3);
+ assert.deepEqual(readdirSync(fixture.tmp), []);
+ });
+});
+
+test("works as `cat bootstrap.sh | bash -s -- ...` without a terminal", async () => {
+ await withFixture(FAKE_INSTALLER, async (fixture) => {
+ const result = await run(["-s", "--", "--yes", "--harness", "codex"], {
+ ...fixture,
+ stdin: readFileSync(bootstrap, "utf8"),
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(argsOf(result.stdout), ["--dist", "tos", "--yes", "--harness", "codex"]);
+ assert.match(result.stdout, /^stdin=device$/m);
+ });
+});
+
+test("runs the installer from a directory of its own, not from the shared temp dir", async () => {
+ const installer = `#!/usr/bin/env bash
+#
+# OpenViking Memory Plugin shared installer (test double).
+dir="$(cd "$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
+[ -e "$dir/lib/install" ] && echo "stray=seen" || echo "stray=unseen"
+`;
+ await withFixture(installer, async (fixture) => {
+ mkdirSync(join(fixture.tmp, "lib", "install"), { recursive: true });
+ const result = await run([bootstrap], fixture);
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /^stray=unseen$/m);
+ assert.deepEqual(readdirSync(fixture.tmp), ["lib"]);
+ });
+});
diff --git a/examples/memory-plugin-shared/entrypoint-symlink.test.mjs b/examples/memory-plugin-shared/entrypoint-symlink.test.mjs
new file mode 100644
index 000000000..cd0f1b9b3
--- /dev/null
+++ b/examples/memory-plugin-shared/entrypoint-symlink.test.mjs
@@ -0,0 +1,126 @@
+/**
+ * Scripts that double as importable modules run their CLI only when they are
+ * the process entrypoint. Node resolves the entrypoint's `import.meta.url`
+ * through symlinks while `process.argv[1]` keeps the path as typed, so a
+ * symlinked `~/.openviking` or HOME made a lexical comparison fail and the
+ * script exited 0 having done nothing. Each case starts one script through a
+ * symlinked directory and checks for an effect only its CLI produces.
+ */
+
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { ROOT, SKILL_TARGETS } from "./sync.mjs";
+import { stripJsonc } from "./lib/install/jsonc-edit.mjs";
+
+function withTemp(fn) {
+ const dir = mkdtempSync(join(tmpdir(), "openviking-entrypoint-"));
+ try {
+ return fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/** Run `<link>/<name>` where `link` is a symlink to `realDir`. */
+function runThroughLink(tmp, realDir, name, args = [], input = "") {
+ const link = join(tmp, "link");
+ symlinkSync(realDir, link, "dir");
+ const env = { ...process.env, HOME: tmp };
+ delete env.SOURCE_COMMIT;
+ return spawnSync(process.execPath, [join(link, name), ...args], {
+ input,
+ env,
+ encoding: "utf8",
+ timeout: 20_000,
+ });
+}
+
+const output = (result) => `status=${result.status}\n${result.stdout}\n${result.stderr}`;
+
+test("host-json-config runs its CLI through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const result = runThroughLink(tmp, join(ROOT, "examples/memory-plugin-shared/lib/install"), "host-json-config.mjs");
+ assert.equal(result.status, 2, output(result));
+ assert.match(result.stderr, /usage: host-json-config\.mjs/u);
+ });
+});
+
+test("jsonc-edit runs its CLI through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const config = join(tmp, "opencode.jsonc");
+ const result = runThroughLink(
+ tmp,
+ join(ROOT, "examples/memory-plugin-shared/lib/install"),
+ "jsonc-edit.mjs",
+ [config, "", "/opt/openviking/servers/mcp-proxy.mjs"],
+ );
+ assert.equal(result.status, 0, output(result));
+ const written = JSON.parse(stripJsonc(readFileSync(config, "utf8")));
+ assert.deepEqual(written.mcp.openviking.command, ["node", "/opt/openviking/servers/mcp-proxy.mjs"]);
+ });
+});
+
+for (const pluginDir of [
+ "agent-plugins",
+ "examples/agent-hook-plugin",
+ "examples/claude-code-memory-plugin",
+ "examples/codex-memory-plugin",
+ "examples/dsh-memory-plugin",
+ "examples/opencode-plugin",
+]) {
+ test(`${pluginDir} MCP proxy serves stdio through a symlinked directory`, () => {
+ withTemp((tmp) => {
+ const result = runThroughLink(tmp, join(ROOT, pluginDir, "servers"), "mcp-proxy.mjs", [], "not json\n");
+ assert.equal(result.status, 0, output(result));
+ assert.equal(JSON.parse(result.stdout.trim()).error.code, -32700, output(result));
+ });
+ });
+}
+
+// sync.mjs writes into the tree it sits in, so it runs from an empty copy of
+// that tree rather than from this checkout.
+test("sync runs through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const tree = join(tmp, "tree");
+ const shared = join(tree, "examples/memory-plugin-shared");
+ mkdirSync(join(shared, "lib"), { recursive: true });
+ copyFileSync(join(ROOT, "examples/memory-plugin-shared/sync.mjs"), join(shared, "sync.mjs"));
+ for (const { skill } of SKILL_TARGETS) mkdirSync(join(tree, "examples/skills", skill), { recursive: true });
+ const result = runThroughLink(tmp, tree, "examples/memory-plugin-shared/sync.mjs");
+ assert.equal(result.status, 0, output(result));
+ assert.ok(existsSync(join(shared, "lib/MANIFEST")), output(result));
+ });
+});
+
+test("the pi experiment's credentials CLI runs through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const result = runThroughLink(
+ tmp,
+ join(ROOT, "examples/pi-experimental-context-management/shared"),
+ "credentials.mjs",
+ );
+ assert.equal(result.status, 2, output(result));
+ assert.match(result.stderr, /usage: ov-credentials\.mjs/u);
+ });
+});
+
+test("check-marketplace-archive runs through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const result = runThroughLink(tmp, join(ROOT, ".github/scripts"), "check-marketplace-archive.mjs");
+ assert.equal(result.status, 2, output(result));
+ assert.match(result.stderr, /usage: check-marketplace-archive\.mjs/u);
+ });
+});
+
+test("opencode-release-version runs through a symlinked directory", () => {
+ withTemp((tmp) => {
+ const result = runThroughLink(tmp, join(ROOT, ".github/scripts"), "opencode-release-version.mjs");
+ assert.equal(result.status, 1, output(result));
+ assert.match(result.stderr, /Missing source commit/u);
+ });
+});
diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
index 5aafc02b9..e393af84d 100644
--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs
+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { chmodSync, cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -47,6 +47,8 @@ function runInstaller(home, args, extraEnv = {}, script = installer) {
...process.env,
HOME: home,
OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_INSTALLER_REEXEC: "0",
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
...extraEnv,
},
encoding: "utf8",
@@ -58,7 +60,7 @@ function runInstall(home, harnesses = "cursor,trae,trae-cn,zcode") {
"--harness", harnesses,
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
]);
@@ -86,7 +88,7 @@ test("Kimi installs a self-contained native bundle without legacy config edits",
"--harness", "kimicode",
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
]);
@@ -179,7 +181,7 @@ exit 0
"--harness", "trae-cli",
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], {
@@ -191,6 +193,8 @@ exit 0
assert.doesNotMatch(installed.stdout, /Selected harnesses: codex/u);
assert.match(installed.stdout, /TraeCode CLI 2.0/);
assert.doesNotMatch(installed.stdout, /trae-cli harness is deprecated/);
+ assert.match(installed.stdout, /Removes the deprecated TRAE CLI Hooks integration: ~\/\.trae\/cli\/hooks\.json, ~\/\.trae\/traecli\.toml, ~\/\.openviking\/agent-integrations\/trae-cli\n/);
+ assert.match(installed.stdout, /Uninstall: trae-cli plugin uninstall openviking-memory@openviking && trae-cli plugin marketplace remove openviking\n/);
const hooks = JSON.parse(readFileSync(hooksPath, "utf8"));
assert.ok(hooks.hooks.Stop.some((entry) => JSON.stringify(entry).includes("third-party stop")));
@@ -243,7 +247,7 @@ exit 0
"--harness", "trae-cli",
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], { PATH: `${binDir}:${dirname(installedNode)}:/usr/bin:/bin` });
@@ -290,7 +294,7 @@ exit 0
"--harness", "trae-cli",
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], { PATH: `${binDir}:${dirname(installedNode)}:/usr/bin:/bin` });
@@ -514,7 +518,7 @@ for (const client of ["cursor", "trae", "trae-cn", "zcode"]) {
"--harness", client,
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
]);
@@ -527,6 +531,38 @@ for (const client of ["cursor", "trae", "trae-cn", "zcode"]) {
});
}
+test("validation fails a hook host whose files are missing or whose hook does not run", () => {
+ const home = mkdtempSync(join(tmpdir(), "openviking-validate-hooks-"));
+ try {
+ runInstall(home);
+ const source = readFileSync(installer, "utf8");
+ const prelude = source.slice(0, source.indexOf("# ---------------------------------------------------------------------------\n# Main\n"));
+ const validate = (client) => spawnSync("bash", [], {
+ env: { ...process.env, HOME: home, OPENVIKING_HOME: join(home, ".openviking") },
+ input: `${prelude}\nNODE_BIN="$(command -v node)"\nvalidate_hook_host ${client}\n`,
+ encoding: "utf8",
+ });
+
+ for (const client of ["cursor", "trae", "trae-cn", "zcode"]) {
+ const result = validate(client);
+ assert.equal(result.status, 0, `${client}: ${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, new RegExp(`${client}: hooks and MCP are configured`));
+ }
+
+ rmSync(join(home, ".cursor", "skills", "openviking-skills"), { recursive: true });
+ const incomplete = validate("cursor");
+ assert.equal(incomplete.status, 1);
+ assert.match(incomplete.stdout, /cursor: OpenViking hook or MCP config is incomplete/);
+
+ writeFileSync(join(home, ".openviking", "agent-integrations", "zcode", "scripts", "hook.mjs"), "process.exit(3);\n");
+ const broken = validate("zcode");
+ assert.equal(broken.status, 1);
+ assert.match(broken.stdout, /zcode: installed Hook runtime failed its smoke test/);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+});
+
// The documented uninstall pipes install.sh from a URL, so the running script
// has no lib/ sibling, and the first uninstall drops the assembled copy under
// $OV_HOME. Nothing left to read is not a reason to abort — and never a reason
@@ -542,13 +578,11 @@ test("uninstall with no installer runtime on disk removes what it can and fetche
force: true,
});
const result = runInstaller(home, ["--harness", "cursor", "--uninstall", "--lang", "en", "--yes"], {
- OPENVIKING_REPO_URL: "file:///nonexistent/openviking.git",
- OPENVIKING_REPO_DIR: join(home, "openviking-repo"),
+ OPENVIKING_TOS_BASE: "file:///nonexistent",
}, detached);
const output = `${result.stdout}\n${result.stderr}`;
assert.equal(result.status, 0, output);
- assert.doesNotMatch(output, /Cloning|Refreshing checkout/u, output);
- assert.equal(existsSync(join(home, "openviking-repo")), false);
+ assert.equal(existsSync(join(home, ".openviking", "memory-plugin-marketplace")), false);
assert.equal(existsSync(join(home, ".openviking", "agent-integrations", "cursor")), false);
assert.equal(existsSync(join(home, ".cursor", "rules", "openviking-memory.mdc")), false);
// The host's own files could not be edited, so the uninstall has to name them.
@@ -558,6 +592,47 @@ test("uninstall with no installer runtime on disk removes what it can and fetche
}
});
+// A symlinked OPENVIKING_HOME puts a symlink in every helper path the installer
+// resolves under it; a detached script (no lib/ sibling) reads its helpers
+// from there, as the documented piped uninstall does.
+test("cursor installs and uninstalls through a symlinked OPENVIKING_HOME", () => {
+ const home = mkdtempSync(join(tmpdir(), "openviking-symlinked-home-"));
+ try {
+ const realOvHome = join(home, "real-openviking");
+ mkdirSync(realOvHome);
+ const ovHome = join(home, ".openviking");
+ symlinkSync(realOvHome, ovHome, "dir");
+ const hooksPath = join(home, ".cursor", "hooks.json");
+ const mcpPath = join(home, ".cursor", "mcp.json");
+ const detached = join(home, "install.sh");
+ cpSync(installer, detached);
+
+ const installed = runInstaller(home, [
+ "--harness", "cursor",
+ "--source", "dev",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:9",
+ "--api-key", "",
+ "--yes",
+ ], { OPENVIKING_HOME: ovHome });
+ assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);
+ assert.ok(hookCommands(JSON.parse(readFileSync(hooksPath, "utf8"))).some((command) => command.includes("openviking-memory")));
+ assert.ok(JSON.parse(readFileSync(mcpPath, "utf8")).mcpServers.openviking);
+
+ const removed = runInstaller(home, ["--harness", "cursor", "--uninstall", "--lang", "en", "--yes"], {
+ OPENVIKING_HOME: ovHome,
+ }, detached);
+ assert.equal(removed.status, 0, `${removed.stdout}\n${removed.stderr}`);
+ assert.deepEqual(
+ hookCommands(JSON.parse(readFileSync(hooksPath, "utf8"))).filter((command) => command.includes("openviking-memory")),
+ [],
+ );
+ assert.equal(Boolean(JSON.parse(readFileSync(mcpPath, "utf8")).mcpServers?.openviking), false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+});
+
test("malformed existing agent JSON fails without overwriting user configuration", () => {
const home = mkdtempSync(join(tmpdir(), "openviking-agent-invalid-json-"));
try {
@@ -569,7 +644,7 @@ test("malformed existing agent JSON fails without overwriting user configuration
"--harness", "cursor",
"--source", "dev",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
]);
diff --git a/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
index 50c13027d..b99296537 100644
--- a/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
+++ b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
@@ -125,6 +125,20 @@ test("an empty config is filled in, and a second run changes nothing", () => {
assert.equal(updateOpencodeConfig(first, { pluginSpec: SPEC, mcpProxy: PROXY }), first);
});
+test("an npm registration of the plugin is dropped when the file plugin is written", () => {
+ const next = updateOpencodeConfig([
+ "{",
+ " // keep this user note",
+ ' "plugin": ["@openviking/[email protected]", "some-other-plugin"]',
+ "}",
+ "",
+ ].join("\n"), { pluginSpec: "", mcpProxy: PROXY });
+
+ assert.match(next, /\/\/ keep this user note/);
+ assert.deepEqual(parse(next).plugin, ["some-other-plugin"]);
+ assert.equal(parse(next).mcp.openviking.command[1], PROXY);
+});
+
test("a server the user disabled stays disabled", () => {
const raw = [
"{",
@@ -157,7 +171,7 @@ function runInstaller(args, options, script = installer) {
// The cases above are the editor; this is the wiring. It is the only thing that
// proves install.sh still finds the module and hands it the right three
// arguments now that the editor no longer lives inside the script.
-for (const sourceMode of ["dev", "archive", "remote"]) {
+for (const sourceMode of ["dev", "archive"]) {
test(`the OpenCode ${sourceMode} install loads its entries from clean sources`, async () => {
const dir = await mkdtemp(join(tmpdir(), "ov-opencode-jsonc-"));
try {
@@ -171,28 +185,30 @@ for (const sourceMode of ["dev", "archive", "remote"]) {
await writeFile(opencode, "#!/usr/bin/env sh\nprintf 'opencode 0.0.0-test\\n'\n");
await chmod(opencode, 0o755);
+ // An earlier installer registered the npm package; the file plugin
+ // replaces it rather than loading beside it.
const configPath = join(configDir, "opencode.jsonc");
- await writeFile(configPath, '{\n // keep this user note\n "theme": "system"\n}\n');
+ await writeFile(configPath, `{\n // keep this user note\n "theme": "system",\n "plugin": ["${SPEC}"]\n}\n`);
// Copy only tracked paths from the working tree: no ignored generated
// runtime or node_modules may hide a missing installation step.
const source = join(dir, "source");
- const files = execFileSync("git", ["ls-files", "-z", "--", "examples", "agent-plugins"], { cwd: repoRoot, encoding: "utf8" }).split("\0").filter(Boolean);
+ const files = execFileSync("git", ["ls-files", "-z", "--", "examples", "agent-plugins", ".github/scripts"], { cwd: repoRoot, encoding: "utf8" }).split("\0").filter(Boolean);
for (const file of files) {
mkdirSync(dirname(join(source, file)), { recursive: true });
copyFileSync(join(repoRoot, file), join(source, file));
}
await mkdir(join(source, ".git"));
if (sourceMode === "archive") {
- execFileSync("zip", ["-rq", join(dir, "source.zip"), "source"], { cwd: dir });
+ execFileSync("bash", [join(source, ".github/scripts/stage-memory-plugin-marketplace.sh"), join(dir, "memory-plugin-marketplace")]);
+ execFileSync("zip", ["-rq", join(dir, "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], { cwd: dir });
}
await runInstaller([
"--harness", "opencode",
"--source", sourceMode,
- "--dist", "github",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], {
@@ -201,8 +217,8 @@ for (const sourceMode of ["dev", "archive", "remote"]) {
...process.env,
HOME: home,
OPENVIKING_HOME: join(home, ".openviking"),
- OPENVIKING_MARKETPLACE_ARCHIVE_URL: "",
- OPENVIKING_REPO_ARCHIVE_URL: `file://${join(dir, "source.zip")}`,
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(dir, "memory-plugin-marketplace.zip")}`,
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
PATH: `${bin}:${process.env.PATH}`,
},
}, join(source, "examples/memory-plugin-shared/install.sh"));
@@ -213,12 +229,9 @@ for (const sourceMode of ["dev", "archive", "remote"]) {
assert.match(parse(raw).mcp.openviking.command[1], /servers\/mcp-proxy\.mjs$/);
const installedRoot = join(configDir, "plugins/openviking");
const env = { HOME: home, OPENVIKING_HOME: join(home, ".openviking") };
+ assert.deepEqual(parse(raw).plugin, []);
expectExit(await runHookScript(parse(raw).mcp.openviking.command[1], { cwd: home, env }));
- if (sourceMode !== "remote") {
- expectExit(await runHookScript(join(installedRoot, "index.mjs"), { cwd: home, env }));
- } else {
- assert.deepEqual(parse(raw).plugin, [SPEC]);
- }
+ expectExit(await runHookScript(join(installedRoot, "index.mjs"), { cwd: home, env }));
} finally {
await rm(dir, { recursive: true, force: true });
}
diff --git a/examples/memory-plugin-shared/install-sources.test.mjs b/examples/memory-plugin-shared/install-sources.test.mjs
new file mode 100644
index 000000000..17846c1c3
--- /dev/null
+++ b/examples/memory-plugin-shared/install-sources.test.mjs
@@ -0,0 +1,549 @@
+/**
+ * Where the installer gets what it installs.
+ *
+ * Every file-based harness installs from one release bundle, downloaded once
+ * per run and never through git. Claude Code on its URL marketplace needs no
+ * bundle at all, and neither does its statusline, which resolves the installed
+ * plugin when it runs.
+ */
+
+import assert from "node:assert/strict";
+import { spawn, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const stageScript = join(ROOT, ".github", "scripts", "stage-memory-plugin-marketplace.sh");
+
+// Real path: the installer's Node helpers do nothing when started through a
+// symlinked directory, which the temp directory is on macOS.
+const work = mkdtempSync(join(realpathSync(tmpdir()), "openviking-install-sources-"));
+process.on("exit", () => rmSync(work, { recursive: true, force: true }));
+
+// A copy away from the checkout runs the way `curl | bash` does: no sibling
+// lib/, no dev mode, so everything has to come from the bundle.
+const installer = join(work, "install.sh");
+cpSync(join(ROOT, "examples", "memory-plugin-shared", "install.sh"), installer);
+
+// The bundle sits where the default channel looks for it.
+const tosBase = join(work, "tos");
+mkdirSync(join(tosBase, "releases", "latest"), { recursive: true });
+const staged = spawnSync("bash", [stageScript, join(work, "memory-plugin-marketplace")], { encoding: "utf8" });
+assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);
+const zipped = spawnSync("zip", ["-rq", join(tosBase, "releases", "latest", "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], {
+ cwd: work,
+ encoding: "utf8",
+});
+assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+
+function writeExecutable(file, body) {
+ writeFileSync(file, body, { mode: 0o755 });
+}
+
+function installEnv(home, bin, extraEnv) {
+ return {
+ ...process.env,
+ HOME: home,
+ PATH: `${bin}:${process.env.PATH}`,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_TOS_BASE: `file://${tosBase}`,
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: "",
+ OPENVIKING_INSTALLER_REEXEC: "0",
+ OPENVIKING_REPO_URL: "",
+ OPENVIKING_REPO_REF: "",
+ OPENVIKING_REPO_BRANCH: "",
+ OPENVIKING_CODEX_TOS_GIT_URL: "",
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
+ ...extraEnv,
+ };
+}
+
+function run(home, bin, args, extraEnv = {}) {
+ return spawnSync("bash", [installer, ...args], { cwd: home, env: installEnv(home, bin, extraEnv), encoding: "utf8" });
+}
+
+// For runs that talk to a server in this process, which spawnSync would block.
+function runAsync(home, bin, args, extraEnv = {}) {
+ return new Promise((done) => {
+ const child = spawn("bash", [installer, ...args], { cwd: home, env: installEnv(home, bin, extraEnv) });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("close", (status) => done({ status, stdout, stderr }));
+ });
+}
+
+test("a default install of cursor, zcode and opencode downloads the bundle once and never runs git", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const log = join(home, "calls.log");
+ mkdirSync(bin);
+ const realCurl = spawnSync("bash", ["-c", "command -v curl"], { encoding: "utf8" }).stdout.trim();
+ writeExecutable(join(bin, "git"), `#!/bin/sh\necho "git $*" >> "${log}"\nexit 1\n`);
+ writeExecutable(join(bin, "curl"), `#!/bin/sh\necho "curl $*" >> "${log}"\nexec "${realCurl}" "$@"\n`);
+ writeExecutable(join(bin, "opencode"), "#!/bin/sh\nexit 0\n");
+
+ const result = run(home, bin, [
+ "--harness", "cursor,zcode,opencode", "--lang", "en",
+ "--url", "http://127.0.0.1:9", "--api-key", "", "--yes",
+ ]);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+
+ const calls = existsSync(log) ? readFileSync(log, "utf8").split("\n").filter(Boolean) : [];
+ assert.deepEqual(calls.filter((line) => line.startsWith("git ")), []);
+ assert.equal(calls.filter((line) => line.includes("memory-plugin-marketplace.zip")).length, 1, calls.join("\n"));
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "cursor", "scripts", "hook.mjs")));
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "zcode", "scripts", "hook.mjs")));
+ assert.ok(existsSync(join(home, ".config", "opencode", "plugins", "openviking", "index.mjs")));
+});
+
+// It records its calls and keeps the one marketplace registration the
+// installer reads back; `--version` answers with the URL-marketplace release.
+function writeFakeClaude(bin, dir) {
+ writeExecutable(join(bin, "claude"), `#!/bin/sh
+echo "$*" >> "${dir}/calls.log"
+case "$*" in
+ --version) echo "2.1.224 (Claude Code)" ;;
+ "plugin marketplace list --json") cat "${dir}/marketplaces.json" 2>/dev/null || echo "[]" ;;
+ "plugin marketplace add "*) printf '[{"name":"openviking","path":"%s"}]' "$4" > "${dir}/marketplaces.json" ;;
+esac
+exit 0
+`);
+}
+
+test("a GitHub-channel Claude install moves to TOS, and its statusline follows the installed plugin", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const fake = join(home, "fake-claude");
+ mkdirSync(bin);
+ mkdirSync(fake);
+ writeFakeClaude(bin, fake);
+ const settingsPath = join(home, ".claude", "settings.json");
+ const statusLine = () => JSON.parse(readFileSync(settingsPath, "utf8")).statusLine?.command;
+ const setStatusLine = (command) => {
+ mkdirSync(dirname(settingsPath), { recursive: true });
+ writeFileSync(settingsPath, JSON.stringify({ statusLine: { type: "command", command } }));
+ };
+ const install = (...extra) => {
+ const result = run(home, bin, [
+ "--harness", "claude", "--lang", "en",
+ "--url", "http://127.0.0.1:9", "--api-key", "", "--yes", ...extra,
+ ], { OPENVIKING_TOS_BASE: "https://tos.example.invalid" });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ return result;
+ };
+
+ // The GitHub channel registered a generated directory marketplace. A re-run
+ // re-registers the TOS URL marketplace and leaves the directory alone, since
+ // another Claude-format CLI may still be registered against it.
+ const githubMarketplace = join(home, ".openviking", "marketplaces", "openviking-claude");
+ mkdirSync(join(githubMarketplace, ".claude-plugin"), { recursive: true });
+ writeFileSync(join(githubMarketplace, ".claude-plugin", "marketplace.json"), "{}");
+ writeFileSync(join(fake, "marketplaces.json"), JSON.stringify([{ name: "openviking", path: githubMarketplace }]));
+
+ // A statusline an earlier installer pointed into its clone is repointed on a
+ // plain re-run, with no prompt and no bundle download, and the clone it
+ // leaves unused is pointed out.
+ const clone = join(home, ".openviking", "openviking-repo");
+ mkdirSync(clone, { recursive: true });
+ setStatusLine(`node "${clone}/examples/claude-code-memory-plugin/scripts/statusline.mjs"`);
+ const repointed = install();
+ const command = statusLine();
+ assert.match(command, /installed_plugins\.json/);
+ assert.match(repointed.stdout, /~\/\.claude\/settings\.json \(marketplace auto-update, statusline\)\n/);
+ assert.equal(existsSync(join(home, ".openviking", "memory-plugin-marketplace")), false);
+ assert.match(repointed.stdout, /No longer used by the installer; you can delete it: .*openviking-repo/);
+ assert.ok(existsSync(clone));
+ const calls = readFileSync(join(fake, "calls.log"), "utf8").split("\n");
+ assert.ok(calls.includes("plugin marketplace remove openviking"), calls.join("\n"));
+ assert.ok(calls.includes("plugin marketplace add https://tos.example.invalid/plugins/claude/marketplace.json"), calls.join("\n"));
+ assert.ok(existsSync(githubMarketplace));
+
+ // The command runs whatever copy the registry names, so it follows updates.
+ const configDir = join(home, "claude-config");
+ const runStatusLine = () => spawnSync("sh", ["-c", command], {
+ env: { ...process.env, HOME: home, CLAUDE_CONFIG_DIR: configDir },
+ input: "{}",
+ encoding: "utf8",
+ });
+ const missing = runStatusLine();
+ assert.equal(missing.status, 0, missing.stderr);
+ assert.equal(missing.stdout, "");
+ for (const version of ["1.0.0", "1.0.1"]) {
+ const pluginRoot = join(configDir, "plugins", "cache", "openviking", "openviking-memory", version);
+ mkdirSync(join(pluginRoot, "scripts"), { recursive: true });
+ writeFileSync(join(pluginRoot, "scripts", "statusline.mjs"), `process.stdout.write("statusline ${version}");\n`);
+ writeFileSync(join(configDir, "plugins", "installed_plugins.json"), JSON.stringify({
+ version: 2,
+ plugins: { "openviking-memory@openviking": [{ scope: "user", installPath: pluginRoot, version }] },
+ }));
+ const shown = runStatusLine();
+ assert.equal(shown.status, 0, shown.stderr);
+ assert.equal(shown.stdout, `statusline ${version}`);
+ }
+
+ // Someone else's statusline stays unless the user asks for ours, and so does
+ // one that only wraps ours.
+ setStatusLine("my-statusline");
+ const kept = install();
+ assert.equal(statusLine(), "my-statusline");
+ assert.match(kept.stdout, /~\/\.claude\/settings\.json \(marketplace auto-update\)\n/);
+ const wrapped = `sh -c 'node "${clone}/examples/claude-code-memory-plugin/scripts/statusline.mjs"; echo " | main"'`;
+ setStatusLine(wrapped);
+ install();
+ assert.equal(statusLine(), wrapped);
+ const chinese = install("--statusline", "--lang", "zh");
+ assert.equal(statusLine(), command);
+ assert.match(chinese.stdout, /安装来源: OpenViking 发布版\n/);
+ assert.match(chinese.stdout, /Statusline 已注册(备份:.*settings\.json\.bak\.[0-9-]+)\n/);
+ assert.match(chinese.stdout, /可随时用 export OPENVIKING_STATUSLINE=off 关闭\n/);
+});
+
+test("Claude Code without the plugin command is skipped with an upgrade hint", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const log = join(home, "calls.log");
+ mkdirSync(bin);
+ writeExecutable(join(bin, "claude"), `#!/bin/sh
+echo "$*" >> "${log}"
+case "$*" in
+ --version) echo "1.0.128 (Claude Code)" ;;
+ plugin*) exit 1 ;;
+esac
+exit 0
+`);
+
+ const result = run(home, bin, [
+ "--harness", "claude", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes",
+ ], { OPENVIKING_TOS_BASE: "https://tos.example.invalid" });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /Skipping claude: it has no 'plugin' command\. The plugin needs Claude Code 2\.0 or newer/);
+ // Neither the review nor the next steps offer commands it cannot run.
+ assert.doesNotMatch(result.stdout, /claude plugin/);
+ const calls = readFileSync(log, "utf8").split("\n").filter(Boolean);
+ assert.deepEqual(calls.filter((line) => !["--version", "plugin --help"].includes(line)), []);
+ assert.equal(existsSync(join(home, ".claude", "settings.json")), false);
+ assert.equal(existsSync(join(home, ".openviking", "memory-plugin-marketplace")), false);
+});
+
+// It records its calls and keeps the one marketplace registration the
+// installer reads back; FAKE_CODEX_GIT_FAILS makes adding a git marketplace fail.
+function writeFakeCodex(bin, dir) {
+ writeExecutable(join(bin, "codex"), `#!/bin/sh
+echo "$*" >> "${dir}/calls.log"
+case "$*" in
+ "plugin marketplace list --json") cat "${dir}/marketplaces.json" 2>/dev/null || echo '{"marketplaces":[]}' ;;
+ "plugin marketplace remove "*) rm -f "${dir}/marketplaces.json" ;;
+ "plugin marketplace add "*)
+ case "$4" in *.git) [ -z "$FAKE_CODEX_GIT_FAILS" ] || { echo "fatal: git marketplace unreachable" >&2; exit 1; } ;; esac
+ printf '{"marketplaces":[{"name":"openviking","marketplaceSource":{"source":"%s"}}]}' "$4" > "${dir}/marketplaces.json" ;;
+ "plugin list") echo "openviking-memory@openviking" ;;
+esac
+exit 0
+`);
+}
+
+// The fake leaves no plugin cache behind, which validation has to tolerate.
+test("Codex moves to the TOS git marketplace, falls back to the bundle, and says how it updates", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const fake = join(home, "fake-codex");
+ mkdirSync(bin);
+ mkdirSync(fake);
+ writeFakeCodex(bin, fake);
+ const install = (extraEnv) => {
+ rmSync(join(fake, "calls.log"), { force: true });
+ const result = run(home, bin, [
+ "--harness", "codex", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes",
+ ], extraEnv);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ return { stdout: result.stdout, calls: readFileSync(join(fake, "calls.log"), "utf8").split("\n") };
+ };
+
+ // A marketplace the GitHub channel registered is re-registered from TOS.
+ writeFileSync(join(fake, "marketplaces.json"), JSON.stringify({
+ marketplaces: [{ name: "openviking", marketplaceSource: { source: "https://github.com/volcengine/OpenViking.git" } }],
+ }));
+ const moved = install();
+ assert.ok(moved.calls.includes("plugin marketplace remove openviking"), moved.calls.join("\n"));
+ assert.ok(moved.calls.includes(`plugin marketplace add file://${tosBase}/plugins/memory-plugins.git`), moved.calls.join("\n"));
+ assert.match(moved.stdout, /Codex\n {4}Next: .*\n {4}Updates: automatic; Codex upgrades the marketplace when it starts\n/);
+ assert.match(moved.stdout, /Uninstall: codex plugin remove openviking-memory@openviking && codex plugin marketplace remove openviking\n/);
+ assert.match(readFileSync(join(home, ".codex", "config.toml"), "utf8"), /\[plugins\."openviking-memory@openviking"\]\nenabled = true/);
+ assert.equal(existsSync(join(home, ".openviking", "memory-plugin-marketplace")), false);
+
+ // A git marketplace that cannot be added gives way to the bundle's directory.
+ rmSync(join(fake, "marketplaces.json"));
+ const fallback = install({ FAKE_CODEX_GIT_FAILS: "1" });
+ assert.match(fallback.stdout, /TOS git marketplace unavailable; falling back to the archive directory/);
+ assert.ok(fallback.calls.includes(`plugin marketplace add ${join(home, ".openviking", "memory-plugin-marketplace")}`), fallback.calls.join("\n"));
+ assert.match(fallback.stdout, /Codex\n {4}Next: .*\n {4}Updates: re-run this installer\n/);
+});
+
+// macOS ships bash 3.2 as /bin/bash, which runs the ERR trap for a failing
+// `command <program>` even where the failure is handled.
+test("a handled CLI failure neither reports itself nor disarms the error report", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const fake = join(home, "fake-codex");
+ mkdirSync(bin);
+ mkdirSync(fake);
+ writeFakeCodex(bin, fake);
+ const install = () => spawnSync("/bin/bash", [
+ installer, "--harness", "codex", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes",
+ ], { cwd: home, env: installEnv(home, bin, { CODEX_HOME: join(home, ".codex"), FAKE_CODEX_GIT_FAILS: "1" }), encoding: "utf8" });
+
+ const fellBack = install();
+ assert.equal(fellBack.status, 0, `${fellBack.stdout}\n${fellBack.stderr}`);
+ assert.doesNotMatch(fellBack.stderr, /stopped unexpectedly|unreachable/);
+ const calls = readFileSync(join(fake, "calls.log"), "utf8").split("\n");
+ assert.ok(calls.includes(`plugin marketplace add ${join(home, ".openviking", "memory-plugin-marketplace")}`), calls.join("\n"));
+
+ // A real failure later in the same run is still reported.
+ const config = join(home, ".codex", "config.toml");
+ rmSync(config);
+ mkdirSync(config);
+ const failed = install();
+ assert.equal(failed.status, 1, `${failed.stdout}\n${failed.stderr}`);
+ assert.equal(failed.stderr.match(/OpenViking installer stopped unexpectedly/g)?.length, 1, failed.stderr);
+ assert.match(failed.stderr, /Command: node /);
+});
+
+test("Claude Code and Codex files go where CLAUDE_CONFIG_DIR and CODEX_HOME point", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const fakeClaude = join(home, "fake-claude");
+ const fakeCodex = join(home, "fake-codex");
+ mkdirSync(bin);
+ mkdirSync(fakeClaude);
+ mkdirSync(fakeCodex);
+ writeFakeClaude(bin, fakeClaude);
+ writeFakeCodex(bin, fakeCodex);
+ const claudeDir = join(home, "claude-config");
+ const codexDir = join(home, "codex-home");
+ const cachedProxy = join(codexDir, "plugins", "cache", "openviking", "openviking-memory", "1.0.0", "servers", "mcp-proxy.mjs");
+ mkdirSync(dirname(cachedProxy), { recursive: true });
+ writeFileSync(cachedProxy, "");
+
+ const result = run(home, bin, [
+ "--harness", "claude,codex", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--statusline", "--yes",
+ ], { OPENVIKING_TOS_BASE: "https://tos.example.invalid", CLAUDE_CONFIG_DIR: claudeDir, CODEX_HOME: codexDir });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+
+ const settings = JSON.parse(readFileSync(join(claudeDir, "settings.json"), "utf8"));
+ assert.equal(settings.extraKnownMarketplaces.openviking.autoUpdate, true);
+ assert.match(settings.statusLine.command, /installed_plugins\.json/);
+ assert.match(readFileSync(join(codexDir, "config.toml"), "utf8"), /\[plugins\."openviking-memory@openviking"\]\nenabled = true/);
+ assert.ok(result.stdout.includes(`codex: cached stdio proxy parses (${cachedProxy})`), result.stdout);
+ assert.equal(existsSync(join(home, ".claude")), false);
+ assert.equal(existsSync(join(home, ".codex")), false);
+});
+
+test("retired GitHub-channel options are accepted, announced and ignored", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ mkdirSync(bin);
+ const notice = /The GitHub install channel was removed and its options are ignored/;
+ const install = (args, extraEnv) => run(home, bin, [
+ "--harness", "cursor", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes", ...args,
+ ], extraEnv);
+
+ for (const [args, extraEnv] of [
+ [["--dist", "github"], {}],
+ [["--source", "remote"], {}],
+ [[], { OPENVIKING_REPO_REF: "my-branch" }],
+ ]) {
+ const result = install(args, extraEnv);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, notice);
+ assert.match(result.stdout, /Source: OpenViking release\n/);
+ }
+ const tos = install(["--dist", "tos"]);
+ assert.equal(tos.status, 0, `${tos.stdout}\n${tos.stderr}`);
+ assert.doesNotMatch(tos.stdout, notice);
+ assert.equal(install(["--dist", "gitlab"]).status, 2);
+});
+
+test("the installer runs when bash reads it from stdin", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ mkdirSync(bin);
+ const piped = (args) => spawnSync("/bin/bash", ["-s", "--", ...args], {
+ cwd: home,
+ env: installEnv(home, bin, {}),
+ input: readFileSync(installer),
+ encoding: "utf8",
+ });
+
+ const help = piped(["--help"]);
+ assert.equal(help.status, 0, help.stderr);
+ assert.match(help.stdout, /^Usage: install\.sh/);
+ const installed = piped(["--harness", "cursor", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes"]);
+ assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "cursor", "scripts", "hook.mjs")));
+});
+
+test("a copy that is not a release build runs the release installer", () => {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ mkdirSync(bin);
+ const release = join(home, "tos", "memory-plugin-shared", "install.sh");
+ mkdirSync(dirname(release), { recursive: true });
+ const args = ["--harness", "cursor", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes"];
+ // A lib/install beside the script would be taken for the installer's own
+ // helpers, so the release copy runs alone in a directory it then removes.
+ const tmp = join(home, "tmp");
+ mkdirSync(join(tmp, "lib", "install"), { recursive: true });
+ const reexec = { OPENVIKING_INSTALLER_REEXEC: "", OPENVIKING_TOS_BASE: `file://${join(home, "tos")}`, TMPDIR: tmp };
+
+ writeFileSync(release, [
+ "#!/usr/bin/env bash",
+ "# OpenViking Memory Plugin shared installer (release stand-in)",
+ 'printf \'%s|\' "$OPENVIKING_INSTALLER_REEXEC" "$@" "$(ls -A "$(dirname "$0")")"',
+ "exit 7",
+ "",
+ ].join("\n"));
+ const handed = run(home, bin, args, reexec);
+ assert.equal(handed.status, 7, handed.stderr);
+ assert.equal(handed.stdout, ["0", "--dist", "tos", ...args, "install.sh", ""].join("|"));
+ assert.deepEqual(readdirSync(tmp), ["lib"]);
+
+ // Anything that is not the installer, such as an error page, is not run.
+ writeFileSync(release, "<html>503 Service Unavailable</html>\n");
+ cpSync(join(tosBase, "releases"), join(home, "tos", "releases"), { recursive: true });
+ const kept = run(home, bin, args, reexec);
+ assert.equal(kept.status, 0, `${kept.stdout}\n${kept.stderr}`);
+ assert.match(kept.stdout, /Could not fetch the release installer; continuing with this copy/);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "cursor", "scripts", "hook.mjs")));
+});
+
+// The release resolver: a local stand-in for the install site answers each
+// harness from `answers`, and every request lands in `requests`.
+const pinnedZip = join(tosBase, "releases", "v9.9.9", "memory-plugin-marketplace.zip");
+mkdirSync(dirname(pinnedZip), { recursive: true });
+cpSync(join(tosBase, "releases", "latest", "memory-plugin-marketplace.zip"), pinnedZip);
+const pinnedSha256 = createHash("sha256").update(readFileSync(pinnedZip)).digest("hex");
+const pinnedGit = `file://${tosBase}/plugins/v9.9.9/memory-plugins.git`;
+
+let answers = {};
+const requests = [];
+const site = createServer((req, res) => {
+ requests.push({ path: req.url, agent: req.headers["user-agent"] });
+ const answer = answers[req.url.replace(/^\/install\/v1\/(.*)\.json$/, "$1")] ?? { status: 404, body: {} };
+ res.writeHead(answer.status, { "content-type": "application/json" });
+ res.end(JSON.stringify(answer.body));
+});
+await new Promise((ready) => site.listen(0, "127.0.0.1", ready));
+test.after(() => site.close());
+const siteEnv = { OPENVIKING_INSTALL_SITE: `http://127.0.0.1:${site.address().port}`, OPENVIKING_SKIP_VERSION_CHECK: "" };
+
+function bundleAnswer(overrides = {}) {
+ return {
+ status: 200,
+ body: {
+ schema: 1,
+ harness: "cursor",
+ version: "9.9.9",
+ bundle_url: `file://${pinnedZip}`,
+ sha256: pinnedSha256,
+ source_url: `file://${tosBase}/releases/v9.9.9/openviking-source.zip`,
+ source_sha256: pinnedSha256,
+ ...overrides,
+ },
+ };
+}
+
+function resolverHome() {
+ const home = mkdtempSync(join(work, "home-"));
+ const bin = join(home, "bin");
+ const log = join(home, "curl.log");
+ mkdirSync(bin);
+ const realCurl = spawnSync("bash", ["-c", "command -v curl"], { encoding: "utf8" }).stdout.trim();
+ writeExecutable(join(bin, "curl"), `#!/bin/sh\necho "curl $*" >> "${log}"\nexec "${realCurl}" "$@"\n`);
+ const downloads = () => readFileSync(log, "utf8").split("\n").filter((line) => line.includes("memory-plugin-marketplace.zip"));
+ return { home, bin, downloads };
+}
+
+const cursorArgs = ["--harness", "cursor", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes"];
+const latestZip = `file://${tosBase}/releases/latest/memory-plugin-marketplace.zip`;
+
+test("the resolver pins the release each harness installs, asked for under its public name", async () => {
+ const { home, bin, downloads } = resolverHome();
+ const traeLog = join(home, "trae-cli.log");
+ writeExecutable(join(bin, "trae-cli"), `#!/bin/sh
+echo "$*" >> "${traeLog}"
+case "$*" in
+ "plugin marketplace list --json") echo "[]" ;;
+ "plugin list") echo "openviking-memory" ;;
+esac
+exit 0
+`);
+ answers = {
+ cursor: bundleAnswer(),
+ "trae-cli": { status: 200, body: { schema: 1, harness: "trae-cli", version: "9.9.9", git_url: pinnedGit } },
+ };
+ requests.length = 0;
+
+ const result = await runAsync(home, bin, [
+ "--harness", "cursor,trae-cli", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes",
+ ], siteEnv);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+
+ assert.deepEqual(requests.map((r) => r.path).sort(), ["/install/v1/cursor.json", "/install/v1/trae-cli.json"]);
+ for (const { agent } of requests) assert.match(agent, /^openviking-installer\/dev \((darwin|linux); [^;)]+\)$/);
+ assert.equal(downloads().length, 1);
+ assert.match(downloads()[0], /releases\/v9\.9\.9\/memory-plugin-marketplace\.zip/);
+ assert.ok(readFileSync(traeLog, "utf8").split("\n").includes(`plugin marketplace add ${pinnedGit}`));
+ assert.match(result.stdout, /Release: 9\.9\.9/);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "cursor", "scripts", "hook.mjs")));
+});
+
+test("an unavailable or untrusted resolver answer falls back to the latest release without a word", async () => {
+ for (const answer of [
+ { status: 503, body: { error: "unavailable" } },
+ bundleAnswer({ bundle_url: "https://elsewhere.example.invalid/memory-plugin-marketplace.zip" }),
+ bundleAnswer({ source_url: "https://elsewhere.example.invalid/openviking-source.zip" }),
+ bundleAnswer({ schema: 2 }),
+ ]) {
+ const { home, bin, downloads } = resolverHome();
+ answers = { cursor: answer };
+ requests.length = 0;
+ const result = await runAsync(home, bin, cursorArgs, siteEnv);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.equal(requests.length, 1);
+ assert.deepEqual(downloads().map((line) => line.split(" ").pop()), [latestZip]);
+ assert.doesNotMatch(`${result.stdout}${result.stderr}`, /install\/v1|elsewhere|Release:/);
+ }
+});
+
+test("a bundle that does not match the resolver's checksum is not installed", async () => {
+ answers = { cursor: bundleAnswer({ sha256: "0".repeat(64) }) };
+ const { home, bin } = resolverHome();
+ const mismatch = await runAsync(home, bin, cursorArgs, siteEnv);
+ assert.equal(mismatch.status, 1, `${mismatch.stdout}\n${mismatch.stderr}`);
+ assert.match(mismatch.stderr, /does not match the checksum the release published/);
+ assert.match(mismatch.stderr, new RegExp(`got ${pinnedSha256}`));
+ assert.equal(existsSync(join(home, ".openviking", "memory-plugin-marketplace")), false);
+ assert.equal(existsSync(join(home, ".openviking", "agent-integrations", "cursor")), false);
+
+ // An explicit bundle URL replaces the resolver's, checksum included.
+ const overridden = await runAsync(home, bin, cursorArgs, { ...siteEnv, OPENVIKING_MARKETPLACE_ARCHIVE_URL: latestZip });
+ assert.equal(overridden.status, 0, `${overridden.stdout}\n${overridden.stderr}`);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", "cursor", "scripts", "hook.mjs")));
+});
+
+test("OPENVIKING_SKIP_VERSION_CHECK skips the version check", async () => {
+ answers = { cursor: bundleAnswer() };
+ requests.length = 0;
+ const { home, bin, downloads } = resolverHome();
+ const result = await runAsync(home, bin, cursorArgs, { ...siteEnv, OPENVIKING_SKIP_VERSION_CHECK: "1" });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.deepEqual(requests, []);
+ assert.deepEqual(downloads().map((line) => line.split(" ").pop()), [latestZip]);
+});
diff --git a/examples/memory-plugin-shared/install-tui.test.mjs b/examples/memory-plugin-shared/install-tui.test.mjs
index 4f5738370..be55e3863 100644
--- a/examples/memory-plugin-shared/install-tui.test.mjs
+++ b/examples/memory-plugin-shared/install-tui.test.mjs
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { spawn, spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -11,15 +12,36 @@ const installerSource = readFileSync(installer, "utf8");
const mainMarker = "# ---------------------------------------------------------------------------\n# Main\n";
const installerPrelude = installerSource.slice(0, installerSource.indexOf(mainMarker));
-function runInstallerPrelude(body) {
+// An `undefined` value removes the variable from the child's environment.
+function preludeEnv(env) {
+ const merged = { ...process.env, OPENVIKING_LANG: "en", ...env };
+ for (const [key, value] of Object.entries(merged)) if (value === undefined) delete merged[key];
+ return merged;
+}
+
+function runInstallerPrelude(body, env = {}) {
return spawnSync("/bin/bash", [], {
encoding: "utf8",
- env: { ...process.env, OPENVIKING_LANG: "en" },
+ env: preludeEnv(env),
input: `${installerPrelude}\n${body}\n`,
timeout: 10_000,
});
}
+// For bodies that talk to a server in this process, which spawnSync would
+// block.
+function runInstallerPreludeAsync(body, env = {}) {
+ return new Promise((resolve) => {
+ const child = spawn("/bin/bash", [], { env: preludeEnv(env) });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ child.stdin.end(`${installerPrelude}\n${body}\n`);
+ });
+}
+
function makeTempHome(t) {
const home = mkdtempSync(join(tmpdir(), "openviking-trae-"));
t.after(() => rmSync(home, { recursive: true, force: true }));
@@ -184,7 +206,8 @@ INTERACTIVE=1
OV_HOME=${JSON.stringify(home)}
OVCLI_CONF=${JSON.stringify(conf)}
exec 3< <(printf '\\n')
-configure_ovcli
+gather_credentials
+write_ovcli
`);
assert.equal(result.status, 0, result.stderr);
@@ -209,6 +232,16 @@ test("menu digit shortcuts move the cursor instead of confirming", () => {
assert.match(chooseFormat[0], /^ +2\) cursor=1 ;;$/m);
});
+test("q at the install confirmation cancels rather than taking the default", () => {
+ // Every other menu keeps its default on q; here the default is Proceed.
+ const menu = /^tui_menu\(\) \{[\s\S]*?^\}$/m.exec(installerSource);
+ assert.ok(menu, "tui_menu not found");
+ assert.match(menu[0], /^ +q\|Q\) cursor="\$\{TUI_MENU_QUIT:-\$def\}"; break ;;$/m);
+ const confirm = /^confirm_plan\(\) \{$[\s\S]*?^\}$/m.exec(installerSource);
+ assert.ok(confirm, "confirm_plan not found");
+ assert.match(confirm[0], /TUI_MENU_QUIT=1 tui_menu "[^\n]*" 0 "\$\(t 'Proceed' '继续'\)" "\$\(t 'Cancel' '取消'\)"$/m);
+});
+
test("an empty element in a comma-separated list is skipped, not fatal", () => {
// Assignments, like the call sites: a trailing comma used to make the loop --
// and so the function -- exit 1, which `set -e` turned into an abort.
@@ -235,7 +268,8 @@ INTERACTIVE=1
OV_HOME=${JSON.stringify(home)}
OVCLI_CONF=${JSON.stringify(conf)}
exec 3< <(printf 'rotated-key\\n')
-configure_ovcli
+gather_credentials
+write_ovcli
`);
assert.equal(result.status, 0, result.stderr);
@@ -243,3 +277,266 @@ configure_ovcli
assert.match(result.stdout, /Updated: api_key: stor…-key \(10\) -> rota…-key \(11\)/);
assert.equal(JSON.parse(readFileSync(conf, "utf8")).api_key, "rotated-key");
});
+
+test("the API key reaches ovcli.conf without passing through a process argument", (t) => {
+ const home = makeTempHome(t);
+ const bin = join(home, "bin");
+ mkdirSync(bin);
+ const log = join(home, "node.log");
+ writeFileSync(join(bin, "node"), `#!/bin/sh\necho "$*" >> "${log}"\nexec "${process.execPath}" "$@"\n`, { mode: 0o755 });
+ const conf = join(home, "ovcli.conf");
+
+ const result = runInstallerPrelude(`
+OV_HOME=${JSON.stringify(home)}
+OVCLI_CONF=${JSON.stringify(conf)}
+CRED_URL="https://example.invalid/openviking"
+CRED_KEY="secret-api-key"
+CRED_ACCOUNT="acct"
+CRED_USER="usr"
+write_ovcli
+`, { PATH: `${bin}:${process.env.PATH}` });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(JSON.parse(readFileSync(conf, "utf8")), {
+ url: "https://example.invalid/openviking",
+ api_key: "secret-api-key",
+ account: "acct",
+ user: "usr",
+ });
+ const calls = readFileSync(log, "utf8");
+ assert.match(calls, /ovcli\.conf/);
+ assert.doesNotMatch(calls, /secret-api-key/);
+});
+
+test("a first-time setup offers the local server first", () => {
+ const result = runInstallerPrelude(`
+tui_menu() { TUI_MENU_CHOICE="$2"; }
+INTERACTIVE=1
+exec 3< <(printf '\\n')
+prompt_connection "" ""
+printf '%s|%s\\n' "$WIZ_URL" "$WIZ_KEY"
+`);
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trim().split("\n").pop(), "http://127.0.0.1:1933|");
+});
+
+test("the language follows --lang, OPENVIKING_LANG, the locale, then the macOS setting", (t) => {
+ const fake = makeTempHome(t);
+ writeFileSync(join(fake, "uname"), '#!/bin/sh\nprintf \'%s\\n\' "$FAKE_UNAME"\n', { mode: 0o755 });
+ writeFileSync(join(fake, "defaults"), [
+ "#!/bin/sh",
+ '[ "$*" = "read -g AppleLocale" ] && [ -n "$FAKE_APPLE_LOCALE" ] || exit 1',
+ 'printf \'%s\\n\' "$FAKE_APPLE_LOCALE"',
+ "",
+ ].join("\n"), { mode: 0o755 });
+ const detect = (env, langArg = "") => {
+ const result = runInstallerPrelude(`
+LANG_ARG=${JSON.stringify(langArg)}
+select_language
+printf '%s\\n' "$UI_LANG"
+`, {
+ OPENVIKING_LANG: undefined,
+ LC_ALL: undefined,
+ LANG: undefined,
+ FAKE_UNAME: "Darwin",
+ FAKE_APPLE_LOCALE: "zh_CN",
+ PATH: `${fake}:/usr/bin:/bin`,
+ ...env,
+ });
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout.trim();
+ };
+
+ assert.equal(detect({ OPENVIKING_LANG: "zh" }, "en"), "en");
+ assert.equal(detect({ OPENVIKING_LANG: "zh", LC_ALL: "en_US.UTF-8" }), "zh");
+ assert.equal(detect({ OPENVIKING_LANG: "en", LANG: "zh_CN.UTF-8" }), "en");
+ assert.equal(detect({ LC_ALL: "zh_CN.UTF-8", LANG: "en_US.UTF-8" }), "zh");
+ assert.equal(detect({ LANG: "zh_TW.UTF-8" }), "zh");
+ assert.equal(detect({ LANG: "en_US.UTF-8" }), "en");
+ assert.equal(detect({ LANG: "C" }), "zh");
+ assert.equal(detect({ LC_ALL: "POSIX" }), "zh");
+ assert.equal(detect({ FAKE_APPLE_LOCALE: "zh-Hans_CN" }), "zh");
+ assert.equal(detect({ FAKE_APPLE_LOCALE: "" }), "en");
+ assert.equal(detect({ FAKE_UNAME: "Linux" }), "en");
+});
+
+test("the server check tells an unreachable server, a rejected key and other failures apart", async (t) => {
+ const key = 'good"key\\';
+ const seen = [];
+ const server = createServer((req, res) => {
+ const [, scenario, ...rest] = req.url.split("/");
+ seen.push({ path: `/${rest.join("/")}`, headers: req.headers });
+ let status = 200;
+ if (rest.join("/") === "api/v1/system/status") {
+ if (scenario === "authed") status = req.headers.authorization === `Bearer ${key}` ? 200 : 401;
+ if (scenario === "broken") status = 500;
+ }
+ res.writeHead(status, { "Content-Type": "application/json" });
+ res.end("{}");
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+ const base = `http://127.0.0.1:${server.address().port}`;
+ const closed = createServer();
+ await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
+ const unreachable = `http://127.0.0.1:${closed.address().port}`;
+ await new Promise((resolve) => closed.close(resolve));
+
+ // Every curl call is logged, so the key can be checked to stay out of argv.
+ const bin = makeTempHome(t);
+ const log = join(bin, "curl.log");
+ const realCurl = spawnSync("bash", ["-c", "command -v curl"], { encoding: "utf8" }).stdout.trim();
+ writeFileSync(join(bin, "curl"), `#!/bin/sh\necho "$*" >> "${log}"\nexec "${realCurl}" "$@"\n`, { mode: 0o755 });
+
+ const result = await runInstallerPreludeAsync(`
+for target in "${base}/open||" "${base}/authed|$PROBE_KEY|acct" "${base}/authed|wrong|" "${base}/authed||" "${base}/broken||" "${unreachable}||"; do
+ IFS='|' read -r url key account <<PROBE
+$target
+PROBE
+ probe_server "$url/" "$key" "$account" "usr"
+ printf '%s:%s\\n' "$PROBE_RESULT" "$PROBE_CODE"
+done
+`, { PROBE_KEY: key, PATH: `${bin}:${process.env.PATH}` });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.stdout.trim().split("\n"), [
+ "ok:200",
+ "ok:200",
+ "rejected:401",
+ "key-required:401",
+ "http:500",
+ "unreachable:000",
+ ]);
+ const authed = seen.find((req) => req.headers.authorization === `Bearer ${key}`);
+ assert.equal(authed.headers["x-openviking-account"], "acct");
+ assert.equal(authed.headers["x-openviking-user"], "usr");
+ assert.ok(seen.filter((req) => req.path === "/health").every((req) => !req.headers.authorization));
+ assert.doesNotMatch(readFileSync(log, "utf8"), /good|wrong/);
+});
+
+test("re-entering after a failed server check probes the new values", async (t) => {
+ const server = createServer((req, res) => {
+ res.writeHead(req.headers.authorization === "Bearer fresh-key" || req.url.endsWith("/health") ? 200 : 401);
+ res.end("{}");
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+ const url = `http://127.0.0.1:${server.address().port}`;
+
+ // First answer: re-enter; then the custom-URL arm, whose prompt keeps the URL.
+ const result = await runInstallerPreludeAsync(`
+MENU_ANSWERS="0 2"
+tui_menu() { set -- $MENU_ANSWERS; TUI_MENU_CHOICE="$1"; shift; MENU_ANSWERS="$*"; }
+INTERACTIVE=1
+exec 3< <(printf '\\nfresh-key\\n')
+CRED_URL=${JSON.stringify(url)}
+CRED_KEY="stale-key"
+check_server
+printf '%s|%s|%s\\n' "$PROBE_RESULT" "$CRED_URL" "$CRED_KEY"
+`);
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /The server rejected the API key \(HTTP 401\)\./);
+ assert.equal(result.stdout.trim().split("\n").pop(), `ok|${url}|fresh-key`);
+});
+
+// A copy away from the checkout, so the run is not in dev mode and the
+// release installer is not fetched.
+function detachedInstaller(t, transform = (source) => source) {
+ const dir = mkdtempSync(join(realpathSync(tmpdir()), "openviking-flow-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const home = join(dir, "home");
+ const bin = join(home, "bin");
+ mkdirSync(bin, { recursive: true });
+ const script = join(dir, "install.sh");
+ writeFileSync(script, transform(installerSource));
+ const dshLog = join(dir, "dsh.log");
+ writeFileSync(join(bin, "dsh"), `#!/bin/sh\necho "$*" >> "${dshLog}"\necho "@openviking/dsh-memory-plugin openviking-memory-runtime"\n`, { mode: 0o755 });
+ // Nothing here downloads, and a curl that cannot connect keeps the server
+ // check away from whatever listens on the default port.
+ writeFileSync(join(bin, "curl"), "#!/bin/sh\nexit 7\n", { mode: 0o755 });
+ const run = (args) => spawnSync("bash", [script, ...args], {
+ cwd: home,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: `${bin}:${process.env.PATH}`,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_TOS_BASE: "https://tos.example.invalid",
+ OPENVIKING_INSTALLER_REEXEC: "0",
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
+ },
+ timeout: 30_000,
+ });
+ return { home, dshLog, run };
+}
+
+test("cancelling at the confirmation leaves the machine untouched", (t) => {
+ // Drive the interactive flow without a terminal: every menu takes its
+ // default except the confirmation, which is cancelled.
+ const { home, dshLog, run } = detachedInstaller(t, (source) => source.replace(mainMarker, `INTERACTIVE=1
+exec 3</dev/null
+tui_menu() {
+ TUI_MENU_CHOICE="$2"
+ case "$1" in *Proceed*) TUI_MENU_CHOICE=1 ;; esac
+}
+${mainMarker}`));
+
+ const result = run(["--harness", "cursor,dsh", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "secret-api-key"]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, /\[2\/5\] Review/);
+ assert.match(result.stdout, /~\/\.cursor\/hooks\.json/);
+ assert.match(result.stdout, /Shared hook runtime: ~\/\.openviking\/agent-integrations\/memory-plugin-shared\n/);
+ assert.match(result.stdout, /Cancelled; nothing was changed\./);
+ assert.doesNotMatch(`${result.stdout}${result.stderr}`, /secret-api-key/);
+ assert.deepEqual(readdirSync(home), ["bin"]);
+ assert.equal(existsSync(dshLog), false);
+});
+
+test("the statusline is asked about before the review, which lists it only when chosen", (t) => {
+ for (const [answer, listed] of [
+ [0, /~\/\.claude\/settings\.json \(marketplace auto-update, statusline\)\n/],
+ [1, /~\/\.claude\/settings\.json \(marketplace auto-update\)\n/],
+ ]) {
+ const { home, run } = detachedInstaller(t, (source) => source.replace(mainMarker, `INTERACTIVE=1
+exec 3</dev/null
+tui_menu() {
+ printf 'menu: %s\\n' "$1"
+ TUI_MENU_CHOICE="$2"
+ case "$1" in *statusline*) TUI_MENU_CHOICE=${answer} ;; *Proceed*) TUI_MENU_CHOICE=1 ;; esac
+}
+${mainMarker}`));
+ writeFileSync(join(home, "bin", "claude"), '#!/bin/sh\n[ "$1" != --version ] || echo "2.1.224 (Claude Code)"\n', { mode: 0o755 });
+
+ const result = run(["--harness", "claude", "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", ""]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ const asked = result.stdout.indexOf("menu: Enable the OpenViking statusline?");
+ assert.ok(asked !== -1 && asked < result.stdout.indexOf("] Review"), result.stdout);
+ assert.match(result.stdout, listed);
+ assert.match(result.stdout, /Cancelled; nothing was changed\./);
+ }
+});
+
+test("a non-interactive run with no server says so and how to re-run", (t) => {
+ const { home, run } = detachedInstaller(t);
+ const notice = /No server was given: the plugin is configured for http:\/\/127\.0\.0\.1:1933 without an API key\./;
+
+ const result = run(["--harness", "dsh", "--lang", "en", "--yes"]);
+
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.match(result.stdout, notice);
+ assert.ok(result.stdout.indexOf("Review") < result.stdout.search(notice));
+ assert.match(result.stdout, /install\.sh\) --yes --harness dsh --url <server-url> --api-key <api-key>/);
+ assert.match(result.stdout, /\[4\/4\] Validation/);
+ assert.match(result.stdout, /DeepSeek Harness\n {4}Next: .*\n {4}Updates: re-run this installer\n {4}Uninstall: dsh plugin --profile web rm @openviking\/dsh-memory-plugin/);
+ assert.equal(JSON.parse(readFileSync(join(home, ".openviking", "ovcli.conf"), "utf8")).url, "http://127.0.0.1:1933");
+
+ // Once a server is configured, a re-run has nothing to warn about.
+ const again = run(["--harness", "dsh", "--lang", "en", "--yes"]);
+ assert.equal(again.status, 0, `${again.stdout}\n${again.stderr}`);
+ assert.doesNotMatch(again.stdout, notice);
+});
diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.sh
index 45c995852..ae33c6167 100644
--- a/examples/memory-plugin-shared/install.sh
+++ b/examples/memory-plugin-shared/install.sh
@@ -1,57 +1,108 @@
#!/usr/bin/env bash
#
# OpenViking Memory Plugin shared installer for Claude Code, Codex, Cursor,
-# TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, Kimi Code, OpenCode, and pi.
+# TRAE / TRAE CN, TraeCode CLI 2.0, ZCode, Kimi Code, OpenCode, pi and
+# DeepSeek Harness (dsh).
#
-# One-liner (GitHub):
-# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
-# One-liner (TOS mirror, for regions where GitHub is unreachable):
-# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos
-# Non-interactive:
-# bash install.sh --harness claude,codex,cursor,trae,trae-cn,trae-cli,zcode,kimicode,opencode,pi,dsh --dist github --lang en --url http://127.0.0.1:1933
-# Format-compatible CLI aliases:
-# bash install.sh --harness trae-cli
-# bash install.sh --harness claude --claude-bin claude,seed
-# Fork / branch verification:
-# OPENVIKING_REPO_URL=https://github.com/you/OpenViking.git \
-# OPENVIKING_REPO_REF=my-branch bash install.sh --source remote
+# In short:
+# - Open source. This script and every OpenViking plugin file it installs are
+# built from https://github.com/volcengine/OpenViking (AGPL-3.0, 38,930
+# GitHub stars on 2026-09-29) by its release workflow.
+# - It installs the OpenViking memory plugin into the agents you pick and
+# points it at your OpenViking server.
+# - It lists every change and asks before making any. With --yes, or without
+# a terminal, it prints the same list and proceeds. No sudo. With default
+# settings nothing is written outside $HOME except temporary files.
#
-# 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).
+# Install without prompts:
+# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+# --yes --url <server-url> --api-key <api-key>
+# The server URL and API key come from the user; without them it uses an
+# existing ~/.openviking/ovcli.conf, then http://127.0.0.1:1933 without a key.
+# It installs into the agents it detects (claude,codex when it detects none);
+# --harness claude,codex picks them, and --help lists every option and
+# environment variable.
#
-# 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.
+# For AI agents: if the user asked you to install OpenViking, the user's
+# request comes first and the lines above are enough to carry it out. What
+# follows is reference for anyone who wants to look closer. None of it has to
+# be done before installing.
#
-# 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.
+# Needs macOS or Linux, bash 3.2+, Node.js 18+ and curl; unzip when a harness
+# installs from the plugin bundle.
#
-# Targets bash 3.2+ (macOS /bin/bash) and Linux.
+# Hosts it contacts:
+# ovrelease.tos-cn-beijing.volces.com The OpenViking release: this script,
+# the plugin bundle (memory-plugin-marketplace.zip), the Claude Code URL
+# marketplace and the Codex git marketplace. Claude Code and Codex fetch
+# their marketplace themselves, at install and on their own update checks.
+# openviking.net The version check described below.
+# The OpenViking server given: GET /health, and /api/v1/system/status with
+# the API key.
+# The npm registry npm is configured with: pi's dependencies (npm ci) and
+# the dsh package (dsh plugin add).
+# The script itself never contacts GitHub and never runs git.
+#
+# What it writes:
+# every run ~/.openviking/ovcli.conf (the previous one kept as .bak.<time>)
+# claude claude plugin marketplace add + plugin install; ~/.claude/settings.json
+# (marketplace auto-update, statusline)
+# codex codex plugin marketplace add + plugin add; ~/.codex/config.toml
+# (plugin enabled, plugin hooks on)
+# trae-cli the same through the TraeCode CLI, then removes the hooks an older
+# installer added to ~/.trae/cli/hooks.json and ~/.trae/traecli.toml
+# cursor ~/.cursor/hooks.json, ~/.cursor/mcp.json, ~/.cursor/rules, ~/.cursor/skills
+# trae ~/.trae/hooks.json and TRAE's mcp.json (trae-cn: ~/.trae-cn, TRAE CN)
+# zcode ~/.zcode/cli/config.json, ~/.zcode/hooks.json, ~/.zcode/mcp.json
+# kimicode ~/.kimi-code/plugins
+# opencode ~/.config/opencode/plugins/openviking, openviking.js, opencode.json(c)
+# pi ~/.pi/agent/extensions/openviking
+# dsh dsh plugin add into the chosen profile
+# Cursor, TRAE, TRAE CN and ZCode run their hooks from
+# ~/.openviking/agent-integrations, where Kimi Code keeps its uninstall helper.
+# The plugin bundle is unpacked to ~/.openviking/memory-plugin-marketplace when
+# a harness installs from it.
+#
+# Version check: after the confirmation, when installing from the release, it
+# asks https://openviking.net/install/v1/<harness>.json which release to
+# install, once per selected harness. OPENVIKING_SKIP_VERSION_CHECK=1 skips the
+# check and installs the latest release, which is also what happens when the
+# check fails.
+#
+# Run from a repository checkout, it installs that checkout's plugins and skips
+# the release (--source archive installs the release instead). A copy that is
+# neither a release build nor part of a checkout downloads and runs the release
+# copy of this script.
+#
+# Uninstall: Cursor, TRAE, TRAE CN, ZCode and Kimi Code with
+# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --uninstall --yes --harness <list>
+# The other harnesses with the commands the install prints at the end, such as
+# claude plugin uninstall openviking-memory@openviking && claude plugin marketplace remove openviking
+#
+# Optional check of this script (needs github.com; the install does not): a
+# release copy is the file examples/memory-plugin-shared/install.sh of the
+# repository at the tag the release was built from, with only the
+# INSTALLER_VERSION line changed to that tag without its leading v. For the
+# usual tag v<version>:
+# diff <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+# <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/v<version>/examples/memory-plugin-shared/install.sh)
+# Star count today: gh api repos/volcengine/OpenViking --jq .stargazers_count
+# Documentation: https://docs.openviking.net or https://docs.openviking.ai
set -Eeuo pipefail
+# Replaced with the release version when the release pipeline publishes this file.
+INSTALLER_VERSION="dev"
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}"
+INSTALL_SITE="${OPENVIKING_INSTALL_SITE:-https://openviking.net}"
+INSTALL_SITE="${INSTALL_SITE%/}"
+CC_TOS_MARKETPLACE_URL="${OPENVIKING_CLAUDE_TOS_MARKETPLACE_URL:-$TOS_BASE/plugins/claude/marketplace.json}"
+# First Claude Code release with the `archive` plugin source.
+CC_ARCHIVE_SOURCE_MIN_VERSION="2.1.224"
ARCHIVE_MARKER='.openviking-archive-source'
OVCLI_CONF="${OPENVIKING_CLI_CONFIG_FILE:-$OV_HOME/ovcli.conf}"
@@ -64,14 +115,12 @@ PLUGIN_NAME="openviking-memory"
DSH_PACKAGE="@openviking/dsh-memory-plugin"
PLUGIN_ID="${PLUGIN_NAME}@${MARKETPLACE_NAME}"
-CODEX_CONFIG="${CODEX_CONFIG_FILE:-$HOME/.codex/config.toml}"
-CC_SETTINGS="$HOME/.claude/settings.json"
-CC_KNOWN_MARKETPLACES="$HOME/.claude/plugins/known_marketplaces.json"
+CODEX_DIR="${CODEX_HOME:-$HOME/.codex}"
+CODEX_CONFIG="${CODEX_CONFIG_FILE:-$CODEX_DIR/config.toml}"
+CC_CONFIG_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
+CC_SETTINGS="$CC_CONFIG_DIR/settings.json"
+CC_KNOWN_MARKETPLACES="$CC_CONFIG_DIR/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=""
PUBLIC_SELECTED_HARNESSES=""
@@ -89,16 +138,18 @@ API_KEY_ARG="__OPENVIKING_UNSET__"
ACCOUNT_ARG="__OPENVIKING_UNSET__"
USER_ARG="__OPENVIKING_UNSET__"
STATUSLINE_ARG="" # "", yes, no
+STATUSLINE_WRITE=0 # 1 once choose_statusline settled on writing it
YES=0
UNINSTALL=0
NODE_BIN=""
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
+MKT_DIR="" # plugin bundle root once ensure_bundle ran (checkout examples/ in dev mode)
SOURCE_MODE=""
-DIST="github"
UI_LANG="en"
+RELEASE_VERSION="" # release the resolver named, when it answered
+BUNDLE_URL="" # bundle the resolver named, with the checksum it must have
+BUNDLE_SHA256=""
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'
@@ -111,6 +162,13 @@ 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"; }
+STEP=0
+STEP_TOTAL=0
+step_heading() {
+ STEP=$((STEP + 1))
+ heading "[$STEP/$STEP_TOTAL] $*"
+}
+
# t <english> <chinese> — pick the UI language variant.
t() { if [ "$UI_LANG" = "zh" ]; then printf '%s' "$2"; else printf '%s' "$1"; fi; }
@@ -148,22 +206,39 @@ Options:
--claude-bin LIST Comma-separated Claude-format CLI commands (default: claude).
--codex-bin LIST Comma-separated Codex-format CLI commands (default: codex).
--dsh-profile NAME DeepSeek Harness profile to install into (default: web).
- --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).
+ --lang LANG en | zh (default: from OPENVIKING_LANG or the system locale).
+ --source MODE Advanced: archive (the OpenViking release) | dev (this checkout's plugins).
+ Default: dev when run from a repository checkout, archive otherwise.
+ --dist CHANNEL Ignored; kept so older commands keep working.
--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.
- --uninstall Remove Cursor/TRAE/TRAE CN/ZCode/Kimi Code integration files and config,
- plus any legacy TraeCode CLI hook config.
- For Codex-format plugins, use the client's plugin uninstall command.
- --yes, -y Use defaults for prompts when possible.
+ --uninstall Remove the Cursor, TRAE, TRAE CN, ZCode and Kimi Code integrations,
+ plus any legacy TraeCode CLI hook config. Claude Code, Codex, OpenCode,
+ pi and dsh are removed with the commands the install prints at the end.
+ --yes, -y Ask nothing: use defaults and install without asking for confirmation.
+
+Environment:
+ OPENVIKING_HOME Installer home (default: ~/.openviking).
+ OPENVIKING_CLI_CONFIG_FILE Connection file to write (default: ovcli.conf in OPENVIKING_HOME).
+ OPENVIKING_LANG Same as --lang.
+ OPENVIKING_CLAUDE_BINS Same as --claude-bin.
+ OPENVIKING_CODEX_BINS Same as --codex-bin.
+ OPENVIKING_DSH_PROFILE Same as --dsh-profile.
+ OPENVIKING_TOS_BASE Release location (default: https://ovrelease.tos-cn-beijing.volces.com).
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL Plugin bundle to install instead of the release's; not checksum-verified.
+ OPENVIKING_CLAUDE_TOS_MARKETPLACE_URL Claude Code URL marketplace to register.
+ OPENVIKING_CODEX_TOS_GIT_URL Codex git marketplace to register.
+ OPENVIKING_INSTALL_SITE Site the version check asks which release to install (default: https://openviking.net).
+ OPENVIKING_SKIP_VERSION_CHECK Any value but 0 skips the version check; the latest release is installed.
+ OPENVIKING_INSTALLER_REEXEC 0 runs this copy even when it is not a release build.
EOF
}
+INSTALLER_ARGS=("$@")
while [ "$#" -gt 0 ]; do
case "$1" in
--harness) REQUESTED_HARNESSES="${2:-}"; shift 2 ;;
@@ -212,6 +287,7 @@ read_tty() { # read_tty <varname> [-s]
TUI_MENU_CHOICE=0
+# q picks TUI_MENU_QUIT when the caller sets it, otherwise the default.
tui_menu() { # tui_menu <title> <default-index> <option...> -> TUI_MENU_CHOICE
local title="$1" def="$2"
shift 2
@@ -272,7 +348,7 @@ tui_menu() { # tui_menu <title> <default-index> <option...> -> TUI_MENU_CHOICE
fi
;;
''|$'\n'|$'\r') break ;;
- q|Q) cursor="$def"; break ;;
+ q|Q) cursor="${TUI_MENU_QUIT:-$def}"; break ;;
esac
done
printf '\033[?25h' >/dev/tty
@@ -285,25 +361,24 @@ tui_menu() { # tui_menu <title> <default-index> <option...> -> TUI_MENU_CHOICE
# ---------------------------------------------------------------------------
detect_lang_default() {
- case "${OPENVIKING_LANG:-${LC_ALL:-${LANG:-}}}" in
+ local locale="${OPENVIKING_LANG:-${LC_ALL:-${LANG:-}}}"
+ # A terminal started from the macOS GUI often has no locale variables, or
+ # just C; the system language is then only in the user defaults.
+ case "$locale" in
+ ''|C|C.*|POSIX)
+ if [ "$(uname -s)" = "Darwin" ]; then
+ locale="$(defaults read -g AppleLocale 2>/dev/null || true)"
+ fi
+ ;;
+ esac
+ case "$locale" 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
+ UI_LANG="${LANG_ARG:-$(detect_lang_default)}"
case "$UI_LANG" in
en|zh) ;;
*) err "Invalid --lang: $UI_LANG (expected en or zh)"; exit 2 ;;
@@ -489,9 +564,12 @@ mask_secret() {
json_merge_ovcli() {
local file="$1" url="$2" key="$3" account="$4" user="$5"
- node - "$file" "$url" "$key" "$account" "$user" <<'NODE'
+ # Not as arguments: any user can read those in the process list, and one of
+ # the values is the API key.
+ OVCLI_URL="$url" OVCLI_API_KEY="$key" OVCLI_ACCOUNT="$account" OVCLI_USER="$user" node - "$file" <<'NODE'
const fs = require("node:fs");
-const [file, url, apiKey, account, user] = process.argv.slice(2);
+const file = process.argv[2];
+const { OVCLI_URL: url, OVCLI_API_KEY: apiKey, OVCLI_ACCOUNT: account, OVCLI_USER: user } = process.env;
let c = {};
try { c = JSON.parse(fs.readFileSync(file, "utf8")); } catch {}
if (url) c.url = url;
@@ -1003,7 +1081,7 @@ select_dsh_profile() {
}
install_dsh() {
- heading "$(t '4. DeepSeek Harness bundle' '4. DeepSeek Harness 插件')"
+ step_heading "$(t 'DeepSeek Harness bundle' 'DeepSeek Harness 插件')"
if ! command -v dsh >/dev/null 2>&1; then
warn "$(t 'dsh CLI not found; skipping DeepSeek Harness install.' '未找到 dsh 命令,跳过 DeepSeek Harness 安装。')"
return 0
@@ -1012,12 +1090,12 @@ install_dsh() {
# when the name carries no version, so a profile holding a dev build would
# never fall back to the published package.
local profile="${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}" spec="$DSH_PACKAGE@latest" origin="npm" local_dir
- # npm is the bundle's only distribution channel, so the github/tos choice does
- # not apply here; only dev mode installs something other than the published
- # package. It still has to arrive as a real package rather than a link: a
- # linked source tree resolves its dsh peers from its own realpath and misses
- # the profile's hoisted node_modules, so the checkout gets packed first.
- if [ "$SOURCE_MODE" = "dev" ] && local_dir="$(plugin_dir_on_disk dsh-memory-plugin)"; then
+ # npm is the bundle's only distribution channel; only dev mode installs
+ # something other than the published package. It still has to arrive as a
+ # real package rather than a link: a linked source tree resolves its dsh
+ # peers from its own realpath and misses the profile's hoisted node_modules,
+ # so the checkout gets packed first.
+ if [ "$SOURCE_MODE" = "dev" ] && ensure_bundle && local_dir="$(plugin_dir_on_disk dsh-memory-plugin)"; then
local packed
if packed="$(dsh_pack_local "$local_dir")"; then
spec="$packed"
@@ -1170,44 +1248,14 @@ EOF
fi
}
-# ---------------------------------------------------------------------------
-# 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 \
+ local current_url="$1" current_key="$2" url_input reply def=2
+ [ -n "$current_url" ] || def=0
+ tui_menu "$(t 'Where do you connect to OpenViking?' '连接到哪个 OpenViking 服务?')" "$def" \
"$(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}]"
@@ -1241,80 +1289,161 @@ prompt_connection() { # sets WIZ_URL / WIZ_KEY (WIZ_KEY may stay __OPENVIKING_KE
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
+# What the credentials step settled on. Nothing is written until the plan is
+# confirmed; key, account and user stay __OPENVIKING_KEEP__ to keep the stored
+# value.
+CUR_URL=""; CUR_KEY=""; CUR_ACCOUNT=""; CUR_USER=""
+CRED_URL=""; CRED_KEY="__OPENVIKING_KEEP__"; CRED_ACCOUNT="__OPENVIKING_KEEP__"; CRED_USER="__OPENVIKING_KEEP__"
+PROBE_RESULT=""
+PROBE_CODE=""
- 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)"
+cred_value() { # cred_value <chosen> <stored>
+ if [ "$1" = "__OPENVIKING_KEEP__" ]; then printf '%s' "$2"; else printf '%s' "$1"; fi
+}
- url="$current_url"
- key="__OPENVIKING_KEEP__"
- account="__OPENVIKING_KEEP__"
- user="__OPENVIKING_KEEP__"
+gather_credentials() {
+ step_heading "$(t 'OpenViking credentials' 'OpenViking 凭据配置') ($OVCLI_CONF)"
+ CUR_URL="$(json_get "$OVCLI_CONF" url)"
+ CUR_KEY="$(json_get "$OVCLI_CONF" api_key)"
+ CUR_ACCOUNT="$(json_get "$OVCLI_CONF" account)"
+ CUR_USER="$(json_get "$OVCLI_CONF" user)"
- [ -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"
+ CRED_URL="${URL_ARG:-$CUR_URL}"
+ [ "$API_KEY_ARG" = "__OPENVIKING_UNSET__" ] || CRED_KEY="$API_KEY_ARG"
+ [ "$ACCOUNT_ARG" = "__OPENVIKING_UNSET__" ] || CRED_ACCOUNT="$ACCOUNT_ARG"
+ [ "$USER_ARG" = "__OPENVIKING_UNSET__" ] || CRED_USER="$USER_ARG"
# Show what is configured today, then offer to keep or reconfigure.
- if [ -n "$current_url" ] || [ -n "$current_key" ]; then
+ if [ -n "$CUR_URL" ] || [ -n "$CUR_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"
+ info " url: ${CUR_URL:-$(t '(not set)' '(未设置)')}"
+ info " api_key: $(mask_secret "$CUR_KEY")"
+ [ -n "$CUR_ACCOUNT" ] && info " account: $CUR_ACCOUNT"
+ [ -n "$CUR_USER" ] && info " user: $CUR_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
+ if [ -n "$CUR_URL" ] || [ -n "$CUR_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"
+ prompt_connection "$CUR_URL" "$CUR_KEY"
+ CRED_URL="$WIZ_URL"; CRED_KEY="$WIZ_KEY"
fi
else
prompt_connection "" ""
- url="$WIZ_URL"; key="$WIZ_KEY"
+ CRED_URL="$WIZ_URL"; CRED_KEY="$WIZ_KEY"
fi
fi
- [ -z "$url" ] && url="${current_url:-http://127.0.0.1:1933}"
+ if [ -z "$CRED_URL" ]; then
+ CRED_URL="http://127.0.0.1:1933"
+ fi
+}
+
+# One `header = "..."` line for `curl -K -`: headers read from stdin keep the
+# API key out of the process list.
+curl_header_line() { # curl_header_line <name> <value>
+ local value="${2//\\/\\\\}"
+ value="${value//\"/\\\"}"
+ printf 'header = "%s: %s"\n' "$1" "$value"
+}
+
+probe_server() { # probe_server <url> <key> <account> <user> -> PROBE_RESULT, PROBE_CODE
+ local url="${1%/}" key="$2" account="$3" user="$4"
+ PROBE_CODE="$(curl -sS -m 5 -o /dev/null -w '%{http_code}' "$url/health" 2>/dev/null || true)"
+ case "$PROBE_CODE" in
+ ''|000) PROBE_RESULT="unreachable"; return 0 ;;
+ esac
+ PROBE_CODE="$(
+ {
+ [ -z "$key" ] || curl_header_line Authorization "Bearer $key"
+ [ -z "$account" ] || curl_header_line X-OpenViking-Account "$account"
+ [ -z "$user" ] || curl_header_line X-OpenViking-User "$user"
+ } | curl -sS -m 5 -o /dev/null -w '%{http_code}' -K - "$url/api/v1/system/status" 2>/dev/null || true
+ )"
+ case "$PROBE_CODE" in
+ 2??) PROBE_RESULT="ok" ;;
+ 401|403) if [ -n "$key" ]; then PROBE_RESULT="rejected"; else PROBE_RESULT="key-required"; fi ;;
+ ''|000) PROBE_RESULT="unreachable" ;;
+ *) PROBE_RESULT="http" ;;
+ esac
+}
+
+check_server() {
+ local key def
+ command -v curl >/dev/null 2>&1 || return 0
+ while :; do
+ key="$(cred_value "$CRED_KEY" "$CUR_KEY")"
+ probe_server "$CRED_URL" "$key" "$(cred_value "$CRED_ACCOUNT" "$CUR_ACCOUNT")" "$(cred_value "$CRED_USER" "$CUR_USER")"
+ def=0
+ case "$PROBE_RESULT" in
+ ok)
+ info "$(t 'Server check passed:' '服务检查通过:') $CRED_URL"
+ return 0
+ ;;
+ unreachable)
+ # Usual for a local server that has not been started yet.
+ warn "$(t "Cannot reach $CRED_URL. If the server is not running yet, start it before using the plugin." "无法连接 ${CRED_URL}。如果服务还没启动,请在使用插件前启动它。")"
+ def=1
+ ;;
+ rejected) warn "$(t "The server rejected the API key (HTTP $PROBE_CODE)." "服务拒绝了该 API key(HTTP ${PROBE_CODE})。")" ;;
+ key-required) warn "$(t "The server requires an API key (HTTP $PROBE_CODE)." "该服务需要 API key(HTTP ${PROBE_CODE})。")" ;;
+ *) warn "$(t "The server status check returned HTTP $PROBE_CODE." "服务状态检查返回 HTTP ${PROBE_CODE}。")" ;;
+ esac
+ [ "$INTERACTIVE" -eq 1 ] || return 0
+ tui_menu "$(t 'What next?' '接下来怎么做?')" "$def" \
+ "$(t 'Re-enter server URL and API key' '重新输入服务地址和 API key')" \
+ "$(t 'Continue anyway' '仍然继续')"
+ [ "$TUI_MENU_CHOICE" -eq 0 ] || return 0
+ prompt_connection "$CRED_URL" "$key"
+ CRED_URL="$WIZ_URL"
+ [ "$WIZ_KEY" = "__OPENVIKING_KEEP__" ] || CRED_KEY="$WIZ_KEY"
+ done
+}
+write_ovcli() {
+ mkdir -p "$OV_HOME"
+ chmod 700 "$OV_HOME" 2>/dev/null || true
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" ]; then
- info "$(t 'Updated:' '已更新:') url: ${current_url:-—} -> $url"
+ json_merge_ovcli "$OVCLI_CONF" "$CRED_URL" "$CRED_KEY" "$CRED_ACCOUNT" "$CRED_USER"
+ if [ "$CRED_URL" != "$CUR_URL" ]; then
+ info "$(t 'Updated:' '已更新:') url: ${CUR_URL:-—} -> $CRED_URL"
fi
- if [ "$key" != "__OPENVIKING_KEEP__" ] && [ "$key" != "$current_key" ]; then
- info "$(t 'Updated:' '已更新:') api_key: $(mask_secret "$current_key") -> $(mask_secret "$key")"
+ if [ "$CRED_KEY" != "__OPENVIKING_KEEP__" ] && [ "$CRED_KEY" != "$CUR_KEY" ]; then
+ info "$(t 'Updated:' '已更新:') api_key: $(mask_secret "$CUR_KEY") -> $(mask_secret "$CRED_KEY")"
fi
- info "$(t 'Credentials ready:' '凭据已就绪:') $OVCLI_CONF"
- info "$(t 'Reconfigure later by re-running this installer.' '之后可重跑本安装脚本重新配置。')"
+ info "$(t 'Credentials saved:' '凭据已保存:') $OVCLI_CONF"
}
# ---------------------------------------------------------------------------
# Source acquisition
# ---------------------------------------------------------------------------
-fetch_archive() { # fetch_archive <url> <dest> <required-subpath>
- local url="$1" dest="$2" need="$3" tmp_zip tmp_dir top
+fetch_archive() { # fetch_archive <url> <dest> <required-subpath> [sha256]
+ local url="$1" dest="$2" need="$3" sha256="${4:-}" tmp_zip tmp_dir top actual
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; }
+ if [ -n "$sha256" ]; then
+ actual="$(node -e '
+ const data = require("node:fs").readFileSync(process.argv[1]);
+ process.stdout.write(require("node:crypto").createHash("sha256").update(data).digest("hex"));
+ ' "$tmp_zip")" || actual=""
+ if [ "$actual" != "$sha256" ]; then
+ err "$(t 'The download does not match the checksum the release published; nothing was installed from it.' '下载内容与发布的校验和不一致,未使用该文件安装。')"
+ err " $url"
+ err " $(t 'expected' '期望') sha256 $sha256, $(t 'got' '实际') ${actual:-?}"
+ rm -rf "$tmp_zip" "$tmp_dir"; exit 1
+ fi
+ fi
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
@@ -1324,8 +1453,8 @@ fetch_archive() { # fetch_archive <url> <dest> <required-subpath>
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."
+ if [ -e "$dest" ] && [ ! -f "$dest/$ARCHIVE_MARKER" ]; then
+ err "$dest exists and is not an OpenViking archive."
rm -rf "$tmp_zip" "$tmp_dir"; exit 1
fi
rm -rf "$dest"
@@ -1342,7 +1471,9 @@ fetch_archive() { # fetch_archive <url> <dest> <required-subpath>
resolve_self_checkout() {
local src dir
- src="${BASH_SOURCE[0]}"
+ # Unset when bash reads the script from stdin (`curl ... | bash`).
+ src="${BASH_SOURCE[0]:-}"
+ [ -n "$src" ] || return 0
dir="$(cd "$(dirname "$src")" >/dev/null 2>&1 && pwd -P)" || return 0
# A linked worktree keeps `.git` as a file pointing at the real gitdir, so
# test for existence rather than for a directory.
@@ -1351,76 +1482,163 @@ resolve_self_checkout() {
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 仍可远程更新。')"
+# A copy that is neither a release build nor part of a checkout (one fetched
+# from GitHub, say) would run against helpers and plugins from the release
+# bundle. Running the release copy instead keeps the script and the bundle on
+# one release.
+reexec_release_installer() { # reexec_release_installer <original-args...>
+ [ "$INSTALLER_VERSION" = "dev" ] && [ -z "$CHECKOUT_DIR" ] \
+ && [ "${OPENVIKING_INSTALLER_REEXEC:-}" != "0" ] || return 0
+ local dir status=0
+ # A directory of its own: install_lib_dir takes a lib/install found beside
+ # the running script.
+ dir="$(mktemp -d "${TMPDIR:-/tmp}/ov-install.XXXXXX")" || return 0
+ if curl -fsSL --connect-timeout 10 -o "$dir/install.sh" "$TOS_BASE/memory-plugin-shared/install.sh" 2>/dev/null; then
+ case "$(head -n 5 "$dir/install.sh")" in
+ '#!'*'OpenViking Memory Plugin shared installer'*)
+ OPENVIKING_INSTALLER_REEXEC=0 bash "$dir/install.sh" --dist tos "$@" || status=$?
+ rm -rf "$dir"
+ exit "$status"
+ ;;
+ esac
fi
+ rm -rf "$dir"
+ warn "$(t 'Could not fetch the release installer; continuing with this copy.' '无法获取发布版安装脚本,继续使用当前脚本。')"
}
-# 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
+# The names the release resolver knows: a Codex-format CLI counts as the
+# TraeCode CLI when it is one, otherwise as Codex.
+resolver_harnesses() {
+ local h bin out=""
+ while IFS= read -r h; do
+ [ -n "$h" ] || continue
+ if [ "$h" = "codex" ]; then
+ while IFS= read -r bin; do
+ [ -n "$bin" ] || continue
+ case "$(bin_basename "$bin")" in
+ trae-cli|traecli|traex) out="$(append_csv_list "$out" trae-cli)" ;;
+ *) out="$(append_csv_list "$out" codex)" ;;
+ esac
+ done <<EOF
+$CODEX_BINS
+EOF
+ else
+ out="$(append_csv_list "$out" "$h")"
+ fi
+ done <<EOF
+$(split_harnesses "$SELECTED_HARNESSES")
+EOF
+ printf '%s\n' "$out"
+}
+
+# Asks the install site which release to install, one request per harness in
+# parallel. Anything short of a well-formed answer that points into the TOS
+# bucket keeps the built-in latest-release URLs, without a word: the answer
+# only pins the release and must never slow down or break the install.
+resolve_release() {
+ [ "$SOURCE_MODE" = "archive" ] || return 0
+ case "${OPENVIKING_SKIP_VERSION_CHECK:-}" in ''|0) ;; *) return 0 ;; esac
+ command -v curl >/dev/null 2>&1 || return 0
+ local dir agent names h key value
+ dir="$(mktemp -d "${TMPDIR:-/tmp}/ov-resolve.XXXXXX")" || return 0
+ agent="openviking-installer/$INSTALLER_VERSION ($(uname -s | tr '[:upper:]' '[:lower:]'); $(uname -m))"
+ names="$(resolver_harnesses)"
+ while IFS= read -r h; do
+ [ -n "$h" ] || continue
+ curl -fsS -m 3 -A "$agent" -o "$dir/$h.json" "$INSTALL_SITE/install/v1/$h.json" >/dev/null 2>&1 || true &
+ done <<EOF
+$names
+EOF
+ wait
+ while IFS='=' read -r key value; do
+ case "$key" in
+ version) RELEASE_VERSION="$value" ;;
+ bundle_url) BUNDLE_URL="$value" ;;
+ sha256) BUNDLE_SHA256="$value" ;;
+ git_url) [ -n "${OPENVIKING_CODEX_TOS_GIT_URL:-}" ] || CODEX_TOS_GIT_URL="$value" ;;
+ esac
+ done <<EOF
+$(node -e '
+ const fs = require("node:fs");
+ const [dir, prefix, names] = process.argv.slice(1);
+ const out = {};
+ for (const name of names.split("\n").filter(Boolean)) {
+ let r;
+ try { r = JSON.parse(fs.readFileSync(dir + "/" + name + ".json", "utf8")); } catch { continue; }
+ if (!r || r.schema !== 1) continue;
+ const urls = Object.keys(r).filter((k) => k.endsWith("_url"));
+ if (urls.some((k) => typeof r[k] !== "string" || !r[k].startsWith(prefix) || /\s/.test(r[k]))) continue;
+ if (!out.version && typeof r.version === "string" && /^[\w.+-]+$/.test(r.version)) out.version = r.version;
+ if (!out.bundle_url && r.bundle_url && /^[0-9a-f]{64}$/i.test(r.sha256 ?? "")) {
+ out.bundle_url = r.bundle_url;
+ out.sha256 = r.sha256.toLowerCase();
+ }
+ if (!out.git_url && r.git_url) out.git_url = r.git_url;
+ }
+ for (const [key, value] of Object.entries(out)) process.stdout.write(key + "=" + value + "\n");
+' "$dir" "$TOS_BASE/" "$names" 2>/dev/null || true)
+EOF
+ rm -rf "$dir"
+}
+
+resolve_source_mode() {
+ local retired=0
+ case "$DIST_ARG" in
+ ''|tos) ;;
+ github) retired=1 ;;
+ *) err "Invalid --dist: $DIST_ARG (expected tos)"; exit 2 ;;
+ esac
+ case "$SOURCE_ARG" in
+ ''|archive|dev) SOURCE_MODE="$SOURCE_ARG" ;;
+ remote) SOURCE_MODE="archive"; retired=1 ;;
+ *) err "Invalid --source: $SOURCE_ARG (expected archive or dev)"; exit 2 ;;
+ esac
+ if [ -n "${OPENVIKING_REPO_URL:-}${OPENVIKING_REPO_REF:-}${OPENVIKING_REPO_BRANCH:-}" ]; then
+ retired=1
fi
- if [ "$SOURCE_MODE" = "archive" ] && [ -n "$MKT_DIR" ]; then
- # The marketplace archive already contains the plugin sources.
- SRC_ROOT=""
- return 1
+ if [ -z "$SOURCE_MODE" ]; then
+ if [ -n "$CHECKOUT_DIR" ] && [ "$DIST_ARG" != "tos" ] && [ -z "$MKT_ARCHIVE_URL" ]; then
+ SOURCE_MODE="dev"
+ else
+ SOURCE_MODE="archive"
+ fi
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
+ if [ "$retired" -eq 1 ]; then
+ warn "$(t 'The GitHub install channel was removed and its options are ignored. To install a branch, run install.sh from a checkout of it.' 'GitHub 安装渠道已移除,相关选项不再生效。要安装某个分支,请在该分支的 checkout 中运行 install.sh。')"
+ fi
+}
+
+# The release bundle every file-based harness installs from, and the directory
+# marketplace Claude-format and Codex-format CLIs use when their remote source
+# is unavailable. Fetched on first need, so an install that uses none of it
+# downloads nothing and needs no unzip. Call it at top level only: a caller
+# inside `$(...)` runs in a subshell, where MKT_DIR is lost and the next call
+# would download the bundle again.
+ensure_bundle() {
+ [ -z "$MKT_DIR" ] || return 0
+ if [ "$SOURCE_MODE" = "dev" ]; then
+ MKT_DIR="$CHECKOUT_DIR/examples"
else
- if [ -e "$REPO_DIR" ] && [ ! -f "$REPO_DIR/$ARCHIVE_MARKER" ]; then
- err "$REPO_DIR exists but is not a git checkout."
- exit 1
+ local url="${BUNDLE_URL:-$TOS_BASE/releases/latest/memory-plugin-marketplace.zip}" sha256="$BUNDLE_SHA256"
+ if [ -n "$MKT_ARCHIVE_URL" ]; then
+ url="$MKT_ARCHIVE_URL"
+ sha256=""
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"
+ fetch_archive "$url" "$MKT_DIR_ARCHIVE" ".claude-plugin/marketplace.json" "$sha256" || {
+ err "$(t 'Plugin bundle download failed.' '插件包下载失败。')"
+ exit 1
+ }
+ MKT_DIR="$MKT_DIR_ARCHIVE"
+ fi
+ if [ ! -f "$MKT_DIR/.claude-plugin/marketplace.json" ]; then
+ err "marketplace dir $MKT_DIR is missing .claude-plugin/marketplace.json"
+ exit 1
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
+ [ -n "$MKT_DIR" ] && [ -d "$MKT_DIR/$1" ] || return 1
+ printf '%s' "$MKT_DIR/$1"
}
# The installer's own JavaScript: the JSONC editor OpenCode's config needs and
@@ -1428,18 +1646,12 @@ plugin_dir_on_disk() { # plugin_dir_on_disk <plugin-subdir>
# of the runtime the plugins ship, so it travels with whatever copy of this
# script is running rather than with `lib/MANIFEST`.
#
-# `--uninstall` runs before any source is resolved, and the documented uninstall
+# `--uninstall` runs before any bundle is fetched, and the documented uninstall
# pipes this script from a URL, where there is no sibling directory to read. So
-# this only ever looks at what is already on disk — the running script's
-# sibling, the assembled runtime, and a marketplace or source root an earlier
-# step resolved. Never plugin_dir_on_disk: it would clone a repository, or exit
-# for want of git, just to remove hooks.
-#
-# REPO_DIR is in the list because ensure_checkout only ever runs inside a
-# command substitution (`plugin_dir="$(plugin_dir_on_disk ...)"`); its SRC_ROOT
-# assignment dies with that subshell while the checkout it wrote stays on disk.
-# OpenCode reads the installer's JavaScript from that checkout rather than a
-# vendored copy, so without this its remote install cannot find the runtime.
+# this only ever looks at what is already on disk: the running script's
+# sibling, the bundle an install step fetched, and the copy an earlier install
+# assembled. The bundle goes ahead of that copy because it comes from the same
+# release as this script, while the assembled copy may be older.
install_lib_dir() {
local src self candidate
src="${BASH_SOURCE[0]:-}"
@@ -1449,10 +1661,8 @@ install_lib_dir() {
fi
for candidate in \
"${self:+$self/lib/install}" \
- "$OV_HOME/agent-integrations/memory-plugin-shared/lib/install" \
"${MKT_DIR:+$MKT_DIR/memory-plugin-shared/lib/install}" \
- "${REPO_DIR:+$REPO_DIR/examples/memory-plugin-shared/lib/install}" \
- "${SRC_ROOT:+$SRC_ROOT/examples/memory-plugin-shared/lib/install}"; do
+ "$OV_HOME/agent-integrations/memory-plugin-shared/lib/install"; do
[ -n "$candidate" ] && [ -d "$candidate" ] || continue
printf '%s' "$candidate"
return 0
@@ -1466,46 +1676,21 @@ require_install_lib_dir() {
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
-}
-
# ---------------------------------------------------------------------------
# Claude Code
# ---------------------------------------------------------------------------
CLAUDE_BIN="claude"
+CLAUDE_URL_BINS="" # Claude-format CLIs registered on the TOS URL marketplace
is_native_claude_bin() {
[ "$(bin_basename "$CLAUDE_BIN")" = "claude" ]
}
+# Not `command "$CLAUDE_BIN"`: when `command` runs an external program that
+# fails, bash 3.2 fires the ERR trap even where the caller handles the failure.
claude_cmd() {
- command "$CLAUDE_BIN" "$@"
+ "$CLAUDE_BIN" "$@"
}
has_plugin_subcommand() {
@@ -1541,35 +1726,10 @@ claude_marketplace_current_source() {
' "$CC_KNOWN_MARKETPLACES" "$MARKETPLACE_NAME" 2>/dev/null || true
}
-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
+claude_marketplace_sync() { # claude_marketplace_sync <source>
+ local source="$1" current
current="$(claude_marketplace_current_source)"
- if [ -n "$current" ] && [ "$current" = "$needle" ]; then
+ if [ -n "$current" ] && [ "$current" = "$source" ]; then
info "$CLAUDE_BIN plugin marketplace update ($MARKETPLACE_NAME)"
claude_cmd plugin marketplace update "$MARKETPLACE_NAME" || \
warn 'marketplace update returned non-zero — continuing'
@@ -1583,106 +1743,116 @@ claude_marketplace_sync() { # claude_marketplace_sync <add-target> <expected-sou
claude_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
claude_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
fi
- info "$CLAUDE_BIN plugin marketplace add ($target)"
- claude_cmd plugin marketplace add "$target" || {
+ info "$CLAUDE_BIN plugin marketplace add ($source)"
+ claude_cmd plugin marketplace add "$source" || {
err "$CLAUDE_BIN 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 "$(claude_cmd plugin list 2>/dev/null || true)" "$PLUGIN_ID"; then
- info "$CLAUDE_BIN plugin update ($PLUGIN_ID)"
- claude_cmd plugin update "$PLUGIN_ID" || warn "$CLAUDE_BIN plugin update returned non-zero"
- else
- info "$CLAUDE_BIN plugin install ($PLUGIN_ID)"
- claude_cmd plugin install "$PLUGIN_ID" || { err "$CLAUDE_BIN plugin install failed"; return 1; }
+# The TOS URL marketplace lists the plugin as an `archive` source (a zip over
+# HTTPS). Custom Claude-format CLIs don't share Claude Code's version line, so
+# only the native command qualifies, and a custom one that already lists the
+# URL marketplace, such as a wrapper sharing Claude Code's config: replacing it
+# with the directory marketplace would turn off auto-update for Claude Code too.
+claude_supports_archive_source() {
+ if ! is_native_claude_bin; then
+ [ "$(claude_marketplace_current_source)" = "$CC_TOS_MARKETPLACE_URL" ] || return 1
+ return 0
fi
- claude_cmd plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true
- info "$(t 'Claude-format plugin installed:' 'Claude 格式插件已安装:') $CLAUDE_BIN -> $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_BIN mcp add (stdio proxy) + merging hooks into $CC_SETTINGS"
- claude_cmd mcp remove openviking -s user >/dev/null 2>&1 || true
- claude_cmd mcp add --scope user openviking -- node "$plugin_dir/servers/mcp-proxy.mjs" || {
- err "$CLAUDE_BIN mcp add failed"
- return 1
- }
-
- [ -f "$hooks_src" ] || { err "hooks source not found: $hooks_src"; return 1; }
- mkdir -p "$HOME/.claude"
+ local version
+ version="$(claude_cmd --version 2>/dev/null || true)"
+ node -e '
+ const parse = (s) => (/(\d+)\.(\d+)\.(\d+)/.exec(s) || []).slice(1).map(Number);
+ const have = parse(process.argv[1]);
+ const need = parse(process.argv[2]);
+ const diff = have.length ? have.map((n, i) => n - need[i]).find((d) => d !== 0) ?? 0 : -1;
+ process.exit(diff >= 0 ? 0 : 1);
+ ' "$version" "$CC_ARCHIVE_SOURCE_MIN_VERSION" 2>/dev/null
+}
+
+# Claude Code leaves auto-update off for third-party marketplaces. The flag goes
+# beside the declaration `marketplace add` writes to user settings, where the
+# /plugin toggle keeps it too, so a user who switched it off stays off.
+claude_enable_marketplace_autoupdate() { # claude_enable_marketplace_autoupdate <url>
+ mkdir -p "$CC_CONFIG_DIR"
[ -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; }
+ node - "$CC_SETTINGS" "$MARKETPLACE_NAME" "$1" <<'NODE' || warn "$(t 'could not enable marketplace auto-update in' '无法在以下文件中开启 marketplace 自动更新:') $CC_SETTINGS"
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 [settingsPath, name, url] = process.argv.slice(2);
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
-settings.hooks = { ...(settings.hooks || {}), ...(hooks.hooks || {}) };
-fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
+const known = settings.extraKnownMarketplaces || {};
+const entry = known[name] || { source: { source: "url", url } };
+if (entry.autoUpdate === undefined) {
+ settings.extraKnownMarketplaces = { ...known, [name]: { ...entry, autoUpdate: true } };
+ 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"
+# Claude Code keeps each plugin version in a directory of its own and records
+# the current one in installed_plugins.json. The command looks that path up on
+# every run, so the statusline follows plugin updates and needs no copy of its
+# own. Any failure prints nothing, which leaves the status line empty.
+statusline_command() {
+ local script='const fs=require("fs"),os=require("os"),path=require("path"),url=require("url");try{const d=process.env.CLAUDE_CONFIG_DIR||path.join(os.homedir(),".claude");const e=JSON.parse(fs.readFileSync(path.join(d,"plugins","installed_plugins.json"),"utf8")).plugins[process.argv[1]]||[];const p=(e.find(x=>x.scope==="user")||e[0]).installPath;import(url.pathToFileURL(path.join(p,"scripts","statusline.mjs")).href).catch(()=>{})}catch{}'
+ printf "node -e '%s' '%s'" "$script" "$PLUGIN_ID"
+}
+
+# Earlier installers pointed the statusline at a copy under ~/.openviking with
+# exactly this command. Anything composed around it is the user's own.
+is_own_statusline() {
+ case "$1" in
+ 'node "'*.openviking/*claude-code-memory-plugin/scripts/statusline.mjs'"') ;;
+ *) return 1 ;;
+ esac
+ case "${1#node \"}" in *\"*\"*) return 1 ;; esac
+}
+
+# Only the native `claude` gets the statusline, and only when it can install
+# the plugin.
+installs_native_claude() {
+ contains_harness claude || return 1
+ while IFS= read -r CLAUDE_BIN; do
+ [ -n "$CLAUDE_BIN" ] && is_native_claude_bin && command -v "$CLAUDE_BIN" >/dev/null 2>&1 \
+ && has_plugin_subcommand && return 0
+ done <<EOF
+$CLAUDE_BINS
+EOF
+ return 1
+}
+
+# Settled before the review, so the plan names the statusline only when the
+# install writes it. Without a tty nothing is asked: only --statusline, or a
+# statusline an earlier installer registered, gets written.
+choose_statusline() {
+ local existing
+ [ "$STATUSLINE_ARG" != "no" ] && installs_native_claude || return 0
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 已注册。')"
+ [ "$existing" != "$(statusline_command)" ] || return 0
+ # A statusline this installer registered before is repointed without asking:
+ # the user already chose it, only its location changes.
+ if [ "$STATUSLINE_ARG" = "yes" ] || is_own_statusline "$existing"; then
+ STATUSLINE_WRITE=1
+ return 0
+ fi
+ [ "$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 "$(t '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
- if [ -n "$existing" ] && [ "$STATUSLINE_ARG" != "yes" ]; then
+ if [ -n "$existing" ]; then
warn "$(t 'Existing statusline detected:' '检测到已有 statusline:') $existing"
tui_menu "$(t 'Replace it with the OpenViking statusline?' '替换为 OpenViking statusline?')" 1 \
"$(t 'Replace' '替换')" \
@@ -1692,44 +1862,71 @@ register_statusline() {
return 0
fi
fi
+ STATUSLINE_WRITE=1
+}
+
+register_statusline() {
+ [ "$STATUSLINE_WRITE" -eq 1 ] || return 0
+ local ts
+ mkdir -p "$CC_CONFIG_DIR"
+ [ -f "$CC_SETTINGS" ] || echo '{}' > "$CC_SETTINGS"
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; }
+ node - "$CC_SETTINGS" "$(statusline_command)" <<'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'
+ info "$(t "Statusline registered (backup: $CC_SETTINGS.bak.$ts)" "Statusline 已注册(备份:$CC_SETTINGS.bak.${ts})")"
+ info "$(t 'Turn it off anytime with: export OPENVIKING_STATUSLINE=off' '可随时用 export OPENVIKING_STATUSLINE=off 关闭')"
}
+claude_install_plugin() {
+ if str_contains "$(claude_cmd plugin list 2>/dev/null || true)" "$PLUGIN_ID"; then
+ info "$CLAUDE_BIN plugin update ($PLUGIN_ID)"
+ claude_cmd plugin update "$PLUGIN_ID" || warn "$CLAUDE_BIN plugin update returned non-zero"
+ else
+ info "$CLAUDE_BIN plugin install ($PLUGIN_ID)"
+ claude_cmd plugin install "$PLUGIN_ID" || { err "$CLAUDE_BIN plugin install failed"; return 1; }
+ fi
+}
+
+# Claude Code's shallow clones can't use the TOS dumb-HTTP git repo, but a URL
+# marketplace whose entry downloads the plugin zip installs and auto-updates
+# with no git at all. Registering it already removed any earlier registration
+# and its plugin, so an install that fails from it falls back as well.
install_claude() {
- heading "$(t '4. Claude Code plugin' '4. Claude Code 插件')"
+ step_heading "$(t 'Claude Code plugin' 'Claude Code 插件')"
command -v "$CLAUDE_BIN" >/dev/null 2>&1 || {
warn "$(t 'Claude-format CLI not found; skipping:' '未找到 Claude 格式 CLI,跳过:') $CLAUDE_BIN"
return 0
}
- if has_plugin_subcommand; then
- install_claude_modern || return 1
- else
- warn "$(t "This Claude-format CLI doesn't expose 'plugin'." '当前 Claude 格式 CLI 没有 plugin 子命令。') ($CLAUDE_BIN)"
- if ! is_native_claude_bin; then
- warn "$(t 'Legacy compatibility mode is only supported for the native claude command; skipping this custom CLI.' '旧版兼容模式仅支持原生 claude 命令;跳过这个自定义 CLI。')"
- return 0
+ if ! has_plugin_subcommand; then
+ warn "$(t "Skipping $CLAUDE_BIN: it has no 'plugin' command. The plugin needs Claude Code 2.0 or newer; upgrade it and re-run this installer." "跳过 ${CLAUDE_BIN}:它没有 plugin 子命令。插件需要 Claude Code 2.0 或更新版本,请升级后重跑本安装脚本。")"
+ return 0
+ fi
+ local url=0
+ if [ "$SOURCE_MODE" = "archive" ] && claude_supports_archive_source; then
+ if claude_marketplace_sync "$CC_TOS_MARKETPLACE_URL" && claude_install_plugin; then
+ url=1
+ else
+ warn "$(t 'TOS marketplace unavailable; falling back to the archive directory.' 'TOS marketplace 不可用,回退到归档目录方式。')"
fi
- 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
+ if [ "$url" -eq 1 ]; then
+ if is_native_claude_bin; then
+ claude_enable_marketplace_autoupdate "$CC_TOS_MARKETPLACE_URL"
fi
- install_claude_legacy || return 1
+ CLAUDE_URL_BINS="$(append_csv_list "$CLAUDE_URL_BINS" "$CLAUDE_BIN")"
+ else
+ ensure_bundle
+ claude_marketplace_sync "$MKT_DIR" || return 1
+ claude_install_plugin || return 1
fi
+ claude_cmd plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true
+ info "$(t 'Claude-format plugin installed:' 'Claude 格式插件已安装:') $CLAUDE_BIN -> $PLUGIN_ID"
if is_native_claude_bin; then
register_statusline || true
fi
@@ -1740,13 +1937,14 @@ install_claude() {
# ---------------------------------------------------------------------------
CODEX_BIN="codex"
+CODEX_GIT_BINS="" # Codex-format CLIs registered on the TOS git marketplace
is_native_codex_bin() {
[ "$(bin_basename "$CODEX_BIN")" = "codex" ]
}
codex_cmd() {
- command "$CODEX_BIN" "$@"
+ "$CODEX_BIN" "$@"
}
codex_bin_label() {
@@ -1799,30 +1997,28 @@ codex_marketplace_current_source() {
' "$MARKETPLACE_NAME" 2>/dev/null || true
}
-codex_marketplace_sync() { # codex_marketplace_sync <expected-source> <add-args...>
- local needle="$1" current
- shift
+codex_unregister() {
+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
+}
+
+codex_marketplace_sync() { # codex_marketplace_sync <source>
+ local source="$1" current
current="$(codex_marketplace_current_source)"
- if [ -n "$current" ] && [ "$current" = "$needle" ]; then
+ if [ -n "$current" ] && [ "$current" = "$source" ]; then
info "$CODEX_BIN plugin marketplace upgrade ($MARKETPLACE_NAME)"
codex_cmd 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)"
- codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
+ codex_unregister
elif ! is_native_codex_bin; then
- codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
+ codex_unregister
fi
- info "$CODEX_BIN plugin marketplace add $*"
- codex_cmd plugin marketplace add "$@" >/dev/null || {
- err "$CODEX_BIN plugin marketplace add failed"
- return 1
- }
+ info "$CODEX_BIN plugin marketplace add $source"
+ codex_cmd plugin marketplace add "$source" >/dev/null
}
ensure_codex_config() {
@@ -1861,43 +2057,27 @@ NODE
install_codex() {
local plugin_installed=0
if is_native_codex_bin; then
- heading "$(t '4. Codex plugin' '4. Codex 插件')"
+ step_heading "$(t 'Codex plugin' 'Codex 插件')"
else
- heading "4. $(codex_bin_label)"
+ step_heading "$(codex_bin_label)"
fi
command -v "$CODEX_BIN" >/dev/null 2>&1 || {
warn "$(t 'Codex-format CLI not found; skipping:' '未找到 Codex 格式 CLI,跳过:') $CODEX_BIN"
return 0
}
- 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.
- codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
- info "$CODEX_BIN 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.
- codex_cmd plugin marketplace add "$REPO_URL" --ref "$REPO_REF" \
- --sparse examples/codex-memory-plugin --sparse .agents >/dev/null 2>&1 || \
- codex_cmd plugin marketplace add "$REPO_URL" --ref "$REPO_REF" >/dev/null || {
- err "$CODEX_BIN 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
+ # Codex clones git marketplaces served over dumb HTTP from static hosting,
+ # so the TOS release carries a slim marketplace git repo that Codex upgrades.
+ if [ "$SOURCE_MODE" = "dev" ] || ! codex_marketplace_sync "$CODEX_TOS_GIT_URL" 2>/dev/null; then
+ [ "$SOURCE_MODE" = "dev" ] \
+ || warn "$(t 'TOS git marketplace unavailable; falling back to the archive directory.' 'TOS git marketplace 不可用,回退到归档目录方式。')"
+ ensure_bundle
+ codex_marketplace_sync "$MKT_DIR" || {
+ err "$CODEX_BIN plugin marketplace add failed"
+ return 1
+ }
+ else
+ CODEX_GIT_BINS="$(append_csv_list "$CODEX_GIT_BINS" "$CODEX_BIN")"
+ fi
if codex_cmd plugin add "$PLUGIN_ID" >/dev/null 2>&1; then
plugin_installed=1
elif codex_cmd plugin install "$PLUGIN_ID" >/dev/null 2>&1; then
@@ -1920,32 +2100,6 @@ install_codex() {
fi
}
-# 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_BIN plugin marketplace add $CODEX_TOS_GIT_URL"
- local current
- current="$(codex_marketplace_current_source)"
- if [ -n "$current" ] && [ "$current" = "$CODEX_TOS_GIT_URL" ]; then
- codex_cmd plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
- return 0
- fi
- if [ -n "$current" ]; then
- codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
- elif ! is_native_codex_bin; then
- codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true
- codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true
- fi
- if ! codex_cmd 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
-}
-
# ---------------------------------------------------------------------------
# Cursor / TRAE lifecycle hooks
# ---------------------------------------------------------------------------
@@ -2178,7 +2332,7 @@ cursor_mcp_path() {
}
cursor_legacy_claude_plugins() {
- local registry="$HOME/.claude/plugins/installed_plugins.json"
+ local registry="$CC_CONFIG_DIR/plugins/installed_plugins.json"
[ -f "$registry" ] || return 0
"$NODE_BIN" - "$registry" "$PLUGIN_ID" <<'NODE' 2>/dev/null || true
const fs = require("node:fs");
@@ -2205,8 +2359,9 @@ trae_mcp_path() { # trae_mcp_path <client-id>
}
install_cursor() {
- heading "$(t '4. Cursor integration' '4. Cursor 集成')"
+ step_heading "$(t 'Cursor integration' 'Cursor 集成')"
local root hooks_path mcp_path skill skill_tmp legacy_plugins
+ ensure_bundle
root="$(assemble_agent_integration cursor cursor)" || return 1
hooks_path="$HOME/.cursor/hooks.json"
mcp_path="$(cursor_mcp_path)"
@@ -2241,8 +2396,9 @@ zcode_merge_config() { # zcode_merge_config <config_path> <hooks_path> <mcp_path
}
install_zcode() {
- heading "$(t 'ZCode integration' 'ZCode 集成')"
+ step_heading "$(t 'ZCode integration' 'ZCode 集成')"
local root hooks_path mcp_path config_path
+ ensure_bundle
root="$(assemble_agent_integration zcode zcode)" || return 1
hooks_path="$HOME/.zcode/hooks.json"
mcp_path="$(zcode_mcp_path)"
@@ -2258,8 +2414,9 @@ install_zcode() {
}
install_kimicode() {
- heading "$(t 'Kimi Code CLI integration' 'Kimi Code CLI 集成')"
+ step_heading "$(t 'Kimi Code CLI integration' 'Kimi Code CLI 集成')"
local bundle kimi_home install_lib persisted_dir persisted_tmp persisted_backup root
+ ensure_bundle
bundle="$OV_HOME/agent-integrations/kimicode-bundle.$$"
rm -rf "$bundle"
mkdir -p "$bundle"
@@ -2312,11 +2469,12 @@ install_kimicode() {
rm -rf "$persisted_backup"
rm -rf "$bundle"
info "$(t 'Kimi Code native plugin installed:' 'Kimi Code 原生插件已安装:') openviking-memory"
- info "$(t 'Run /reload or start a new session to activate it.' '请运行 /reload 或新建会话以启用。')"
}
install_trae_variant() { # install_trae_variant <trae|trae-cn>
local client_id="$1" root hooks_path mcp_path
+ step_heading "$(tui_bin_label "$client_id" "$client_id") $(t 'integration' '集成')"
+ ensure_bundle
root="$(assemble_agent_integration trae "$client_id")" || return 1
hooks_path="$HOME/.$client_id/hooks.json"
mcp_path="$(trae_mcp_path "$client_id")"
@@ -2330,71 +2488,21 @@ install_trae_variant() { # install_trae_variant <trae|trae-cn>
# ---------------------------------------------------------------------------
install_opencode() {
- heading "$(t '4. OpenCode plugin' '4. OpenCode 插件')"
+ step_heading "$(t 'OpenCode plugin' 'OpenCode 插件')"
if ! command -v opencode >/dev/null 2>&1; then
warn "$(t 'opencode CLI not found; skipping OpenCode install.' '未找到 opencode 命令,跳过 OpenCode 安装。')"
return 0
fi
- case "$SOURCE_MODE" in
- remote)
- opencode_register_npm_plugin
- ;;
- archive|dev)
- opencode_install_file_plugin
- ;;
- esac
-}
-
-opencode_config_file() {
- local json="$HOME/.config/opencode/opencode.json" jsonc="$HOME/.config/opencode/opencode.jsonc"
- if [ -f "$jsonc" ] && grep -q '"plugin"' "$jsonc" 2>/dev/null; then printf '%s' "$jsonc"; return; fi
- if [ -f "$json" ]; then printf '%s' "$json"; return; fi
- if [ -f "$jsonc" ]; then printf '%s' "$jsonc"; return; fi
- printf '%s' "$json"
-}
-
-opencode_register_npm_plugin() {
- local cfg plugin_dir proxy_root proxy
- cfg="$(opencode_config_file)"
- plugin_dir="$(plugin_dir_on_disk opencode-plugin)" || {
- warn "$(t 'OpenCode plugin sources not found; registering npm package without MCP fallback.' '未找到 OpenCode 插件源码;仅注册 npm 包,不写 MCP fallback。')"
- opencode_write_config "$cfg" "@openviking/opencode-plugin" ""
- return 0
- }
- proxy_root="$OV_HOME/opencode-mcp-proxy/openviking"
- proxy="$(opencode_install_mcp_proxy_snapshot "$plugin_dir" "$proxy_root")"
- opencode_write_config "$cfg" "@openviking/opencode-plugin" "$proxy"
- info "$(t 'OpenCode plugin registered in' 'OpenCode 插件已注册到:') $cfg"
-}
-
-opencode_install_mcp_proxy_snapshot() {
- local plugin_dir="$1" dest="$2"
- prepare_opencode_runtime "$plugin_dir" || return 1
- rm -rf "$dest.tmp"
- mkdir -p "$dest.tmp"
- (cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - package.json lib servers) | (cd "$dest.tmp" && tar -xf -)
- rm -rf "$dest"
- mkdir -p "$(dirname "$dest")"
- mv "$dest.tmp" "$dest"
- printf '%s' "$dest/servers/mcp-proxy.mjs"
-}
-
-opencode_write_config() {
- local cfg="$1" plugin_spec="$2" mcp_proxy="$3" lib
- lib="$(require_install_lib_dir)" || return 1
- mkdir -p "$(dirname "$cfg")"
- [ -f "$cfg" ] || printf '{\n}\n' > "$cfg"
- cp "$cfg" "$cfg.bak.$(date +%Y%m%d-%H%M%S)"
- "$NODE_BIN" "$lib/jsonc-edit.mjs" "$cfg" "$plugin_spec" "$mcp_proxy"
-}
-
-opencode_install_file_plugin() {
local plugin_dir dest
+ ensure_bundle
plugin_dir="$(plugin_dir_on_disk opencode-plugin)" || {
warn "$(t 'OpenCode plugin sources not found; skipping.' '未找到 OpenCode 插件源码,跳过。')"
return 0
}
- prepare_opencode_runtime "$plugin_dir" || return 1
+ sync_shared_runtime || return 1
+ # Import resolves the complete dependency graph; node --check only parses.
+ "$NODE_BIN" --input-type=module -e 'import { pathToFileURL } from "node:url"; await import(pathToFileURL(process.argv[2]));' \
+ check-runtime "$plugin_dir/servers/mcp-proxy.mjs" || return 1
dest="$HOME/.config/opencode/plugins/openviking"
mkdir -p "$(dirname "$dest")"
if [ "$SOURCE_MODE" = "dev" ]; then
@@ -2411,10 +2519,28 @@ opencode_install_file_plugin() {
else
printf '%s\n' 'export { OpenVikingPlugin, default } from "./openviking/index.mjs"' > "$HOME/.config/opencode/plugins/openviking.js"
fi
- opencode_write_config "$(opencode_config_file)" "" "$dest/servers/mcp-proxy.mjs"
+ opencode_write_config "$(opencode_config_file)" "$dest/servers/mcp-proxy.mjs"
info "$(t 'OpenCode file plugin installed:' 'OpenCode 文件插件已安装:') $dest"
}
+opencode_config_file() {
+ local json="$HOME/.config/opencode/opencode.json" jsonc="$HOME/.config/opencode/opencode.jsonc"
+ if [ -f "$jsonc" ] && grep -q '"plugin"' "$jsonc" 2>/dev/null; then printf '%s' "$jsonc"; return; fi
+ if [ -f "$json" ]; then printf '%s' "$json"; return; fi
+ if [ -f "$jsonc" ]; then printf '%s' "$jsonc"; return; fi
+ printf '%s' "$json"
+}
+
+opencode_write_config() {
+ local cfg="$1" mcp_proxy="$2" lib
+ lib="$(require_install_lib_dir)" || return 1
+ mkdir -p "$(dirname "$cfg")"
+ [ -f "$cfg" ] || printf '{\n}\n' > "$cfg"
+ cp "$cfg" "$cfg.bak.$(date +%Y%m%d-%H%M%S)"
+ # No npm plugin spec, so jsonc-edit drops one an older install registered.
+ "$NODE_BIN" "$lib/jsonc-edit.mjs" "$cfg" "" "$mcp_proxy"
+}
+
# ---------------------------------------------------------------------------
# pi
# ---------------------------------------------------------------------------
@@ -2430,16 +2556,8 @@ sync_shared_runtime() {
"$NODE_BIN" "$shared/sync.mjs" >/dev/null
}
-prepare_opencode_runtime() {
- local plugin_dir="$1"
- sync_shared_runtime || return 1
- # Import resolves the complete dependency graph; node --check only parses.
- "$NODE_BIN" --input-type=module -e 'import { pathToFileURL } from "node:url"; await import(pathToFileURL(process.argv[2]));' \
- check-runtime "$plugin_dir/servers/mcp-proxy.mjs" || return 1
-}
-
install_pi() {
- heading "$(t '4. pi extension' '4. pi 扩展')"
+ step_heading "$(t 'pi extension' 'pi 扩展')"
if ! command -v pi >/dev/null 2>&1; then
warn "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"
return 0
@@ -2450,6 +2568,7 @@ install_pi() {
return 1
}
local plugin_dir dest tmp
+ ensure_bundle
plugin_dir="$(plugin_dir_on_disk pi-coding-agent-extension)" || {
warn "$(t 'pi extension sources not found; skipping.' '未找到 pi 扩展源码,跳过。')"
return 0
@@ -2491,9 +2610,43 @@ install_pi() {
# Validation
# ---------------------------------------------------------------------------
+# Cursor, TRAE, TRAE CN and ZCode run the same hook runtime; they differ only
+# in where their hooks and MCP entries live and in the session-start event name.
+validate_hook_host() { # validate_hook_host <client>
+ local client="$1" root="$OV_HOME/agent-integrations/$1" shared="$OV_HOME/agent-integrations/memory-plugin-shared/lib"
+ local hooks mcp event file complete=1
+ set -- "$root/scripts/hook.mjs" "$root/scripts/uri-guard.mjs" "$root/integration.json" "$shared/agent-hook-runtime.mjs"
+ case "$client" in
+ cursor)
+ hooks="$HOME/.cursor/hooks.json"; mcp="$(cursor_mcp_path)"; event=sessionStart
+ set -- "$@" "$root/plugin.json" "$shared/uri-guard.mjs" "$HOME/.cursor/rules/openviking-memory.mdc" \
+ "$HOME/.cursor/skills/openviking-memory/SKILL.md" "$HOME/.cursor/skills/openviking-skills/SKILL.md"
+ ;;
+ zcode) hooks="$HOME/.zcode/cli/config.json"; mcp="$hooks"; event=session-start ;;
+ *) hooks="$HOME/.$client/hooks.json"; mcp="$(trae_mcp_path "$client")"; event=session-start ;;
+ esac
+ for file in "$@"; do
+ [ -f "$file" ] || complete=0
+ done
+ grep -q 'scripts/hook.mjs' "$hooks" 2>/dev/null \
+ && grep -q 'scripts/uri-guard.mjs' "$hooks" 2>/dev/null \
+ && grep -q 'OPENVIKING_INTEGRATION_ID' "$hooks" 2>/dev/null \
+ && grep -q 'mcp-proxy.mjs' "$mcp" 2>/dev/null || complete=0
+ if [ "$complete" -eq 0 ]; then
+ warn "$client: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
+ return 1
+ fi
+ "$NODE_BIN" --check "$root/scripts/hook.mjs" && "$NODE_BIN" --check "$root/scripts/uri-guard.mjs" || return 1
+ if ! printf '%s' '{}' | OPENVIKING_MEMORY_ENABLED=0 "$NODE_BIN" "$root/scripts/hook.mjs" "$event" "$client" >/dev/null; then
+ warn "$client: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
+ return 1
+ fi
+ info "$client: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
+}
+
validate_install() {
- heading "$(t '5. Validation' '5. 安装校验')"
- local ok=1 agent_fatal=0 cached list bin
+ step_heading "$(t 'Validation' '安装校验')"
+ local ok=1 agent_fatal=0 cached list bin client
if contains_harness claude; then
while IFS= read -r bin; do
[ -n "$bin" ] || continue
@@ -2525,7 +2678,7 @@ EOF
ok=0
fi
if is_native_codex_bin; then
- cached=$(find "$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME" -name 'mcp-proxy.mjs' -path '*/servers/*' 2>/dev/null | sort | tail -n 1)
+ cached=$(find "$CODEX_DIR/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME" -name 'mcp-proxy.mjs' -path '*/servers/*' 2>/dev/null | sort | tail -n 1 || true)
if [ -n "$cached" ]; then
node --check "$cached" && info "codex: $(t 'cached stdio proxy parses' '缓存中的 stdio 代理语法正常') ($cached)" || ok=0
fi
@@ -2534,144 +2687,10 @@ EOF
$CODEX_BINS
EOF
fi
- if contains_harness cursor; then
- if grep -q 'scripts/hook.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
- && grep -q 'scripts/uri-guard.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
- && grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.cursor/hooks.json" 2>/dev/null \
- && grep -q 'mcp-proxy.mjs' "$HOME/.cursor/mcp.json" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/cursor/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/cursor/plugin.json" ] \
- && [ -f "$OV_HOME/agent-integrations/cursor/integration.json" ] \
- && [ -f "$HOME/.cursor/rules/openviking-memory.mdc" ] \
- && [ -f "$HOME/.cursor/skills/openviking-memory/SKILL.md" ] \
- && [ -f "$HOME/.cursor/skills/openviking-skills/SKILL.md" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" \
- || { ok=0; agent_fatal=1; }
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/cursor/scripts/uri-guard.mjs" \
- || { ok=0; agent_fatal=1; }
- if printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
- "$NODE_BIN" "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" sessionStart cursor >/dev/null; then
- info "cursor: $(t 'installed Hook runtime passed its smoke test' '已安装的 Hook 运行时通过 smoke test')"
- else
- warn "cursor: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
- ok=0; agent_fatal=1
- fi
- info "cursor: $(t 'integration installed (Hooks, MCP, Rule, Skill)' '集成已安装(Hook、MCP、Rule、Skill)')"
- else
- warn "cursor: $(t 'OpenViking integration installation is incomplete' 'OpenViking 集成安装不完整')"
- ok=0; agent_fatal=1
- fi
- fi
- if contains_harness trae; then
- local trae_mcp
- trae_mcp="$(trae_mcp_path trae)"
- if grep -q 'scripts/hook.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
- && grep -q 'scripts/uri-guard.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
- && grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.trae/hooks.json" 2>/dev/null \
- && grep -q 'mcp-proxy.mjs' "$trae_mcp" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae/integration.json" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" \
- || { ok=0; agent_fatal=1; }
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae/scripts/uri-guard.mjs" \
- || { ok=0; agent_fatal=1; }
- if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
- "$NODE_BIN" "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" session-start trae >/dev/null; then
- warn "trae: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
- ok=0; agent_fatal=1
- fi
- info "trae: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
- else
- warn "trae: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
- ok=0; agent_fatal=1
- fi
- fi
- if contains_harness trae-cn; then
- local trae_cn_mcp
- trae_cn_mcp="$(trae_mcp_path trae-cn)"
- if grep -q 'scripts/hook.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
- && grep -q 'scripts/uri-guard.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
- && grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
- && grep -q 'mcp-proxy.mjs' "$trae_cn_mcp" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae-cn/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae-cn/integration.json" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" \
- || { ok=0; agent_fatal=1; }
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cn/scripts/uri-guard.mjs" \
- || { ok=0; agent_fatal=1; }
- if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
- "$NODE_BIN" "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" session-start trae-cn >/dev/null; then
- warn "trae-cn: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
- ok=0; agent_fatal=1
- fi
- info "trae-cn: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
- else
- warn "trae-cn: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
- ok=0; agent_fatal=1
- fi
- fi
- if contains_harness trae-cli; then
- local trae_home="${TRAE_HOME:-$HOME/.trae}"
- local trae_cli_home="${TRAECLI_HOME:-$trae_home/cli}"
- local trae_cli_hooks="$trae_cli_home/hooks.json"
- local trae_cli_config="$trae_home/traecli.toml"
- if grep -q 'scripts/session-start.mjs' "$trae_cli_hooks" 2>/dev/null \
- && grep -q 'scripts/auto-recall.mjs' "$trae_cli_hooks" 2>/dev/null \
- && grep -q 'scripts/auto-capture.mjs' "$trae_cli_hooks" 2>/dev/null \
- && grep -q 'scripts/uri-guard.mjs' "$trae_cli_hooks" 2>/dev/null \
- && grep -q 'OPENVIKING_INTEGRATION_ID' "$trae_cli_hooks" 2>/dev/null \
- && grep -q '\[mcp_servers."openviking-memory"\]' "$trae_cli_config" 2>/dev/null \
- && grep -q 'mcp-proxy.mjs' "$trae_cli_config" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/trae-cli/scripts/trae-cli-hook.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae-cli/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae-cli/integration.json" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cli/scripts/trae-cli-hook.mjs" \
- || { ok=0; agent_fatal=1; }
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cli/scripts/uri-guard.mjs" \
- || { ok=0; agent_fatal=1; }
- if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
- "$NODE_BIN" "$OV_HOME/agent-integrations/trae-cli/scripts/session-start.mjs" >/dev/null; then
- warn "trae-cli: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
- ok=0; agent_fatal=1
- fi
- info "trae-cli: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
- else
- warn "trae-cli: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
- ok=0; agent_fatal=1
- fi
- fi
- if contains_harness zcode; then
- local zcode_config="$HOME/.zcode/cli/config.json"
- if grep -q 'scripts/hook.mjs' "$zcode_config" 2>/dev/null \
- && grep -q 'scripts/uri-guard.mjs' "$zcode_config" 2>/dev/null \
- && grep -q 'OPENVIKING_INTEGRATION_ID' "$zcode_config" 2>/dev/null \
- && grep -q 'mcp-proxy.mjs' "$zcode_config" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/zcode/scripts/hook.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/zcode/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/zcode/integration.json" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/zcode/scripts/hook.mjs" \
- || { ok=0; agent_fatal=1; }
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/zcode/scripts/uri-guard.mjs" \
- || { ok=0; agent_fatal=1; }
- if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
- "$NODE_BIN" "$OV_HOME/agent-integrations/zcode/scripts/hook.mjs" session-start zcode >/dev/null; then
- warn "zcode: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
- ok=0; agent_fatal=1
- fi
- info "zcode: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
- else
- warn "zcode: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
- ok=0; agent_fatal=1
- fi
- fi
+ for client in cursor trae trae-cn zcode; do
+ contains_harness "$client" || continue
+ validate_hook_host "$client" || { ok=0; agent_fatal=1; }
+ done
if contains_harness kimicode; then
local kimi_home="${KIMI_CODE_HOME:-$HOME/.kimi-code}"
local kimi_root="$kimi_home/plugins/managed/openviking-memory"
@@ -2699,7 +2718,7 @@ EOF
if contains_harness opencode; then
local ocfg="$HOME/.config/opencode/opencode.json"
local ocfgc="$HOME/.config/opencode/opencode.jsonc"
- if grep -q '@openviking/opencode-plugin' "$ocfg" "$ocfgc" 2>/dev/null || { [ -f "$HOME/.config/opencode/plugins/openviking.js" ] && [ -f "$HOME/.config/opencode/plugins/openviking/index.mjs" ]; }; then
+ if [ -f "$HOME/.config/opencode/plugins/openviking.js" ] && [ -f "$HOME/.config/opencode/plugins/openviking/index.mjs" ]; then
info "opencode: $PLUGIN_NAME $(t 'appears installed' '看起来已安装')"
else
warn "opencode: $PLUGIN_NAME $(t 'not found in config/plugin dir' '未在配置或插件目录中找到')"
@@ -2713,8 +2732,6 @@ EOF
fi
if [ -f "$HOME/.config/opencode/plugins/openviking/servers/mcp-proxy.mjs" ]; then
node --check "$HOME/.config/opencode/plugins/openviking/servers/mcp-proxy.mjs" || ok=0
- elif [ -f "$OV_HOME/opencode-mcp-proxy/openviking/servers/mcp-proxy.mjs" ]; then
- node --check "$OV_HOME/opencode-mcp-proxy/openviking/servers/mcp-proxy.mjs" || ok=0
else
warn "opencode: $(t 'OpenViking MCP proxy not found' '未找到 OpenViking MCP proxy')"
ok=0
@@ -2778,44 +2795,279 @@ EOF
fi
}
+# ---------------------------------------------------------------------------
+# Plan, confirmation and next steps
+# ---------------------------------------------------------------------------
+
+# Credentials, review and validation, plus one step per install.
+count_steps() {
+ local h
+ STEP_TOTAL=3
+ if contains_harness claude; then STEP_TOTAL=$((STEP_TOTAL + $(list_count "$CLAUDE_BINS"))); fi
+ if contains_harness codex; then STEP_TOTAL=$((STEP_TOTAL + $(list_count "$CODEX_BINS"))); fi
+ for h in cursor trae trae-cn zcode kimicode opencode pi dsh; do
+ if contains_harness "$h"; then STEP_TOTAL=$((STEP_TOTAL + 1)); fi
+ done
+}
+
+short_path() {
+ case "$1" in
+ "$HOME"/*) printf '%s%s' '~' "${1#"$HOME"}" ;;
+ *) printf '%s' "$1" ;;
+ esac
+}
+
+print_selection() {
+ info "$(t 'Selected harnesses:' '已选择:') $(printf '%s' "${PUBLIC_SELECTED_HARNESSES:-$SELECTED_HARNESSES}" | tr ',' ' ')"
+ if contains_harness claude; then info "$(t 'Claude-format commands:' 'Claude 格式命令:') $(list_words "$CLAUDE_BINS")"; fi
+ if [ -n "$TRAECODE_CLI_BIN" ]; then info "TraeCode CLI 2.0: $TRAECODE_CLI_BIN"; fi
+ if contains_harness codex && [ -z "$TRAECODE_CLI_BIN" ]; then info "$(t 'Codex-format commands:' 'Codex 格式命令:') $(list_words "$CODEX_BINS")"; fi
+ if contains_harness dsh; then info "$(t 'DeepSeek Harness profile:' 'DeepSeek Harness profile:') ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}"; fi
+}
+
+plan_item() { printf ' %s\n' "$*"; }
+
+plan_paths() { # plan_paths <label> <path...>
+ local label="$1" out="" path
+ shift
+ for path in "$@"; do out="${out:+$out, }$(short_path "$path")"; done
+ plan_item "$label: $out"
+}
+
+print_plan() {
+ local bundle origin fallback account user trae_home
+ if [ "$SOURCE_MODE" = "dev" ]; then
+ bundle="$(short_path "$CHECKOUT_DIR/examples")"
+ origin="$(t 'this checkout' '当前 checkout')"
+ else
+ bundle="$(short_path "$MKT_DIR_ARCHIVE")"
+ origin="$(t 'OpenViking release' 'OpenViking 发布版')"
+ fi
+ fallback="$(t 'fallback:' '失败时改用') $bundle"
+ account="$(cred_value "$CRED_ACCOUNT" "$CUR_ACCOUNT")"
+ user="$(cred_value "$CRED_USER" "$CUR_USER")"
+ step_heading "$(t 'Review' '确认安装内容')"
+ print_selection
+ info "$(t 'Server:' '服务地址:') $CRED_URL"
+ info "API key: $(mask_secret "$(cred_value "$CRED_KEY" "$CUR_KEY")")"
+ if [ -n "$account" ]; then info "account: $account"; fi
+ if [ -n "$user" ]; then info "user: $user"; fi
+ info "$(t 'Source:' '安装来源:') $origin"
+ info "$(t 'The install will change:' '安装将修改:')"
+ plan_item "$(short_path "$OVCLI_CONF")"
+ if contains_harness claude; then
+ while IFS= read -r CLAUDE_BIN; do
+ [ -n "$CLAUDE_BIN" ] || continue
+ command -v "$CLAUDE_BIN" >/dev/null 2>&1 || continue
+ has_plugin_subcommand || continue
+ if [ "$SOURCE_MODE" = "archive" ] && claude_supports_archive_source; then
+ plan_item "$CLAUDE_BIN plugin marketplace add/update $CC_TOS_MARKETPLACE_URL ($fallback)"
+ else
+ plan_item "$CLAUDE_BIN plugin marketplace add/update $bundle"
+ fi
+ plan_item "$CLAUDE_BIN plugin install/update $PLUGIN_ID"
+ if is_native_claude_bin && [ "$STATUSLINE_WRITE" -eq 1 ]; then
+ plan_item "$(short_path "$CC_SETTINGS") ($(t 'marketplace auto-update, statusline' 'marketplace 自动更新、statusline'))"
+ elif is_native_claude_bin; then
+ plan_item "$(short_path "$CC_SETTINGS") ($(t 'marketplace auto-update' 'marketplace 自动更新'))"
+ fi
+ done <<EOF
+$CLAUDE_BINS
+EOF
+ fi
+ if contains_harness codex; then
+ while IFS= read -r CODEX_BIN; do
+ [ -n "$CODEX_BIN" ] || continue
+ command -v "$CODEX_BIN" >/dev/null 2>&1 || continue
+ if [ "$SOURCE_MODE" = "archive" ]; then
+ plan_item "$CODEX_BIN plugin marketplace add/upgrade $CODEX_TOS_GIT_URL ($fallback)"
+ else
+ plan_item "$CODEX_BIN plugin marketplace add/upgrade $bundle"
+ fi
+ plan_item "$CODEX_BIN plugin add $PLUGIN_ID"
+ if is_native_codex_bin; then plan_item "$(short_path "$CODEX_CONFIG")"; fi
+ case "$(bin_basename "$CODEX_BIN")" in
+ trae-cli|traecli|traex)
+ trae_home="${TRAE_HOME:-$HOME/.trae}"
+ plan_paths "$(t 'Removes the deprecated TRAE CLI Hooks integration' '移除弃用的 TRAE CLI Hooks 集成')" \
+ "${TRAECLI_HOME:-$trae_home/cli}/hooks.json" "$trae_home/traecli.toml" "$OV_HOME/agent-integrations/trae-cli"
+ ;;
+ esac
+ done <<EOF
+$CODEX_BINS
+EOF
+ fi
+ if [ "$SOURCE_MODE" = "archive" ] && { contains_harness cursor || contains_harness trae || contains_harness trae-cn \
+ || contains_harness zcode || contains_harness kimicode || contains_harness opencode || contains_harness pi; }; then
+ plan_item "$bundle ($(t 'plugin bundle download' '下载插件包'))"
+ fi
+ if contains_harness cursor; then
+ plan_paths Cursor "$HOME/.cursor/hooks.json" "$(cursor_mcp_path)" "$HOME/.cursor/rules/openviking-memory.mdc" \
+ "$HOME/.cursor/skills/openviking-memory" "$HOME/.cursor/skills/openviking-skills" "$OV_HOME/agent-integrations/cursor"
+ fi
+ if contains_harness trae; then
+ plan_paths TRAE "$HOME/.trae/hooks.json" "$(trae_mcp_path trae)" "$OV_HOME/agent-integrations/trae"
+ fi
+ if contains_harness trae-cn; then
+ plan_paths "TRAE CN" "$HOME/.trae-cn/hooks.json" "$(trae_mcp_path trae-cn)" "$OV_HOME/agent-integrations/trae-cn"
+ fi
+ if contains_harness zcode; then
+ plan_paths ZCode "$HOME/.zcode/cli/config.json" "$HOME/.zcode/hooks.json" "$(zcode_mcp_path)" "$OV_HOME/agent-integrations/zcode"
+ fi
+ if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness zcode; then
+ plan_paths "$(t 'Shared hook runtime' '共享 hook 运行时')" "$OV_HOME/agent-integrations/memory-plugin-shared"
+ fi
+ if contains_harness kimicode; then
+ plan_paths "Kimi Code" "${KIMI_CODE_HOME:-$HOME/.kimi-code}/plugins" "$OV_HOME/agent-integrations/kimicode"
+ fi
+ if contains_harness opencode && command -v opencode >/dev/null 2>&1; then
+ plan_paths OpenCode "$HOME/.config/opencode/plugins/openviking" "$HOME/.config/opencode/plugins/openviking.js" "$(opencode_config_file)"
+ fi
+ if contains_harness pi && command -v pi >/dev/null 2>&1; then
+ plan_paths pi "$HOME/.pi/agent/extensions/openviking"
+ fi
+ if contains_harness dsh && command -v dsh >/dev/null 2>&1; then
+ plan_item "dsh plugin --profile ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT} add $DSH_PACKAGE@latest"
+ fi
+}
+
+# Without a tty nobody saw the connection menu, so a run that got no server
+# says loudly what it assumed and how to fix it.
+warn_default_connection() {
+ [ "$INTERACTIVE" -eq 0 ] && [ -z "$URL_ARG" ] && [ "$API_KEY_ARG" = "__OPENVIKING_UNSET__" ] \
+ && [ -z "$CUR_URL" ] && [ -z "$CUR_KEY" ] || return 0
+ local bins=""
+ [ -z "$CLAUDE_BINS_ARG" ] || bins="$bins --claude-bin $CLAUDE_BINS_ARG"
+ [ -z "$CODEX_BINS_ARG" ] || bins="$bins --codex-bin $CODEX_BINS_ARG"
+ printf '\n'
+ warn "${BOLD}$(t 'No server was given: the plugin is configured for http://127.0.0.1:1933 without an API key.' '未指定服务:插件将连接 http://127.0.0.1:1933,且不带 API key。')${RESET}"
+ warn "$(t 'To use another server, re-run with its URL and API key:' '如需连接其他服务,请带上服务地址和 API key 重新运行:')"
+ printf ' bash <(curl -fsSL %s/memory-plugin-shared/install.sh) --yes --harness %s%s --url <server-url> --api-key <api-key>\n\n' \
+ "$TOS_BASE" "${PUBLIC_SELECTED_HARNESSES:-$SELECTED_HARNESSES}" "$bins"
+}
+
+confirm_plan() {
+ TUI_MENU_QUIT=1 tui_menu "$(t 'Proceed with the install?' '开始安装?')" 0 "$(t 'Proceed' '继续')" "$(t 'Cancel' '取消')"
+ if [ "$TUI_MENU_CHOICE" -ne 0 ]; then
+ info "$(t 'Cancelled; nothing was changed.' '已取消,未做任何修改。')"
+ exit 0
+ fi
+}
+
+next_steps() { # next_steps <name> <next> <updates> <verify> <uninstall>
+ printf '\n %s%s%s\n' "$BOLD" "$1" "$RESET"
+ printf ' %s %s\n' "$(t 'Next:' '下一步:')" "$2"
+ printf ' %s %s\n' "$(t 'Updates:' '更新:')" "$3"
+ [ -z "$4" ] || printf ' %s %s\n' "$(t 'Verify:' '验证:')" "$4"
+ printf ' %s %s\n' "$(t 'Uninstall:' '卸载:')" "$5"
+}
+
+print_next_steps() {
+ local label updates rerun uninstall doctor client remove
+ rerun="$(t 're-run this installer' '重新运行本安装脚本')"
+ uninstall="bash <(curl -fsSL $TOS_BASE/memory-plugin-shared/install.sh) --uninstall --yes --harness"
+ heading "$(t 'Done' '完成')"
+ if [ -n "$RELEASE_VERSION" ]; then info "$(t 'Release:' '发布版本:') $RELEASE_VERSION"; fi
+ info "$(t 'Credentials:' '凭据:') $OVCLI_CONF"
+ info "$(t 'Reconfigure later by re-running this installer.' '之后可重跑本安装脚本重新配置。')"
+ if contains_harness claude; then
+ while IFS= read -r CLAUDE_BIN; do
+ [ -n "$CLAUDE_BIN" ] || continue
+ command -v "$CLAUDE_BIN" >/dev/null 2>&1 || continue
+ has_plugin_subcommand || continue
+ label="$(tui_bin_label claude "$CLAUDE_BIN")"
+ updates="$rerun"
+ if list_contains_line "$CLAUDE_URL_BINS" "$CLAUDE_BIN"; then
+ updates="$(t 'automatic; Claude Code checks in the background and loads a new version after a restart' '自动;Claude Code 在后台检查,重启后加载新版本')"
+ fi
+ next_steps "$label" "$(t "restart $label" "重启 $label")" "$updates" \
+ "$(t 'run /openviking-memory:ov in a session' '在会话中运行 /openviking-memory:ov')" \
+ "$CLAUDE_BIN plugin uninstall $PLUGIN_ID && $CLAUDE_BIN plugin marketplace remove $MARKETPLACE_NAME"
+ done <<EOF
+$CLAUDE_BINS
+EOF
+ fi
+ if contains_harness codex; then
+ while IFS= read -r CODEX_BIN; do
+ [ -n "$CODEX_BIN" ] || continue
+ command -v "$CODEX_BIN" >/dev/null 2>&1 || continue
+ label="$(codex_bin_label)"
+ updates="$rerun"
+ if list_contains_line "$CODEX_GIT_BINS" "$CODEX_BIN"; then
+ updates="$(t "automatic; $label upgrades the marketplace when it starts" "自动;$label 启动时升级 marketplace")"
+ fi
+ # Codex has only `plugin remove`, TraeCode CLI only `plugin uninstall`.
+ remove=remove
+ case "$(bin_basename "$CODEX_BIN")" in trae-cli|traecli|traex) remove=uninstall ;; esac
+ next_steps "$label" "$(t "restart $label" "重启 $label")" "$updates" \
+ "$(t "run the \$ov-memory-doctor skill in a session" "在会话中运行 \$ov-memory-doctor skill")" \
+ "$CODEX_BIN plugin $remove $PLUGIN_ID && $CODEX_BIN plugin marketplace remove $MARKETPLACE_NAME"
+ done <<EOF
+$CODEX_BINS
+EOF
+ fi
+ for client in cursor trae trae-cn zcode; do
+ contains_harness "$client" || continue
+ label="$(tui_bin_label "$client" "$client")"
+ doctor="node $(short_path "$OV_HOME/agent-integrations/$client/scripts/ov-memory-doctor.mjs")"
+ next_steps "$label" "$(t "restart $label" "重启 $label")" "$rerun" "$doctor" "$uninstall $client"
+ done
+ if contains_harness kimicode; then
+ next_steps "Kimi Code" "$(t 'run /reload or start a new session' '运行 /reload 或新建会话')" "$rerun" "" "$uninstall kimicode"
+ fi
+ if contains_harness opencode && command -v opencode >/dev/null 2>&1; then
+ next_steps OpenCode "$(t 'restart OpenCode' '重启 OpenCode')" "$rerun" "" \
+ "$(t "rm -rf ~/.config/opencode/plugins/openviking ~/.config/opencode/plugins/openviking.js, then remove mcp.openviking from $(short_path "$(opencode_config_file)")" "rm -rf ~/.config/opencode/plugins/openviking ~/.config/opencode/plugins/openviking.js,再删除 $(short_path "$(opencode_config_file)") 中的 mcp.openviking")"
+ fi
+ if contains_harness pi && command -v pi >/dev/null 2>&1; then
+ next_steps pi "$(t 'restart pi' '重启 pi')" "$rerun" "" "rm -rf ~/.pi/agent/extensions/openviking"
+ fi
+ if contains_harness dsh && command -v dsh >/dev/null 2>&1; then
+ next_steps "DeepSeek Harness" "$(t 'start a new dsh session' '新开一个 dsh 会话')" "$rerun" "" \
+ "dsh plugin --profile ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT} rm $DSH_PACKAGE"
+ fi
+}
+
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
select_language
+resolve_self_checkout
+reexec_release_installer ${INSTALLER_ARGS[@]+"${INSTALLER_ARGS[@]}"}
-heading "$(t '1. Environment check' '1. 环境检查')"
case "$(uname -s)" in
- Darwin|Linux) info "OS: $(uname -s)" ;;
+ Darwin|Linux) ;;
*) 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_BIN="$(command -v node)"
NODE_MAJOR="$("$NODE_BIN" -p 'Number(process.versions.node.split(".")[0])')"
[ "$NODE_MAJOR" -ge 18 ] || { err "Node.js 18+ required; found $("$NODE_BIN" --version)."; exit 1; }
-command -v curl >/dev/null 2>&1 || warn "curl not found; archive installs may fail."
+command -v curl >/dev/null 2>&1 || warn "$(t 'curl not found; the server check is skipped and downloads will fail.' '未找到 curl:将跳过服务检查,下载也会失败。')"
-resolve_self_checkout
select_harnesses
validate_selected_harnesses
select_compatible_bins
select_dsh_profile
refresh_available_harnesses
-info "$(t 'Selected harnesses:' '已选择:') $(printf '%s' "${PUBLIC_SELECTED_HARNESSES:-$SELECTED_HARNESSES}" | tr ',' ' ')"
-if contains_harness claude; then info "$(t 'Claude-format commands:' 'Claude 格式命令:') $(list_words "$CLAUDE_BINS")"; fi
-if [ -n "$TRAECODE_CLI_BIN" ]; then info "TraeCode CLI 2.0: $TRAECODE_CLI_BIN"; fi
-if contains_harness codex && [ -z "$TRAECODE_CLI_BIN" ]; then info "$(t 'Codex-format commands:' 'Codex 格式命令:') $(list_words "$CODEX_BINS")"; fi
-if contains_harness dsh; then info "$(t 'DeepSeek Harness profile:' 'DeepSeek Harness profile:') ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}"; fi
validate_selected_bins
if [ "$UNINSTALL" -eq 1 ]; then
+ print_selection
uninstall_agent_integrations
exit 0
fi
-select_dist
-
-configure_ovcli
resolve_source_mode
-prepare_marketplace_dir
+count_steps
+gather_credentials
+check_server
+choose_statusline
+print_plan
+warn_default_connection
+# Nothing under $OV_HOME or in any harness config is written before this point.
+confirm_plan
+resolve_release
+write_ovcli
if contains_harness claude; then
while IFS= read -r CLAUDE_BIN; do
@@ -2842,24 +3094,9 @@ if contains_harness opencode; then install_opencode; fi
if contains_harness pi; then install_pi; fi
if contains_harness dsh; then install_dsh; fi
validate_install
-
-heading "$(t 'Done' '完成')"
-info "$(t 'Credentials:' '凭据:') $OVCLI_CONF"
-case "$SOURCE_MODE" in
- remote) if contains_harness claude || contains_harness codex; then info "Marketplace: remote ($REPO_URL @ $REPO_REF)"; fi ;;
- *) if contains_harness claude || contains_harness codex; then info "Marketplace: ${MKT_DIR:-$CODEX_TOS_GIT_URL}"; fi ;;
-esac
-if contains_harness claude; then info "Claude-format: $(list_words "$CLAUDE_BINS") -> $PLUGIN_ID"; fi
-if [ -n "$TRAECODE_CLI_BIN" ]; then
- info "TraeCode CLI 2.0: $TRAECODE_CLI_BIN -> $PLUGIN_ID"
-elif contains_harness codex; then
- info "Codex-format: $(list_words "$CODEX_BINS") -> $PLUGIN_ID"
+print_next_steps
+# Earlier installers cloned the repository here; nothing uses it any more
+# unless a legacy hook or statusline in settings.json still points into it.
+if [ -d "$OV_HOME/openviking-repo" ] && ! grep -qF "$OV_HOME/openviking-repo" "$CC_SETTINGS" 2>/dev/null; then
+ info "$(t 'No longer used by the installer; you can delete it:' '安装程序已不再使用该目录,可以手动删除:') $OV_HOME/openviking-repo"
fi
-if contains_harness cursor; then info "Cursor: Hooks + MCP + Rule + Skill"; fi
-if contains_harness trae; then info "TRAE: ~/.trae/hooks.json + MCP"; fi
-if contains_harness trae-cn; then info "TRAE CN: ~/.trae-cn/hooks.json + MCP"; fi
-if contains_harness zcode; then info "ZCode: ~/.zcode/cli/config.json (hooks + MCP)"; fi
-if contains_harness kimicode; then info "Kimi Code: native plugin (hooks + MCP)"; fi
-if contains_harness opencode; then info "OpenCode: @openviking/opencode-plugin"; fi
-if contains_harness pi; then info "pi: ~/.pi/agent/extensions/openviking"; fi
-if contains_harness dsh; then info "DeepSeek Harness: $DSH_PACKAGE ($(t 'profile' '配置档') ${DSH_PROFILE:-$DSH_PROFILE_DEFAULT})"; fi
diff --git a/examples/memory-plugin-shared/lib/install/host-json-config.mjs b/examples/memory-plugin-shared/lib/install/host-json-config.mjs
index 1e0eb5abe..5e5e56c9b 100644
--- a/examples/memory-plugin-shared/lib/install/host-json-config.mjs
+++ b/examples/memory-plugin-shared/lib/install/host-json-config.mjs
@@ -291,7 +291,16 @@ const COMMANDS = {
"merge-zcode": ([configPath, hooksPath, mcpPath]) => mergeZcodeConfig({ configPath, hooksPath, mcpPath }),
};
-if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
const [command, ...argv] = process.argv.slice(2);
const run = COMMANDS[command];
if (!run) {
diff --git a/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs b/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs
index ddbcb9a92..83a80c8de 100644
--- a/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs
+++ b/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs
@@ -313,11 +313,24 @@ function appendStringToTopLevelArray(s, name, value) {
return `${s.slice(0, arrayRange.end)}${insertion}${s.slice(arrayRange.end)}`;
}
-/** The config text with the plugin registered and the MCP fallback pointed at `mcpProxy`. */
+const NPM_PACKAGE_SPEC = /^@openviking\/opencode-plugin(@.*)?$/;
+
+/**
+ * The config text with the plugin registered and the MCP fallback pointed at
+ * `mcpProxy`. Any other registration of the npm package is dropped, because
+ * OpenCode would load it next to the file plugin and run every hook twice.
+ */
export function updateOpencodeConfig(raw, { pluginSpec = "", mcpProxy = "" } = {}) {
let data = {};
try { data = raw.trim() ? JSON.parse(stripJsonc(raw)) : {}; } catch { data = {}; }
let nextRaw = raw.trim() ? raw : "{\n}\n";
+ if (Array.isArray(data.plugin)) {
+ const kept = data.plugin.filter((item) => item === pluginSpec || !NPM_PACKAGE_SPEC.test(item));
+ if (kept.length !== data.plugin.length) {
+ data.plugin = kept;
+ nextRaw = setTopLevelProperty(nextRaw, "plugin", kept);
+ }
+ }
if (pluginSpec) {
const next = Array.isArray(data.plugin) ? data.plugin.slice() : [];
if (!next.includes(pluginSpec)) {
@@ -344,7 +357,16 @@ export function updateOpencodeConfig(raw, { pluginSpec = "", mcpProxy = "" } = {
export { stripJsonc };
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
const file = process.argv[2];
let raw = "";
try { raw = fs.readFileSync(file, "utf8"); } catch {}
diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjs
index 3d3fe7e3b..c66aae2d6 100644
--- a/examples/memory-plugin-shared/release-marketplace.test.mjs
+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs
@@ -1,15 +1,22 @@
import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { execFile, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { dirname, join, resolve, sep } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const installer = join(ROOT, "examples", "memory-plugin-shared", "install.sh");
const stageScript = join(ROOT, ".github", "scripts", "stage-memory-plugin-marketplace.sh");
const archiveCheck = join(ROOT, ".github", "scripts", "check-marketplace-archive.mjs");
+const claudeMarketplaceScript = join(ROOT, ".github", "scripts", "generate-claude-marketplace-json.sh");
+const stampScript = join(ROOT, ".github", "scripts", "stamp-installer-version.sh");
+const publishGitScript = join(ROOT, ".github", "scripts", "publish-dumb-git-repo.sh");
+const zipScript = join(ROOT, ".github", "scripts", "reproducible-zip.sh");
function run(command, args, options = {}) {
return spawnSync(command, args, {
@@ -19,6 +26,200 @@ function run(command, args, options = {}) {
});
}
+function stageMarketplaceZip(tmp) {
+ const stage = join(tmp, "memory-plugin-marketplace");
+ const staged = run("bash", [stageScript, stage]);
+ assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);
+ const zip = join(tmp, "memory-plugin-marketplace.zip");
+ const zipped = run("zip", ["-rq", zip, "memory-plugin-marketplace"], { cwd: tmp });
+ assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+ return { stage, zip };
+}
+
+// A stand-in for the claude CLI: it records each invocation and keeps the one
+// marketplace registration the installer reads back through `--json`.
+function writeFakeClaude(bin) {
+ writeFileSync(join(bin, "claude"), `#!/bin/sh
+echo "$*" >> "$FAKE_CLAUDE_DIR/calls.log"
+case "$*" in
+ --version) echo "$FAKE_CLAUDE_VERSION (Claude Code)" ;;
+ "plugin marketplace list --json") cat "$FAKE_CLAUDE_DIR/marketplaces.json" 2>/dev/null || echo "[]" ;;
+ "plugin marketplace remove "*) rm -f "$FAKE_CLAUDE_DIR/marketplaces.json" ;;
+ "plugin marketplace add "*)
+ case "$4" in https://*) [ -z "$FAKE_CLAUDE_URL_FAILS" ] || exit 1 ;; esac
+ printf '[{"name":"openviking","path":"%s"}]' "$4" > "$FAKE_CLAUDE_DIR/marketplaces.json" ;;
+ "plugin install "*)
+ case "$(cat "$FAKE_CLAUDE_DIR/marketplaces.json" 2>/dev/null)" in *https://*) [ -z "$FAKE_CLAUDE_INSTALL_FAILS" ] || exit 1 ;; esac ;;
+esac
+exit 0
+`, { mode: 0o755 });
+}
+
+test("Claude URL marketplace lists the release's plugin zip as an archive source", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-claude-marketplace-"));
+ try {
+ const { stage } = stageMarketplaceZip(tmp);
+ const pluginZip = join(tmp, "openviking-memory-claude.zip");
+ const zipped = run("zip", ["-rq", pluginZip, "claude-code-memory-plugin"], { cwd: stage });
+ assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+ const out = join(tmp, "marketplace.json");
+ const generated = run("bash", [claudeMarketplaceScript, "v9.9.9", "https://tos.example.invalid/", pluginZip, stage, out]);
+ assert.equal(generated.status, 0, `${generated.stdout}\n${generated.stderr}`);
+
+ const manifest = JSON.parse(readFileSync(out, "utf8"));
+ const pluginJson = JSON.parse(readFileSync(join(stage, "claude-code-memory-plugin", ".claude-plugin", "plugin.json"), "utf8"));
+ assert.equal(manifest.name, "openviking");
+ assert.equal(manifest.plugins.length, 1);
+ const [entry] = manifest.plugins;
+ assert.equal(entry.name, "openviking-memory");
+ // Claude Code only updates an installed plugin when this string changes.
+ assert.equal(entry.version, pluginJson.version);
+ assert.deepEqual(entry.source, {
+ source: "archive",
+ url: "https://tos.example.invalid/releases/v9.9.9/openviking-memory-claude.zip",
+ sha256: createHash("sha256").update(readFileSync(pluginZip)).digest("hex"),
+ });
+
+ // Claude Code strips one wrapping directory, so the manifest must sit
+ // exactly one level down.
+ const listed = run("unzip", ["-Z1", pluginZip]);
+ assert.equal(listed.status, 0, listed.stderr);
+ assert.ok(listed.stdout.split("\n").includes("claude-code-memory-plugin/.claude-plugin/plugin.json"));
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+test("TOS installs register Claude Code's URL marketplace when the CLI supports archive sources", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-claude-tos-"));
+ try {
+ const { zip } = stageMarketplaceZip(tmp);
+ const bin = join(tmp, "bin");
+ const fake = join(tmp, "fake-claude");
+ mkdirSync(bin);
+ mkdirSync(fake);
+ writeFakeClaude(bin);
+ const home = join(tmp, "home");
+ mkdirSync(join(home, ".claude"), { recursive: true });
+ const marketplaceUrl = "https://tos.example.invalid/plugins/claude/marketplace.json";
+ const settingsPath = join(home, ".claude", "settings.json");
+ const readSettings = () => JSON.parse(readFileSync(settingsPath, "utf8"));
+ const calls = () => readFileSync(join(fake, "calls.log"), "utf8").split("\n");
+ const install = (version, extraEnv = {}) => {
+ rmSync(join(fake, "calls.log"), { force: true });
+ const result = run("bash", [
+ installer, "--harness", "claude", "--dist", "tos", "--lang", "en",
+ "--url", "http://127.0.0.1:9", "--api-key", "", "--no-statusline", "--yes",
+ ], {
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: `${bin}:${process.env.PATH}`,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_TOS_BASE: "https://tos.example.invalid",
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${zip}`,
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
+ FAKE_CLAUDE_DIR: fake,
+ FAKE_CLAUDE_VERSION: version,
+ ...extraEnv,
+ },
+ });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ return result;
+ };
+
+ // An install from the old archive channel is re-registered from the URL.
+ const archiveDir = join(home, ".openviking", "memory-plugin-marketplace");
+ writeFileSync(join(fake, "marketplaces.json"), JSON.stringify([{ name: "openviking", path: archiveDir }]));
+ install("2.1.224");
+ let log = calls();
+ assert.ok(log.includes("plugin uninstall openviking-memory@openviking"), log.join("\n"));
+ assert.ok(log.includes("plugin marketplace remove openviking"), log.join("\n"));
+ assert.ok(log.includes(`plugin marketplace add ${marketplaceUrl}`), log.join("\n"));
+ assert.ok(log.includes("plugin install openviking-memory@openviking"), log.join("\n"));
+ assert.deepEqual(readSettings().extraKnownMarketplaces.openviking, {
+ source: { source: "url", url: marketplaceUrl },
+ autoUpdate: true,
+ });
+
+ // A re-run refreshes the same registration and leaves a user's choice to
+ // turn auto-update off alone.
+ const settings = readSettings();
+ settings.extraKnownMarketplaces.openviking.autoUpdate = false;
+ writeFileSync(settingsPath, JSON.stringify(settings));
+ install("2.1.284");
+ log = calls();
+ assert.ok(log.includes("plugin marketplace update openviking"), log.join("\n"));
+ assert.equal(log.some((line) => line.startsWith("plugin marketplace add")), false, log.join("\n"));
+ assert.equal(readSettings().extraKnownMarketplaces.openviking.autoUpdate, false);
+
+ // Unreachable URL marketplace: fall back to the unpacked archive.
+ const failed = install("2.1.284", { FAKE_CLAUDE_URL_FAILS: "1", OPENVIKING_TOS_BASE: "https://other.example.invalid" });
+ log = calls();
+ assert.ok(log.includes(`plugin marketplace add ${archiveDir}`), log.join("\n"));
+ assert.match(failed.stdout + failed.stderr, /falling back to the archive directory/);
+
+ // So does a URL marketplace whose plugin cannot be installed, which
+ // otherwise leaves no plugin at all.
+ const uninstallable = install("2.1.284", { FAKE_CLAUDE_INSTALL_FAILS: "1" });
+ log = calls();
+ assert.equal(log.filter((line) => line === "plugin install openviking-memory@openviking").length, 2, log.join("\n"));
+ assert.ok(log.indexOf(`plugin marketplace add ${archiveDir}`) > log.indexOf(`plugin marketplace add ${marketplaceUrl}`), log.join("\n"));
+ assert.match(uninstallable.stdout, /Claude Code\n {4}Next: .*\n {4}Updates: re-run this installer\n/);
+
+ // Claude Code before the archive source keeps the local directory.
+ rmSync(join(fake, "marketplaces.json"), { force: true });
+ rmSync(settingsPath);
+ const legacy = install("2.1.223");
+ log = calls();
+ assert.ok(log.includes(`plugin marketplace add ${archiveDir}`), log.join("\n"));
+ assert.equal(log.some((line) => line.includes("https://")), false, log.join("\n"));
+ assert.equal(existsSync(settingsPath) && readSettings().extraKnownMarketplaces !== undefined, false);
+ assert.match(legacy.stdout, /Claude Code\n {4}Next: .*\n {4}Updates: re-run this installer\n/);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+test("a Claude-format wrapper sharing Claude Code's config keeps the URL marketplace", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-claude-wrapper-"));
+ try {
+ const bin = join(tmp, "bin");
+ const fake = join(tmp, "fake-claude");
+ const home = join(tmp, "home");
+ mkdirSync(bin);
+ mkdirSync(fake);
+ mkdirSync(home);
+ writeFakeClaude(bin);
+ writeFileSync(join(bin, "claude-wrap"), '#!/bin/sh\nexec claude "$@"\n', { mode: 0o755 });
+ const marketplaceUrl = "https://tos.example.invalid/plugins/claude/marketplace.json";
+
+ const result = run("bash", [
+ installer, "--harness", "claude", "--claude-bin", "claude,claude-wrap", "--dist", "tos", "--lang", "en",
+ "--url", "http://127.0.0.1:9", "--api-key", "", "--no-statusline", "--yes",
+ ], {
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: `${bin}:${process.env.PATH}`,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_TOS_BASE: "https://tos.example.invalid",
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
+ FAKE_CLAUDE_DIR: fake,
+ FAKE_CLAUDE_VERSION: "2.1.284",
+ },
+ });
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ const log = readFileSync(join(fake, "calls.log"), "utf8").split("\n");
+ assert.deepEqual(log.filter((line) => /^plugin (uninstall|marketplace (add|remove))/.test(line)), [
+ `plugin marketplace add ${marketplaceUrl}`,
+ ]);
+ assert.equal(JSON.parse(readFileSync(join(fake, "marketplaces.json"), "utf8"))[0].path, marketplaceUrl);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
test("release marketplace archive supports ZCode and pi TOS installs", () => {
const tmp = mkdtempSync(join(tmpdir(), "openviking-zcode-release-"));
try {
@@ -44,7 +245,7 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
"--dist", "tos",
"--source", "archive",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], {
@@ -53,6 +254,7 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
HOME: home,
OPENVIKING_HOME: join(home, ".openviking"),
OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(tmp, "memory-plugin-marketplace.zip")}`,
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
},
});
assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);
@@ -107,7 +309,7 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
"--dist", "tos",
"--source", "archive",
"--lang", "en",
- "--url", "http://127.0.0.1:1933",
+ "--url", "http://127.0.0.1:9",
"--api-key", "",
"--yes",
], {
@@ -117,6 +319,7 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
PATH: `${bin}:${process.env.PATH}`,
OPENVIKING_HOME: join(home, ".openviking"),
OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(tmp, "memory-plugin-marketplace.zip")}`,
+ OPENVIKING_SKIP_VERSION_CHECK: "1",
},
});
assert.equal(kimiInstalled.status, 0, kimiInstalled.stdout + kimiInstalled.stderr);
@@ -127,10 +330,10 @@ test("release marketplace archive supports ZCode and pi TOS installs", () => {
writeFileSync(join(bin, "pi"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const piArgs = [installer, "--harness", "pi", "--dist", "tos", "--source", "archive",
- "--lang", "en", "--url", "http://127.0.0.1:1933", "--api-key", "", "--yes"];
+ "--lang", "en", "--url", "http://127.0.0.1:9", "--api-key", "", "--yes"];
const piEnv = { ...process.env, HOME: home, PATH: bin + ":" + process.env.PATH,
OPENVIKING_HOME: join(home, ".openviking"),
- OPENVIKING_MARKETPLACE_ARCHIVE_URL: "file://" + join(tmp, "memory-plugin-marketplace.zip") };
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: "file://" + join(tmp, "memory-plugin-marketplace.zip"), OPENVIKING_SKIP_VERSION_CHECK: "1" };
const piInstalled = run("bash", piArgs, { env: piEnv });
assert.equal(piInstalled.status, 0, piInstalled.stdout + piInstalled.stderr);
const piRoot = join(home, ".pi", "agent", "extensions", "openviking");
@@ -201,3 +404,192 @@ test("staging rejects an archive missing a generated shared copy", () => {
rmSync(tmp, { recursive: true, force: true });
}
});
+
+test("published installer copies carry the release version and nothing else changes", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-installer-stamp-"));
+ try {
+ const original = readFileSync(installer, "utf8");
+ const out = join(tmp, "install.sh");
+ const stamped = run("bash", [stampScript, installer, "0.9.1", out]);
+ assert.equal(stamped.status, 0, `${stamped.stdout}\n${stamped.stderr}`);
+ assert.equal(readFileSync(installer, "utf8"), original);
+
+ const before = original.split("\n");
+ const after = readFileSync(out, "utf8").split("\n");
+ const changed = after.flatMap((line, index) => (line === before[index] ? [] : [line]));
+ assert.equal(after.length, before.length);
+ assert.deepEqual(changed, ['INSTALLER_VERSION="0.9.1"']);
+ // The bootstrap rejects a download without these, e.g. an HTML error page.
+ assert.match(after[0], /^#!.*bash/);
+ assert.ok(after.slice(0, 5).some((line) => line.includes("OpenViking Memory Plugin shared installer")));
+ const parsed = run("bash", ["-n", out]);
+ assert.equal(parsed.status, 0, parsed.stderr);
+
+ for (const [name, body] of [
+ ["missing", original.replace('INSTALLER_VERSION="dev"\n', "")],
+ ["duplicated", original.replace('INSTALLER_VERSION="dev"\n', 'INSTALLER_VERSION="dev"\nINSTALLER_VERSION="dev"\n')],
+ ]) {
+ const src = join(tmp, `${name}.sh`);
+ writeFileSync(src, body);
+ const rejected = run("bash", [stampScript, src, "0.9.1", join(tmp, `${name}-out.sh`)]);
+ assert.equal(rejected.status, 1, `${name}: ${rejected.stdout}\n${rejected.stderr}`);
+ assert.match(rejected.stderr, /expected one INSTALLER_VERSION="dev" line/);
+ assert.equal(existsSync(join(tmp, `${name}-out.sh`)), false);
+ }
+
+ for (const version of ["1.0/rc", '1.0"$(id)"']) {
+ const unsafe = run("bash", [stampScript, installer, version, join(tmp, "unsafe.sh")]);
+ assert.equal(unsafe.status, 1, `${version}: ${unsafe.stderr}`);
+ assert.equal(existsSync(join(tmp, "unsafe.sh")), false);
+ }
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+// A re-run of a release rebuilds its zips and overwrites the versioned keys,
+// while the manifests pinning their sha256 may stay as they were.
+test("rebuilding a release zip from the same commit gives the same bytes", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-reproducible-zip-"));
+ try {
+ const files = [join("plugin", "plugin.json"), join("plugin", "scripts", "hook.mjs"), join("plugin", "README.md")];
+ const build = (name, order, mtime) => {
+ const parent = join(tmp, name);
+ for (const file of order) {
+ mkdirSync(dirname(join(parent, file)), { recursive: true });
+ writeFileSync(join(parent, file), `${file}\n`);
+ utimesSync(join(parent, file), mtime, mtime);
+ }
+ const out = join(tmp, `${name}.zip`);
+ const zipped = run("bash", [zipScript, out, parent, "plugin"]);
+ assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+ return out;
+ };
+ const sha256 = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
+
+ const first = build("first", files, new Date("2020-01-01T00:00:00Z"));
+ const second = build("second", [...files].reverse(), new Date());
+ assert.equal(sha256(first), sha256(second));
+ const listed = run("unzip", ["-Z1", first]);
+ assert.equal(listed.status, 0, listed.stderr);
+ assert.deepEqual(listed.stdout.trim().split("\n"), [
+ "plugin/",
+ "plugin/README.md",
+ "plugin/plugin.json",
+ "plugin/scripts/",
+ "plugin/scripts/hook.mjs",
+ ]);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+// A stand-in for `aws s3 cp|sync` against one directory per bucket. It logs
+// each call and applies it the way the real command would for these arguments.
+const FAKE_AWS = `#!/usr/bin/env node
+const fs = require("node:fs");
+const path = require("node:path");
+const [, op, ...rest] = process.argv.slice(2);
+const args = [];
+const flags = [];
+for (let i = 0; i < rest.length; i += 1) {
+ if (!rest[i].startsWith("--")) args.push(rest[i]);
+ else if (["--endpoint-url", "--cache-control"].includes(rest[i])) flags.push(rest[i], rest[++i]);
+ else flags.push(rest[i]);
+}
+fs.appendFileSync(process.env.FAKE_AWS_LOG, JSON.stringify({ op, args, flags }) + "\\n");
+const local = (url) => (url.startsWith("s3://") ? path.join(process.env.FAKE_S3, url.slice(5)) : url);
+const [src, dest] = args.map(local);
+// Git writes pack files read-only, so replace rather than overwrite.
+const copy = (from, to) => {
+ if (fs.statSync(from).isDirectory()) {
+ for (const entry of fs.readdirSync(from)) copy(path.join(from, entry), path.join(to, entry));
+ return;
+ }
+ fs.mkdirSync(path.dirname(to), { recursive: true });
+ fs.rmSync(to, { force: true });
+ fs.copyFileSync(from, to);
+};
+copy(src, dest);
+if (op === "sync" && flags.includes("--delete")) {
+ for (const entry of fs.readdirSync(dest, { recursive: true })) {
+ const target = path.join(dest, entry);
+ if (fs.statSync(target).isFile() && !fs.existsSync(path.join(src, entry))) fs.rmSync(target);
+ }
+}
+`;
+
+test("the Codex git marketplace is replaced packs first, refs next, old objects last", async () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-dumb-git-"));
+ const gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", NO_PROXY: "*", no_proxy: "*" };
+ const git = (args, cwd) => {
+ const result = run("git", args, { cwd, env: gitEnv });
+ assert.equal(result.status, 0, `git ${args.join(" ")}\n${result.stdout}\n${result.stderr}`);
+ };
+ // Built the way the release workflow builds it.
+ const buildRepo = (release) => {
+ const src = join(tmp, `${release}-src`);
+ mkdirSync(src);
+ writeFileSync(join(src, "release.txt"), release);
+ git(["init", "-q", "-b", "main"], src);
+ git(["add", "-A"], src);
+ git(["-c", "[email protected]", "-c", "user.name=Release", "commit", "-qm", release], src);
+ const bare = join(tmp, `${release}.git`);
+ git(["clone", "-q", "--bare", src, bare], tmp);
+ git(["repack", "-adq"], bare);
+ git(["update-server-info"], bare);
+ return bare;
+ };
+
+ const bucket = join(tmp, "s3");
+ const bin = join(tmp, "bin");
+ mkdirSync(bin);
+ writeFileSync(join(bin, "aws"), FAKE_AWS, { mode: 0o755 });
+ const log = join(tmp, "aws.log");
+ const dest = "s3://bucket/plugins/memory-plugins.git";
+ const publish = (repo) => {
+ rmSync(log, { force: true });
+ const published = run("bash", [publishGitScript, repo, `${dest}/`, "--endpoint-url", "https://tos.example.invalid"], {
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, FAKE_S3: bucket, FAKE_AWS_LOG: log },
+ });
+ assert.equal(published.status, 0, `${published.stdout}\n${published.stderr}`);
+ return readFileSync(log, "utf8").trim().split("\n").map((line) => JSON.parse(line));
+ };
+
+ const server = createServer((req, res) => {
+ const file = join(bucket, decodeURIComponent(req.url.split("?")[0]));
+ if (!existsSync(file)) {
+ res.writeHead(404).end();
+ return;
+ }
+ res.writeHead(200, { "content-type": "application/octet-stream" }).end(readFileSync(file));
+ });
+ await new Promise((listening) => server.listen(0, "127.0.0.1", listening));
+ try {
+ publish(buildRepo("v1"));
+ const v2 = buildRepo("v2");
+ const calls = publish(v2);
+
+ const repoPath = (url) => url.slice(dest.length).replace(/^\//, "");
+ assert.deepEqual(
+ calls.map(({ op, args }) => [op, repoPath(args[1])]),
+ [["cp", "objects/pack"], ["cp", "objects/info/packs"], ["cp", "packed-refs"], ["cp", "info/refs"], ["cp", "HEAD"], ["sync", ""]],
+ );
+ assert.ok(calls.at(-1).flags.includes("--delete"));
+ for (const { flags } of calls) {
+ assert.equal(flags[flags.indexOf("--endpoint-url") + 1], "https://tos.example.invalid");
+ assert.match(flags[flags.indexOf("--cache-control") + 1], /no-store/);
+ }
+
+ // The previous release's pack is gone and the new one is what clients get.
+ const published = join(bucket, "bucket", "plugins", "memory-plugins.git");
+ assert.deepEqual(readdirSync(join(published, "objects", "pack")).sort(), readdirSync(join(v2, "objects", "pack")).sort());
+ const clone = join(tmp, "clone");
+ const { port } = server.address();
+ await promisify(execFile)("git", ["clone", "-q", `http://127.0.0.1:${port}/bucket/plugins/memory-plugins.git`, clone], { env: gitEnv });
+ assert.equal(readFileSync(join(clone, "release.txt"), "utf8"), "v2");
+ } finally {
+ server.close();
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index d1658da29..3e65e4c36 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
+import { realpathSync } from "node:fs";
import { access, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve as resolvePath, sep } from "node:path";
import { fileURLToPath } from "node:url";
@@ -376,10 +377,19 @@ async function main() {
}
}
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
// Guard the sync behind the entrypoint check so sync.test.mjs can import the
// target lists as the single source of truth instead of keeping its own copy —
// the duplicated lists had drifted, and a drifted vendored file passed CI.
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+if (isDirectRun()) {
main().catch((err) => {
process.stderr.write(`${err?.stack || err}\n`);
process.exit(1);
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index 3769028f5..ccc41315c 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.5.2",
+ "version": "0.5.3",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
diff --git a/examples/opencode-plugin/servers/mcp-proxy.mjs b/examples/opencode-plugin/servers/mcp-proxy.mjs
index 81b33fb6b..3a915cc06 100644
--- a/examples/opencode-plugin/servers/mcp-proxy.mjs
+++ b/examples/opencode-plugin/servers/mcp-proxy.mjs
@@ -8,6 +8,7 @@
* requests to the server's /mcp endpoint, and keeps stdout protocol-clean.
*/
+import { realpathSync } from "node:fs"
import { resolve as resolvePath } from "node:path"
import { fileURLToPath } from "node:url"
import { loadConfig } from "../lib/config.mjs"
@@ -21,6 +22,15 @@ export function readProxyConfig(env = process.env) {
return toMcpProxyConfig(loadConfig(PLUGIN_ROOT, undefined, { env }), { env })
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url)
+ }
+}
+
+if (isDirectRun()) {
createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start()
}
diff --git a/examples/pi-experimental-context-management/shared/credentials.mjs b/examples/pi-experimental-context-management/shared/credentials.mjs
index ba26a84dc..6e3b8123f 100644
--- a/examples/pi-experimental-context-management/shared/credentials.mjs
+++ b/examples/pi-experimental-context-management/shared/credentials.mjs
@@ -1,5 +1,5 @@
// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { readFileSync } from "node:fs";
+import { readFileSync, realpathSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
@@ -234,6 +234,15 @@ function main() {
process.exitCode = 2;
}
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
main();
}