Skip to content

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

feat(installer, openclaw-plugin): unified installer upgrade (#1020)

LinQiang391182a4d428f13
diff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.md
index b5e0ac00f..30d05af65 100644
--- a/examples/openclaw-plugin/INSTALL-ZH.md
+++ b/examples/openclaw-plugin/INSTALL-ZH.md
@@ -66,7 +66,9 @@ mv ~/.openclaw/extensions/memory-openviking ~/.openclaw/disabled-extensions/memo
### 正式安装
-#### 方式 A:npm 安装(推荐,全平台)
+#### 方式 A:npm 安装(推荐,含 Windows)
+
+**Windows** 与 macOS / Linux 相同:在 **PowerShell** 或 **cmd** 中执行下面的 `npm`、`npx`、`ov-install` 即可(需已安装 Node.js ≥ 22)。指定其它 OpenClaw 数据目录时,把 `--workdir` 换成本机路径(例如 `%USERPROFILE%\.openclaw-second`)。
```bash
npm install -g openclaw-openviking-setup-helper
@@ -84,6 +86,87 @@ ov-install -y
```bash
ov-install --workdir ~/.openclaw-second
```
+
+#### 指定版本(npm / `ov-install`)
+
+npm 上的安装助手包名为 [`openclaw-openviking-setup-helper`](https://www.npmjs.com/package/openclaw-openviking-setup-helper)。默认安装最新版;若需固定 **npm 上某一发布版本**,在包名后追加 `@VERSION`(VERSION 为 npm 上可见的 dist-tag 或版本号):
+
+```bash
+npm install -g openclaw-openviking-setup-helper
+ov-install -y
+```
+
+不全局安装、用 npx 直接跑(同样可在包名后加 `@VERSION` 固定安装助手版本):
+
+```bash
+npx -y -p openclaw-openviking-setup-helper ov-install -y
+```
+
+使用 **`ov-install`** 可指定 **插件代码对应的 Git 引用** 以及 **PyPI 上的 OpenViking 版本**:
+
+| 参数 | 含义 |
+| --- | --- |
+| `--github-repo owner/repo` | 从哪个 GitHub 仓库拉取插件文件(默认:`volcengine/OpenViking`) |
+| `--plugin-version REF` | 分支、tag 或 commit,用于拉取插件(默认:`main`) |
+| `--openviking-version VER` | 固定为 `pip install openviking==VER`(不写则安装 PyPI 最新版) |
+
+示例:
+
+```bash
+# 安装指定 tag 版本的插件(例如 v0.2.9)
+ov-install -y --plugin-version v0.2.9
+
+# 固定 PyPI 上的 OpenViking 版本,插件仍从 main 拉取
+ov-install -y --openviking-version 0.2.9
+
+# 同时指定插件 tag 和 OpenViking PyPI 版本
+ov-install -y --plugin-version v0.2.9 --openviking-version 0.2.9
+
+# 安装旧版插件链路(如需使用旧插件,请在 v0.2.3-v0.2.6 范围内选择版本)
+ov-install -y --plugin-version <legacy-version>
+```
+
+等价环境变量:`REPO`(同 `--github-repo`)、`PLUGIN_VERSION` / `BRANCH`、`OPENVIKING_VERSION`。
+
+#### 升级与回滚(`ov-install`)
+
+使用 `--update` / `--upgrade-plugin` 时,只会升级**插件本身**到指定 `--plugin-version`,不会升级 OpenViking 服务版本。该模式会:
+
+- 保留现有的 OpenViking 服务版本
+- 保留现有的 `~/.openviking/ov.conf`
+- 保留当前插件运行配置
+- 本地模式下保留 `configPath` 和 `port`
+- 远端模式下保留 `baseUrl`、`apiKey`、`agentId`
+- 只清理 `openclaw.json` 中 OpenViking 自己的插件配置,不影响其它插件
+- 在替换插件前备份 `openclaw.json` 和上一版插件目录
+- 在命令输出中记录升级路径和回滚审计文件位置
+
+不要把 `--update` 和 `--openviking-version` 一起使用;如果需要修改 OpenViking 服务版本,请走完整安装流程。
+
+```bash
+# 只升级插件到指定 tag
+ov-install --update --plugin-version v0.2.9
+
+# 只升级插件到指定分支
+ov-install --update --plugin-version dev-branch
+
+# 从指定 GitHub 仓库 + 分支升级插件
+ov-install --update --github-repo yourname/OpenViking --plugin-version dev-branch
+
+# 回滚最近一次插件升级
+ov-install --rollback
+```
+
+升级备份默认保存在:
+
+- `~/.openclaw/.openviking-upgrade-backup/openclaw.json.bak`
+- `~/.openclaw/.openviking-upgrade-backup/last-upgrade.json`
+- `~/.openclaw/disabled-extensions/<pluginId>-upgrade-backup-*`
+
+`--rollback` 会恢复最近一次 `--update` 生成的 `openclaw.json` 备份和插件目录备份。
+
+**Windows:** 升级与回滚命令与上表相同,在 PowerShell / cmd 中执行即可。
+
备注:在运行 `npm install -g openclaw-openviking-setup-helper` 命令时,可能会出现没有安装创建虚拟环境的工具的报错提示,可以直接复制报错提示中的解决方案执行:
```bash
@@ -105,6 +188,8 @@ ov-install
#### 方式 B(可选):curl 一键安装(Linux / macOS)
+**Windows** 请优先使用上文 **方式 A(`npm` / `ov-install`)**。`curl | bash` 需要 Bash 环境;若已在 **Git Bash** 或 **WSL** 中操作,可执行本节命令。
+
```bash
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash
```
@@ -112,18 +197,73 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples
非交互模式:
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -y
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- -y
```
安装到指定 OpenClaw 实例:
```bash
-curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- --workdir ~/.openclaw-second -y
```
-脚本会自动检测多个 OpenClaw 实例并让你选择。还会提示选择 local/remote 模式——remote 模式连接远端 OpenViking 服务,不需要安装 Python。
+#### 指定版本(`install.sh`)
-出现`installation completed`即代表安装成功。
+| 参数 / 环境变量 | 含义 |
+| --- | --- |
+| `--repo owner/repo`、`REPO` | 从哪个 GitHub 仓库拉取插件文件(默认:`volcengine/OpenViking`) |
+| `--plugin-version REF`、`PLUGIN_VERSION` | 分支、tag 或 commit(默认:`main`;兼容旧变量 `BRANCH`) |
+| `--openviking-version VER`、`OPENVIKING_VERSION` | `pip install openviking==VER`(不写则安装 PyPI 最新版) |
+
+示例:
+
+```bash
+# 安装指定 tag 版本的插件(例如 v0.2.9)
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --plugin-version v0.2.9 -y
+
+# 固定 PyPI 上的 OpenViking 版本
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --openviking-version 0.2.9 -y
+
+# 同时指定插件 tag 和 OpenViking PyPI 版本
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --plugin-version v0.2.9 --openviking-version 0.2.9 -y
+```
+
+#### 升级与回滚(`install.sh`)
+
+`curl | bash` 入口现在直接由 `install.sh` 原生执行升级和回滚逻辑,不依赖机器上预先安装全局安装助手,也支持“只升级插件”和“回滚最近一次插件升级”:
+
+```bash
+# 只升级插件到指定 tag
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --plugin-version v0.2.9
+
+# 只升级插件到指定分支
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --plugin-version dev-branch
+
+# 从指定 GitHub 仓库 + 分支升级插件
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --repo yourname/OpenViking --plugin-version dev-branch
+
+# 回滚最近一次插件升级
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --rollback
+```
+
+`--update` 模式只改插件,不改 OpenViking 服务版本,因此不要搭配 `--openviking-version`。
+
+Shell 原生升级行为:
+
+- 保留当前 local / remote 模式下的插件配置
+- 不会重写 `~/.openviking/ov.conf`
+- 会把 `openclaw.json` 备份到 `~/.openclaw/.openviking-upgrade-backup/openclaw.json.bak`
+- 会把回滚审计写到 `~/.openclaw/.openviking-upgrade-backup/last-upgrade.json`
+- 每个插件只保留一份最新的目录备份,位置在 `~/.openclaw/disabled-extensions/`
+- 升级成功后会打印 `Upgrade path: <from> -> <to>`
+
+`install.sh` 会检测本机多个 OpenClaw 实例并供选择;首次安装会询问 local/remote;仅升级插件时会复用现有模式与配置。
### 启动OpenClaw + OpenViking
@@ -132,6 +272,13 @@ curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
```bash
source ~/.openclaw/openviking.env && openclaw gateway restart
```
+
+Windows PowerShell 可使用:
+
+```powershell
+. "$HOME/.openclaw/openviking.env.ps1"
+openclaw gateway restart
+```
出现 `openviking: registered context-engine` 代表拉取成功。
接着,执行
@@ -362,12 +509,14 @@ openclaw config set plugins.entries.openviking.config.agentId "my-agent"
### `~/.openclaw/openviking.env`
-由安装助手自动生成,记录 Python 路径等环境变量:
+由安装器自动生成,记录 Python 路径等环境变量:
```bash
export OPENVIKING_PYTHON='/usr/local/bin/python3'
```
+在 Windows PowerShell 下,安装器会生成 `~/.openclaw/openviking.env.ps1`。
+
---
## 日常使用
diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.md
index 03eb51ecc..330d487f3 100644
--- a/examples/openclaw-plugin/INSTALL.md
+++ b/examples/openclaw-plugin/INSTALL.md
@@ -64,7 +64,9 @@ If the legacy plugin was using `plugins.entries.memory-openviking.config`, migra
Run the prerequisite steps above only if they apply to your environment. Once finished, continue with the Plugin 2.0 installation flow. For now, we do not recommend direct natural-language installation; the npm one-click installer is the preferred path.
-### Method A: npm Installation (Recommended, Cross-platform)
+### Method A: npm Installation (Recommended, Including Windows)
+
+**Windows:** use the same `npm`, `npx`, and `ov-install` commands in **PowerShell** or **cmd** (Node.js ≥ 22 required). For a non-default OpenClaw state directory, pass a real path to `--workdir` (e.g. `%USERPROFILE%\.openclaw-second`).
```bash
npm install -g openclaw-openviking-setup-helper
@@ -96,8 +98,90 @@ ov-install --workdir ~/.openclaw-second
```
+#### Pinning versions (npm / `ov-install`)
+
+The published helper package is [`openclaw-openviking-setup-helper`](https://www.npmjs.com/package/openclaw-openviking-setup-helper). Install globally (latest by default), or append `@VERSION` with a published dist-tag or version from npm when you need to pin the installer:
+
+```bash
+npm install -g openclaw-openviking-setup-helper
+ov-install -y
+```
+
+Run **without** global install (same optional `@VERSION` pin):
+
+```bash
+npx -y -p openclaw-openviking-setup-helper ov-install -y
+```
+
+Use **`ov-install`** to install a **specific archived plugin version** or pin the **OpenViking PyPI version**:
+
+| Flag | Meaning |
+| --- | --- |
+| `--github-repo owner/repo` | GitHub repo for plugin raw downloads (default: `volcengine/OpenViking`) |
+| `--plugin-version REF` | Git branch, tag, or commit for plugin files (default: `main`) |
+| `--openviking-version VER` | Pin `pip install openviking==VER` (omit for latest PyPI release) |
+
+Examples:
+
+```bash
+# Install a specific tagged plugin version (e.g. v0.2.9)
+ov-install -y --plugin-version v0.2.9
+
+# Pin OpenViking on PyPI, plugin from main
+ov-install -y --openviking-version 0.2.9
+
+# Pin both plugin tag and OpenViking PyPI version
+ov-install -y --plugin-version v0.2.9 --openviking-version 0.2.9
+
+# Legacy plugin line (use a release in the v0.2.3-v0.2.6 range if you need the old plugin line)
+ov-install -y --plugin-version <legacy-version>
+```
+
+Environment variables (same semantics): `REPO` (same as `--github-repo`), `PLUGIN_VERSION` / `BRANCH`, `OPENVIKING_VERSION`.
+
+#### Upgrade and rollback (`ov-install`)
+
+Use `--update` / `--upgrade-plugin` to upgrade **only the plugin** to a specific plugin ref. This mode:
+
+- keeps the existing OpenViking service version
+- keeps the existing `~/.openviking/ov.conf`
+- preserves the current plugin runtime settings
+- for local mode, keeps `configPath` and `port`
+- for remote mode, keeps `baseUrl`, `apiKey`, and `agentId`
+- cleans only the OpenViking plugin entries from `openclaw.json`, without touching unrelated plugins
+- backs up `openclaw.json` and the previous plugin directory before replacing the plugin
+- records the upgrade path and rollback audit file in the command output
+
+Do **not** combine `--update` with `--openviking-version`; changing the OpenViking service version still requires a full install flow.
+
+```bash
+# Upgrade only the plugin to a tagged release
+ov-install --update --plugin-version v0.2.9
+
+# Upgrade only the plugin to a branch
+ov-install --update --plugin-version dev-branch
+
+# Upgrade only the plugin from a specific GitHub repo + branch
+ov-install --update --github-repo yourname/OpenViking --plugin-version dev-branch
+
+# Roll back the last plugin upgrade
+ov-install --rollback
+```
+
+Upgrade backups are stored under:
+
+- `~/.openclaw/.openviking-upgrade-backup/openclaw.json.bak`
+- `~/.openclaw/.openviking-upgrade-backup/last-upgrade.json`
+- `~/.openclaw/disabled-extensions/<pluginId>-upgrade-backup-*`
+
+`--rollback` restores the latest saved `openclaw.json` snapshot and the previous plugin directory created by the last `--update`.
+
+**Windows:** the same `ov-install` upgrade and rollback commands work in PowerShell or cmd.
+
### Method B: curl One-Click Installation (Linux / macOS)
+On **Windows**, prefer **Method A** (`npm` / `ov-install`). `curl | bash` needs a Bash environment (**Git Bash** or **WSL**) if you use this section.
+
```bash
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash
@@ -106,18 +190,75 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples
Non-interactive mode:
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -y
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- -y
```
Install to a specific OpenClaw instance:
```bash
-curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- --workdir ~/.openclaw-second -y
+
+```
+
+#### Pinning versions (`install.sh`)
+
+| Flag / env | Meaning |
+| --- | --- |
+| `--repo owner/repo` / `REPO` | GitHub repo for plugin raw files (default: `volcengine/OpenViking`) |
+| `--plugin-version REF` / `PLUGIN_VERSION` | Git branch, tag, or commit (default: `main`; legacy: `BRANCH`) |
+| `--openviking-version VER` / `OPENVIKING_VERSION` | `pip install openviking==VER` (omit for latest) |
+
+Examples:
+
+```bash
+# Install a specific tagged plugin version (e.g. v0.2.9)
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --plugin-version v0.2.9 -y
+
+# Pin OpenViking on PyPI
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --openviking-version 0.2.9 -y
+
+# Pin both plugin tag and OpenViking PyPI version
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --plugin-version v0.2.9 --openviking-version 0.2.9 -y
+```
+
+#### Upgrade and rollback (`install.sh`)
+
+The `curl | bash` entry point now runs the same upgrade and rollback logic natively in `install.sh`. The target machine does not need a preinstalled global installer helper for plugin-only upgrade or rollback.
+
+```bash
+# Upgrade only the plugin to a tagged release
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --plugin-version v0.2.9
+
+# Upgrade only the plugin to a branch
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --plugin-version dev-branch
+# Upgrade only the plugin from a specific GitHub repo + branch
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --update --repo yourname/OpenViking --plugin-version dev-branch
+
+# Roll back the last plugin upgrade
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash -s -- \
+ --rollback
```
-The script will automatically detect multiple OpenClaw instances and let you choose. It will also prompt you to select local/remote mode—remote mode connects to a remote OpenViking service and does not require installing Python.
+`--update` only changes the plugin release. Do not pass `--openviking-version` in upgrade mode.
+
+Native shell upgrade behavior:
+
+- keeps the current local or remote plugin settings
+- does not rewrite `~/.openviking/ov.conf`
+- backs up `openclaw.json` to `~/.openclaw/.openviking-upgrade-backup/openclaw.json.bak`
+- writes rollback audit data to `~/.openclaw/.openviking-upgrade-backup/last-upgrade.json`
+- keeps only the latest plugin directory backup per plugin under `~/.openclaw/disabled-extensions/`
+- prints `Upgrade path: <from> -> <to>` after a successful upgrade
+
+The script will automatically detect multiple OpenClaw instances and let you choose. During a fresh install it also prompts you to select local or remote mode. During plugin-only upgrade it reuses the existing mode and config instead of prompting again.
### Start OpenClaw + OpenViking
@@ -125,6 +266,13 @@ The script will automatically detect multiple OpenClaw instances and let you cho
source ~/.openclaw/openviking.env && openclaw gateway restart
```
+On Windows PowerShell:
+
+```powershell
+. "$HOME/.openclaw/openviking.env.ps1"
+openclaw gateway restart
+```
+
Seeing `openviking: registered context-engine` indicates the plugin was loaded.
Then verify:
@@ -393,13 +541,15 @@ If not configured, the plugin auto-generates a unique ID in the format `openclaw
### `~/.openclaw/openviking.env`
-Automatically generated by the setup helper, recording environment variables such as the Python path:
+Automatically generated by the installer, recording environment variables such as the Python path:
```bash
export OPENVIKING_PYTHON='/usr/local/bin/python3'
```
+On Windows PowerShell, the installer writes `~/.openclaw/openviking.env.ps1` instead.
+
---
## Daily Usage
diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.json
new file mode 100644
index 000000000..dfd29e691
--- /dev/null
+++ b/examples/openclaw-plugin/install-manifest.json
@@ -0,0 +1,37 @@
+{
+ "manifestVersion": "1.0",
+ "pluginVersion": "2026.3.25",
+ "plugin": {
+ "id": "openviking",
+ "kind": "context-engine",
+ "slot": "contextEngine"
+ },
+ "files": {
+ "required": [
+ "index.ts",
+ "config.ts",
+ "package.json"
+ ],
+ "optional": [
+ "context-engine.ts",
+ "client.ts",
+ "process-manager.ts",
+ "memory-ranking.ts",
+ "text-utils.ts",
+ "tool-call-id.ts",
+ "session-transcript-repair.ts",
+ "openclaw.plugin.json",
+ "tsconfig.json",
+ "package-lock.json",
+ ".gitignore"
+ ]
+ },
+ "npm": {
+ "install": true,
+ "omitDev": true
+ },
+ "compatibility": {
+ "minOpenclawVersion": "2026.3.7",
+ "minOpenvikingVersion": "0.2.9"
+ }
+}
diff --git a/examples/openclaw-plugin/install.ps1 b/examples/openclaw-plugin/install.ps1
deleted file mode 100644
index f7e84434a..000000000
--- a/examples/openclaw-plugin/install.ps1
+++ /dev/null
@@ -1,474 +0,0 @@
-param(
- [switch]$Yes,
- [switch]$Zh,
- [string]$Workdir = ""
-)
-
-$ErrorActionPreference = "Stop"
-
-function T {
- param(
- [string]$En,
- [string]$ZhText
- )
- if ($Zh) { return $ZhText }
- return $En
-}
-
-function Info($m) { Write-Host "[INFO] $m" -ForegroundColor Green }
-function Warn($m) { Write-Host "[WARN] $m" -ForegroundColor Yellow }
-function Err($m) { Write-Host "[ERROR] $m" -ForegroundColor Red }
-function Title($m) { Write-Host $m -ForegroundColor Cyan }
-function Write-Utf8NoBom {
- param(
- [string]$Path,
- [string]$Content
- )
- $enc = New-Object System.Text.UTF8Encoding($false)
- [System.IO.File]::WriteAllText($Path, $Content, $enc)
-}
-
-$Repo = if ($env:REPO) { $env:REPO } else { "volcengine/OpenViking" }
-$Branch = if ($env:BRANCH) { $env:BRANCH } else { "main" }
-$NpmRegistry = if ($env:NPM_REGISTRY) { $env:NPM_REGISTRY } else { "https://registry.npmmirror.com" }
-$PipIndexUrl = if ($env:PIP_INDEX_URL) { $env:PIP_INDEX_URL } else { "https://pypi.tuna.tsinghua.edu.cn/simple" }
-
-$HomeDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
-$OpenClawDir = if ($Workdir) { $Workdir } else { Join-Path $HomeDir ".openclaw" }
-$OpenVikingDir = Join-Path $HomeDir ".openviking"
-$PluginDest = Join-Path $OpenClawDir "extensions\openviking"
-$SelectedMode = "local"
-
-$DefaultServerPort = 1933
-$DefaultAgfsPort = 1833
-$DefaultVlmModel = "doubao-seed-2-0-pro-260215"
-$DefaultEmbeddingModel = "doubao-embedding-vision-251215"
-
-function Get-PythonCommand {
- if ($env:OPENVIKING_PYTHON) { return $env:OPENVIKING_PYTHON }
- if (Get-Command python -ErrorAction SilentlyContinue) { return "python" }
- if (Get-Command python3 -ErrorAction SilentlyContinue) { return "python3" }
- return $null
-}
-
-function Check-Python {
- $py = Get-PythonCommand
- if (-not $py) {
- return @{ Ok = $false; Detail = (T "Python not found. Install Python >= 3.10." "Python 未找到,请安装 Python >= 3.10") }
- }
- try {
- $v = & $py -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>$null
- if (-not $v) {
- return @{ Ok = $false; Detail = (T "Python command failed." "Python 命令执行失败") }
- }
- $parts = $v.Trim().Split(".")
- $major = [int]$parts[0]
- $minor = [int]$parts[1]
- if ($major -lt 3 -or ($major -eq 3 -and $minor -lt 10)) {
- return @{ Ok = $false; Detail = (T "Python $v is too old. Need >= 3.10." "Python 版本 $v 过低,需要 >= 3.10") }
- }
- return @{ Ok = $true; Detail = "$v ($py)"; Cmd = $py }
- } catch {
- return @{ Ok = $false; Detail = $_.Exception.Message }
- }
-}
-
-function Check-Node {
- try {
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
- return @{ Ok = $false; Detail = (T "Node.js not found. Install Node.js >= 22." "Node.js 未找到,请安装 Node.js >= 22") }
- }
- $v = (node -v).Trim()
- $major = [int]($v.TrimStart("v").Split(".")[0])
- if ($major -lt 22) {
- return @{ Ok = $false; Detail = (T "Node.js $v is too old. Need >= 22." "Node.js 版本 $v 过低,需要 >= 22") }
- }
- return @{ Ok = $true; Detail = $v }
- } catch {
- return @{ Ok = $false; Detail = $_.Exception.Message }
- }
-}
-
-function Validate-Environment {
- Info (T "Checking OpenViking runtime environment..." "正在校验 OpenViking 运行环境...")
- Write-Host ""
-
- $missing = @()
-
- $py = Check-Python
- if ($py.Ok) {
- Info (" Python: {0} ✓" -f $py.Detail)
- } else {
- $missing += "Python >= 3.10"
- Err (" {0}" -f $py.Detail)
- }
-
- $node = Check-Node
- if ($node.Ok) {
- Info (" Node.js: {0} ✓" -f $node.Detail)
- } else {
- $missing += "Node.js >= 22"
- Err (" {0}" -f $node.Detail)
- }
-
- if ($missing.Count -gt 0) {
- Write-Host ""
- Err (T "Environment check failed. Install missing dependencies first." "环境校验未通过,请先安装以下缺失组件。")
- Write-Host ""
- if ($missing -contains "Python >= 3.10") {
- Write-Host (T "Python (example via winget):" "Python(可使用 winget 安装示例):")
- Write-Host " winget install --id Python.Python.3.11 -e"
- Write-Host ""
- }
- if ($missing -contains "Node.js >= 22") {
- Write-Host (T "Node.js (example via nvm-windows):" "Node.js(可使用 nvm-windows 安装示例):")
- Write-Host " nvm install 22.22.0"
- Write-Host " nvm use 22.22.0"
- Write-Host ""
- }
- exit 1
- }
-
- Write-Host ""
- Info (T "Environment check passed ✓" "环境校验通过 ✓")
- Write-Host ""
-}
-
-function Check-OpenClaw {
- if ($env:SKIP_OPENCLAW -eq "1") {
- Info (T "Skipping OpenClaw check (SKIP_OPENCLAW=1)" "跳过 OpenClaw 校验 (SKIP_OPENCLAW=1)")
- return
- }
-
- Info (T "Checking OpenClaw..." "正在校验 OpenClaw...")
- if (Get-Command openclaw -ErrorAction SilentlyContinue) {
- Info (T "OpenClaw detected ✓" "OpenClaw 已安装 ✓")
- return
- }
-
- Err (T "OpenClaw not found. Install it manually, then rerun this script." "未检测到 OpenClaw,请先手动安装后再执行本脚本")
- Write-Host ""
- Write-Host (T "Recommended command:" "推荐命令:")
- Write-Host " npm install -g openclaw --registry $NpmRegistry"
- Write-Host ""
- Write-Host " openclaw --version"
- Write-Host " openclaw onboard"
- Write-Host ""
- exit 1
-}
-
-function Install-OpenViking {
- if ($env:SKIP_OPENVIKING -eq "1") {
- Info (T "Skipping OpenViking install (SKIP_OPENVIKING=1)" "跳过 OpenViking 安装 (SKIP_OPENVIKING=1)")
- return
- }
-
- $py = (Check-Python).Cmd
- Info (T "Installing OpenViking from PyPI..." "正在安装 OpenViking (PyPI)...")
- Info ("{0} {1}" -f (T "Using pip index:" "使用 pip 镜像源:"), $PipIndexUrl)
- & $py -m pip install --upgrade pip -i $PipIndexUrl | Out-Host
- & $py -m pip install openviking -i $PipIndexUrl | Out-Host
- Info (T "OpenViking installed ✓" "OpenViking 安装完成 ✓")
-}
-
-function Prompt-OrDefault {
- param(
- [string]$PromptText,
- [string]$DefaultValue
- )
- $v = Read-Host "$PromptText [$DefaultValue]"
- if ([string]::IsNullOrWhiteSpace($v)) { return $DefaultValue }
- return $v.Trim()
-}
-
-function Prompt-Optional {
- param([string]$PromptText)
- $v = Read-Host $PromptText
- if ([string]::IsNullOrWhiteSpace($v)) { return "" }
- return $v.Trim()
-}
-
-function Select-Workdir {
- # Already set via -Workdir
- $defaultDir = Join-Path $HomeDir ".openclaw"
- if ($OpenClawDir -ne $defaultDir) { return }
-
- $instances = @()
- Get-ChildItem -Path $HomeDir -Directory -Filter ".openclaw*" -ErrorAction SilentlyContinue | ForEach-Object {
- $name = $_.Name
- if ($name -eq ".openclaw" -or $name -like ".openclaw-*") {
- $instances += $_.FullName
- }
- }
-
- if ($instances.Count -le 1) { return }
-
- if (-not $Yes) {
- Write-Host ""
- Title (T "Found multiple OpenClaw instances:" "发现多个 OpenClaw 实例:")
- for ($i = 0; $i -lt $instances.Count; $i++) {
- Write-Host " $($i + 1)) $($instances[$i])"
- }
- Write-Host ""
- $choice = Prompt-OrDefault (T "Select instance number" "选择实例编号") "1"
- $idx = [int]$choice - 1
- if ($idx -ge 0 -and $idx -lt $instances.Count) {
- $script:OpenClawDir = $instances[$idx]
- } else {
- Warn (T "Invalid selection, using default" "无效选择,使用默认")
- $script:OpenClawDir = $instances[0]
- }
- $script:PluginDest = Join-Path $script:OpenClawDir "extensions\openviking"
- }
-}
-
-function Select-Mode {
- if ($Yes) {
- $script:SelectedMode = "local"
- return
- }
- $mode = Prompt-OrDefault (T "Plugin mode (local/remote)" "插件模式 (local/remote)") "local"
- if ($mode -eq "remote") {
- $script:SelectedMode = "remote"
- } else {
- $script:SelectedMode = "local"
- }
-}
-
-function Collect-RemoteConfig {
- $script:RemoteBaseUrl = "http://127.0.0.1:1933"
- $script:RemoteApiKey = ""
- $script:RemoteAgentId = ""
- if (-not $Yes) {
- $script:RemoteBaseUrl = Prompt-OrDefault (T "OpenViking server URL" "OpenViking 服务器地址") $script:RemoteBaseUrl
- $script:RemoteApiKey = Prompt-Optional (T "API Key (optional)" "API Key(可选)")
- $script:RemoteAgentId = Prompt-Optional (T "Agent ID (optional)" "Agent ID(可选)")
- }
-}
-
-function Configure-OvConf {
- New-Item -ItemType Directory -Force -Path $OpenVikingDir | Out-Null
-
- $workspace = Join-Path $OpenVikingDir "data"
- $serverPort = "$DefaultServerPort"
- $agfsPort = "$DefaultAgfsPort"
- $vlmModel = $DefaultVlmModel
- $embeddingModel = $DefaultEmbeddingModel
-
- $legacyKey = if ($env:OPENVIKING_ARK_API_KEY) { $env:OPENVIKING_ARK_API_KEY } else { "" }
- $vlmApiKey = if ($env:OPENVIKING_VLM_API_KEY) { $env:OPENVIKING_VLM_API_KEY } else { $legacyKey }
- $embeddingApiKey = if ($env:OPENVIKING_EMBEDDING_API_KEY) { $env:OPENVIKING_EMBEDDING_API_KEY } else { $legacyKey }
-
- if (-not $Yes) {
- Write-Host ""
- $workspace = Prompt-OrDefault (T "OpenViking workspace path" "OpenViking 数据目录") $workspace
- $serverPort = Prompt-OrDefault (T "OpenViking HTTP port" "OpenViking HTTP 端口") $serverPort
- $agfsPort = Prompt-OrDefault (T "AGFS port" "AGFS 端口") $agfsPort
- $vlmModel = Prompt-OrDefault (T "VLM model" "VLM 模型") $vlmModel
- $embeddingModel = Prompt-OrDefault (T "Embedding model" "Embedding 模型") $embeddingModel
- Write-Host (T "VLM and Embedding API keys can differ. You can leave either empty and edit ov.conf later." "说明:VLM 与 Embedding 的 API Key 可能不同,可分别填写;留空后续可在 ov.conf 修改。")
- $vlmInput = Prompt-Optional (T "VLM API key (optional)" "VLM API Key(可留空)")
- $embInput = Prompt-Optional (T "Embedding API key (optional)" "Embedding API Key(可留空)")
- if ($vlmInput) { $vlmApiKey = $vlmInput }
- if ($embInput) { $embeddingApiKey = $embInput }
- }
-
- New-Item -ItemType Directory -Force -Path $workspace | Out-Null
-
- $cfg = @{
- server = @{
- host = "127.0.0.1"
- port = [int]$serverPort
- root_api_key = $null
- cors_origins = @("*")
- }
- storage = @{
- workspace = $workspace
- vectordb = @{ name = "context"; backend = "local"; project = "default" }
- agfs = @{ port = [int]$agfsPort; log_level = "warn"; backend = "local"; timeout = 10; retry_times = 3 }
- }
- embedding = @{
- dense = @{
- provider = "volcengine"
- api_key = $(if ($embeddingApiKey) { $embeddingApiKey } else { $null })
- model = $embeddingModel
- api_base = "https://ark.cn-beijing.volces.com/api/v3"
- dimension = 1024
- input = "multimodal"
- }
- }
- log = @{
- level = "WARNING"
- format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
- output = "file"
- rotation = $true
- rotation_days = 3
- rotation_interval = "midnight"
- }
- vlm = @{
- provider = "volcengine"
- api_key = $(if ($vlmApiKey) { $vlmApiKey } else { $null })
- model = $vlmModel
- api_base = "https://ark.cn-beijing.volces.com/api/v3"
- temperature = 0.1
- max_retries = 3
- }
- }
-
- $confPath = Join-Path $OpenVikingDir "ov.conf"
- $cfgJson = $cfg | ConvertTo-Json -Depth 10
- Write-Utf8NoBom -Path $confPath -Content $cfgJson
- Info ("{0} {1}" -f (T "Config generated:" "已生成配置:"), $confPath)
- return [int]$serverPort
-}
-
-function Download-Plugin {
- $rawBase = "https://raw.githubusercontent.com/$Repo/$Branch"
- $files = @(
- "examples/openclaw-plugin/index.ts",
- "examples/openclaw-plugin/context-engine.ts",
- "examples/openclaw-plugin/config.ts",
- "examples/openclaw-plugin/client.ts",
- "examples/openclaw-plugin/process-manager.ts",
- "examples/openclaw-plugin/memory-ranking.ts",
- "examples/openclaw-plugin/text-utils.ts",
- "examples/openclaw-plugin/openclaw.plugin.json",
- "examples/openclaw-plugin/package.json",
- "examples/openclaw-plugin/package-lock.json",
- "examples/openclaw-plugin/tsconfig.json",
- "examples/openclaw-plugin/.gitignore"
- )
-
- New-Item -ItemType Directory -Force -Path $PluginDest | Out-Null
- Info (T "Downloading openviking plugin..." "正在下载 openviking 插件...")
- Info ("{0} $Repo@$Branch" -f (T "Plugin source:" "插件来源:"))
-
- foreach ($rel in $files) {
- $name = Split-Path $rel -Leaf
- $url = "$rawBase/$rel"
- $dst = Join-Path $PluginDest $name
- try {
- Invoke-WebRequest -Uri $url -OutFile $dst -UseBasicParsing | Out-Null
- } catch {
- Err ("{0} $url" -f (T "Download failed:" "下载失败:"))
- throw
- }
- }
-
- Push-Location $PluginDest
- try {
- npm install --no-audit --no-fund | Out-Host
- } finally {
- Pop-Location
- }
- Info ("{0} $PluginDest" -f (T "Plugin deployed:" "插件部署完成:"))
-}
-
-function Configure-OpenClawPlugin {
- param([int]$ServerPort)
- Info (T "Configuring OpenClaw plugin..." "正在配置 OpenClaw 插件...")
-
- $oldStateDir = $env:OPENCLAW_STATE_DIR
- if ($OpenClawDir -ne (Join-Path $HomeDir ".openclaw")) {
- $env:OPENCLAW_STATE_DIR = $OpenClawDir
- }
-
- try {
- # Enable plugin (files already deployed to extensions dir by Deploy-Plugin)
- openclaw plugins enable openviking
- if ($LASTEXITCODE -ne 0) { throw "openclaw plugins enable failed (exit code $LASTEXITCODE)" }
- openclaw config set plugins.slots.contextEngine openviking
-
- # Set gateway mode
- openclaw config set gateway.mode local
-
- # Set plugin config for the selected mode
- if ($SelectedMode -eq "local") {
- $ovConfPath = Join-Path $OpenVikingDir "ov.conf"
- openclaw config set plugins.entries.openviking.config.mode local
- openclaw config set plugins.entries.openviking.config.configPath $ovConfPath
- openclaw config set plugins.entries.openviking.config.port $ServerPort
- } else {
- openclaw config set plugins.entries.openviking.config.mode remote
- openclaw config set plugins.entries.openviking.config.baseUrl $RemoteBaseUrl
- if ($RemoteApiKey) {
- openclaw config set plugins.entries.openviking.config.apiKey $RemoteApiKey
- }
- if ($RemoteAgentId) {
- openclaw config set plugins.entries.openviking.config.agentId $RemoteAgentId
- }
- }
-
- Info (T "OpenClaw plugin configured" "OpenClaw 插件配置完成")
- } finally {
- $env:OPENCLAW_STATE_DIR = $oldStateDir
- }
-}
-
-function Write-OpenVikingEnv {
- $pyCmd = Get-PythonCommand
- $pyPath = ""
- if ($pyCmd) {
- $g = Get-Command $pyCmd -ErrorAction SilentlyContinue
- if ($g) { $pyPath = $g.Source }
- }
-
- New-Item -ItemType Directory -Force -Path $OpenClawDir | Out-Null
- $envPath = Join-Path $OpenClawDir "openviking.env.ps1"
- $envContent = '$env:OPENVIKING_PYTHON = "' + $pyPath + '"'
- Write-Utf8NoBom -Path $envPath -Content $envContent
-
- Info ("{0} $envPath" -f (T "Environment file generated:" "已生成环境文件:"))
-}
-
-Title (T "🦣 OpenClaw + OpenViking Installer" "🦣 OpenClaw + OpenViking 一键安装")
-Write-Host ""
-
-Select-Workdir
-Info ("{0} $OpenClawDir" -f (T "Target:" "目标实例:"))
-
-Select-Mode
-Info ("{0} $SelectedMode" -f (T "Mode:" "模式:"))
-
-$serverPort = $DefaultServerPort
-if ($SelectedMode -eq "local") {
- Validate-Environment
- Check-OpenClaw
- Install-OpenViking
- $serverPort = Configure-OvConf
-} else {
- Check-OpenClaw
- Collect-RemoteConfig
-}
-
-Download-Plugin
-Configure-OpenClawPlugin -ServerPort $serverPort
-
-if ($SelectedMode -eq "local") {
- Write-OpenVikingEnv
-}
-
-Write-Host ""
-Title "═══════════════════════════════════════════════════════════"
-Title (" {0}" -f (T "Installation complete!" "安装完成!"))
-Title "═══════════════════════════════════════════════════════════"
-Write-Host ""
-
-if ($SelectedMode -eq "local") {
- Info (T "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")
- Write-Host " 1) openclaw --version"
- Write-Host " 2) openclaw onboard"
- Write-Host " 3) . `"$OpenClawDir\openviking.env.ps1`"; openclaw gateway"
- Write-Host " 4) openclaw status"
- Write-Host ""
- Info ("{0} $OpenVikingDir\ov.conf" -f (T "You can edit the config freely:" "你可以按需自由修改配置文件:"))
-} else {
- Info (T "Run these commands to start OpenClaw:" "请按以下命令启动 OpenClaw:")
- Write-Host " 1) openclaw --version"
- Write-Host " 2) openclaw onboard"
- Write-Host " 3) openclaw gateway"
- Write-Host " 4) openclaw status"
- Write-Host ""
- Info ("{0} $RemoteBaseUrl" -f (T "Remote server:" "远程服务器:"))
-}
-Write-Host ""
diff --git a/examples/openclaw-plugin/install.sh b/examples/openclaw-plugin/install.sh
index 425d7686a..678cf901c 100755
--- a/examples/openclaw-plugin/install.sh
+++ b/examples/openclaw-plugin/install.sh
@@ -3,9 +3,22 @@
# OpenClaw + OpenViking one-click installer
# Usage: curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/install.sh | bash
#
+# Options:
+# --repo <owner/repo> - GitHub repository (default: volcengine/OpenViking)
+# --plugin-version <tag> - Plugin version (Git tag, e.g. v0.2.9, default: main)
+# --openviking-version <ver> - OpenViking PyPI version (e.g. 0.2.9, default: latest)
+# --workdir <path> - OpenClaw config directory (default: ~/.openclaw)
+# --update / --upgrade-plugin - Upgrade only the plugin using native script logic
+# --rollback - Roll back the last plugin upgrade
+# -y, --yes - Non-interactive mode
+# --zh - Chinese prompts
+# -h, --help - Show help
+#
# Environment variables:
-# REPO=owner/repo - GitHub repository (default: volcengine/OpenViking)
-# BRANCH=branch - Git branch/tag/commit (default: main)
+# REPO=owner/repo - GitHub repository (same as --repo)
+# BRANCH=branch - Git branch/tag/commit (legacy, use --plugin-version instead)
+# PLUGIN_VERSION=tag - Plugin version (same as --plugin-version)
+# OPENVIKING_VERSION=ver - OpenViking PyPI version (same as --openviking-version)
# OPENVIKING_INSTALL_YES=1 - non-interactive mode (same as -y)
# SKIP_OPENCLAW=1 - skip OpenClaw check
# SKIP_OPENVIKING=1 - skip OpenViking installation
@@ -13,64 +26,157 @@
# PIP_INDEX_URL=url - pip index URL (default: https://pypi.tuna.tsinghua.edu.cn/simple)
# OPENVIKING_VLM_API_KEY - VLM model API key (optional)
# OPENVIKING_EMBEDDING_API_KEY - Embedding model API key (optional)
-# OPENVIKING_ARK_API_KEY - legacy fallback for both keys
-# OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1 - if venv unavailable (PEP 668 only), allow pip --break-system-packages (opt-in, default off)
-# GET_PIP_URL=url - URL for get-pip.py when using venv --without-pip (default: auto)
+# OPENVIKING_ARK_API_KEY - legacy fallback for both keys
+# OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1 - if venv unavailable (PEP 668 only), allow pip --break-system-packages
+# GET_PIP_URL=url - URL for get-pip.py when using venv --without-pip (default: auto)
#
# On Debian/Ubuntu (PEP 668), the script installs OpenViking into a venv at
# ~/.openviking/venv to avoid "externally-managed-environment" errors.
#
+# If curl | bash from a branch URL looks stale, pin the commit SHA in the path:
+# .../LinQiang391/OpenViking/<commit>/examples/openclaw-plugin/install.sh
+# (raw.githubusercontent.com may cache branch resolution briefly.)
+#
set -e
+set -o pipefail
# Set by install_openviking when using venv (e.g. on Debian/Ubuntu); used by write_openviking_env
OPENVIKING_PYTHON_PATH=""
REPO="${REPO:-volcengine/OpenViking}"
-BRANCH="${BRANCH:-main}"
+# BRANCH is legacy, prefer PLUGIN_VERSION
+PLUGIN_VERSION="${PLUGIN_VERSION:-${BRANCH:-main}}"
+OPENVIKING_VERSION="${OPENVIKING_VERSION:-}"
INSTALL_YES="${OPENVIKING_INSTALL_YES:-0}"
+UPGRADE_PLUGIN_ONLY="${OPENVIKING_UPGRADE_PLUGIN_ONLY:-0}"
+ROLLBACK_LAST_UPGRADE="${OPENVIKING_ROLLBACK_LAST_UPGRADE:-0}"
SKIP_OC="${SKIP_OPENCLAW:-0}"
SKIP_OV="${SKIP_OPENVIKING:-0}"
NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmmirror.com}"
-PIP_INDEX_URL="${PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}"
+PIP_INDEX_URL="${PIP_INDEX_URL:-https://mirrors.volces.com/pypi/simple/}"
HOME_DIR="${HOME:-$USERPROFILE}"
-OPENCLAW_DIR="${HOME_DIR}/.openclaw"
+DEFAULT_OPENCLAW_DIR="${HOME_DIR}/.openclaw"
+OPENCLAW_DIR="${DEFAULT_OPENCLAW_DIR}"
OPENVIKING_DIR="${HOME_DIR}/.openviking"
-PLUGIN_DEST="${OPENCLAW_DIR}/extensions/openviking"
+PLUGIN_DEST="" # Will be set after resolving plugin config
DEFAULT_SERVER_PORT=1933
DEFAULT_AGFS_PORT=1833
DEFAULT_VLM_MODEL="doubao-seed-2-0-pro-260215"
DEFAULT_EMBED_MODEL="doubao-embedding-vision-251215"
SELECTED_SERVER_PORT="${DEFAULT_SERVER_PORT}"
+SELECTED_CONFIG_PATH=""
SELECTED_MODE="local"
LANG_UI="en"
+# Plugin config (set by resolve_plugin_config)
+RESOLVED_PLUGIN_DIR=""
+RESOLVED_PLUGIN_ID=""
+RESOLVED_PLUGIN_KIND=""
+RESOLVED_PLUGIN_SLOT=""
+RESOLVED_FILES_REQUIRED=()
+RESOLVED_FILES_OPTIONAL=()
+RESOLVED_NPM_OMIT_DEV="true"
+RESOLVED_MIN_OPENCLAW_VERSION=""
+RESOLVED_MIN_OPENVIKING_VERSION=""
+RESOLVED_PLUGIN_RELEASE_ID=""
+
+UPGRADE_DETECTED_GENERATION="none"
+UPGRADE_DETECTED_FROM_VERSION=""
+UPGRADE_RUNTIME_MODE="local"
+UPGRADE_RUNTIME_CONFIG_PATH=""
+UPGRADE_RUNTIME_PORT=""
+UPGRADE_RUNTIME_BASE_URL=""
+UPGRADE_RUNTIME_API_KEY=""
+UPGRADE_RUNTIME_AGENT_ID=""
+UPGRADE_CLAIM_SLOT="1"
+UPGRADE_DETECTED_IDS=()
+UPGRADE_AUDIT_OPERATION=""
+UPGRADE_AUDIT_CREATED_AT=""
+UPGRADE_AUDIT_FROM_VERSION=""
+UPGRADE_AUDIT_TO_VERSION=""
+UPGRADE_AUDIT_CONFIG_BACKUP_PATH=""
+UPGRADE_AUDIT_RUNTIME_MODE=""
+UPGRADE_AUDIT_COMPLETED_AT=""
+UPGRADE_AUDIT_ROLLED_BACK_AT=""
+UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH=""
+UPGRADE_AUDIT_PLUGIN_BACKUPS=()
+
# Parse args (supports curl | bash -s -- ...)
_expect_workdir=""
+_expect_plugin_version=""
+_expect_ov_version=""
+_expect_repo=""
for arg in "$@"; do
if [[ -n "$_expect_workdir" ]]; then
OPENCLAW_DIR="$arg"
- PLUGIN_DEST="${OPENCLAW_DIR}/extensions/openviking"
_expect_workdir=""
continue
fi
+ if [[ -n "$_expect_plugin_version" ]]; then
+ PLUGIN_VERSION="$arg"
+ _expect_plugin_version=""
+ continue
+ fi
+ if [[ -n "$_expect_ov_version" ]]; then
+ OPENVIKING_VERSION="$arg"
+ _expect_ov_version=""
+ continue
+ fi
+ if [[ -n "$_expect_repo" ]]; then
+ REPO="$arg"
+ _expect_repo=""
+ continue
+ fi
[[ "$arg" == "-y" || "$arg" == "--yes" ]] && INSTALL_YES="1"
+ [[ "$arg" == "--upgrade-plugin" || "$arg" == "--update" || "$arg" == "--upgrade" ]] && UPGRADE_PLUGIN_ONLY="1"
+ [[ "$arg" == "--rollback" || "$arg" == "--rollback-last-upgrade" ]] && ROLLBACK_LAST_UPGRADE="1"
[[ "$arg" == "--zh" ]] && LANG_UI="zh"
[[ "$arg" == "--workdir" ]] && { _expect_workdir="1"; continue; }
+ [[ "$arg" == "--plugin-version" ]] && { _expect_plugin_version="1"; continue; }
+ [[ "$arg" == "--openviking-version" ]] && { _expect_ov_version="1"; continue; }
+ [[ "$arg" == "--repo" ]] && { _expect_repo="1"; continue; }
[[ "$arg" == "-h" || "$arg" == "--help" ]] && {
- echo "Usage: curl -fsSL <INSTALL_URL> | bash [-s -- -y --zh --workdir <path>]"
+ echo "Usage: curl -fsSL <INSTALL_URL> | bash [-s -- OPTIONS]"
echo ""
echo "Options:"
- echo " -y, --yes Non-interactive mode"
- echo " --zh Chinese prompts"
- echo " --workdir <path> OpenClaw config directory (default: ~/.openclaw)"
- echo " -h, --help Show this help"
+ echo " --repo <owner/repo> GitHub repository (default: volcengine/OpenViking)"
+ echo " --plugin-version <tag> Plugin version (Git tag, e.g. v0.2.9, default: main)"
+ echo " --openviking-version <v> OpenViking PyPI version (e.g. 0.2.9, default: latest)"
+ echo " --workdir <path> OpenClaw config directory (default: ~/.openclaw)"
+ echo " --update, --upgrade-plugin"
+ echo " Upgrade only the plugin to the requested --plugin-version; do not change the OpenViking service"
+ echo " --rollback Roll back the last plugin upgrade"
+ echo " -y, --yes Non-interactive mode"
+ echo " --zh Chinese prompts"
+ echo " -h, --help Show this help"
+ echo ""
+ echo "Examples:"
+ echo " # Install latest version"
+ echo " curl -fsSL <URL> | bash"
+ echo ""
+ echo " # Install from a fork repository"
+ echo " curl -fsSL <URL> | bash -s -- --repo yourname/OpenViking --plugin-version dev-branch"
echo ""
- echo "Env vars: REPO, BRANCH, OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING, NPM_REGISTRY, PIP_INDEX_URL"
+ echo " # Install specific plugin version"
+ echo " curl -fsSL <URL> | bash -s -- --plugin-version v0.2.8"
+ echo ""
+ echo " # Upgrade only the plugin files"
+ echo " curl -fsSL <URL> | bash -s -- --update --plugin-version main"
+ echo ""
+ echo " # Roll back the last plugin upgrade"
+ echo " curl -fsSL <URL> | bash -s -- --rollback"
+ echo ""
+ echo "Env vars: REPO, PLUGIN_VERSION, OPENVIKING_VERSION, SKIP_OPENCLAW, SKIP_OPENVIKING, NPM_REGISTRY, PIP_INDEX_URL"
exit 0
}
done
+if [[ "$UPGRADE_PLUGIN_ONLY" == "1" && "$ROLLBACK_LAST_UPGRADE" == "1" ]]; then
+ echo "[ERROR] --update/--upgrade-plugin and --rollback cannot be used together"
+ exit 1
+fi
+
tr() {
local en="$1"
local zh="$2"
@@ -81,18 +187,695 @@ tr() {
fi
}
+legacy_plugin_install_hint() {
+ local args=(--plugin-version "<legacy-version>")
+ [[ "$OPENCLAW_DIR" != "$DEFAULT_OPENCLAW_DIR" ]] && args+=(--workdir "$OPENCLAW_DIR")
+ [[ "$REPO" != "volcengine/OpenViking" ]] && args+=(--repo "$REPO")
+ [[ "$LANG_UI" == "zh" ]] && args+=(--zh)
+
+ if [[ -n "${OPENVIKING_INSTALL_LEGACY_HINT:-}" ]]; then
+ printf "%s\n" "${OPENVIKING_INSTALL_LEGACY_HINT}"
+ return 0
+ fi
+
+ if [[ -n "${BASH_SOURCE[0]:-}" ]]; then
+ local script_path=""
+ script_path="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
+ printf "bash %q" "${script_path}"
+ local arg
+ for arg in "${args[@]}"; do
+ printf " %q" "${arg}"
+ done
+ printf "\n"
+ return 0
+ fi
+
+ printf "ov-install"
+ local arg
+ for arg in "${args[@]}"; do
+ printf " %q" "${arg}"
+ done
+ printf "\n"
+}
+
+shell_single_quote() {
+ printf "%s" "$1" | sed "s/'/'\"'\"'/g"
+}
+
+iso_now() {
+ node -e "process.stdout.write(new Date().toISOString())"
+}
+
+decode_base64_with_node() {
+ local value="${1:-}"
+ node -e "process.stdout.write(Buffer.from(process.argv[1] || '', 'base64').toString('utf8'))" "${value}"
+}
+
+run_openclaw_cmd() {
+ if [[ "$OPENCLAW_DIR" != "$DEFAULT_OPENCLAW_DIR" ]]; then
+ OPENCLAW_STATE_DIR="$OPENCLAW_DIR" "$@"
+ else
+ "$@"
+ fi
+}
+
+get_openclaw_config_path() {
+ printf "%s\n" "${OPENCLAW_DIR}/openclaw.json"
+}
+
+get_install_state_path_for_plugin() {
+ printf "%s\n" "${OPENCLAW_DIR}/extensions/$1/.ov-install-state.json"
+}
+
+get_upgrade_audit_dir() {
+ printf "%s\n" "${OPENCLAW_DIR}/.openviking-upgrade-backup"
+}
+
+get_upgrade_audit_path() {
+ printf "%s\n" "$(get_upgrade_audit_dir)/last-upgrade.json"
+}
+
+get_openclaw_config_backup_path() {
+ printf "%s\n" "$(get_upgrade_audit_dir)/openclaw.json.bak"
+}
+
+variant_meta_by_id() {
+ case "$1" in
+ memory-openviking) printf "%s\n" "memory-openviking|openclaw-memory-plugin|memory|legacy|none" ;;
+ openviking) printf "%s\n" "openviking|openclaw-plugin|contextEngine|current|legacy" ;;
+ *) return 1 ;;
+ esac
+}
+
+format_target_version_label() {
+ local base="${RESOLVED_PLUGIN_ID:-openviking}@${PLUGIN_VERSION}"
+ if [[ -n "${RESOLVED_PLUGIN_RELEASE_ID}" && "${RESOLVED_PLUGIN_RELEASE_ID}" != "${PLUGIN_VERSION}" ]]; then
+ printf "%s\n" "${base} (${RESOLVED_PLUGIN_RELEASE_ID})"
+ return 0
+ fi
+ printf "%s\n" "${base}"
+}
+
+validate_requested_plugin_version() {
+ if [[ "${PLUGIN_VERSION}" == "v0.2.7" ]]; then
+ err "Plugin version v0.2.7 does not exist. Please choose another release or branch."
+ exit 1
+ fi
+}
+
+ensure_plugin_only_operation_args() {
+ if [[ ("${UPGRADE_PLUGIN_ONLY}" == "1" || "${ROLLBACK_LAST_UPGRADE}" == "1") && -n "${OPENVIKING_VERSION}" ]]; then
+ err "--update/--upgrade-plugin and --rollback only operate on the plugin. Do not use --openviking-version with these modes."
+ exit 1
+ fi
+}
+
+backup_openclaw_config() {
+ local config_path="$1"
+ local backup_dir
+ local backup_path
+ backup_dir="$(get_upgrade_audit_dir)"
+ backup_path="$(get_openclaw_config_backup_path)"
+ mkdir -p "${backup_dir}"
+ cp "${config_path}" "${backup_path}"
+ printf "%s\n" "${backup_path}"
+}
+
+write_upgrade_audit_file() {
+ local audit_path
+ audit_path="$(get_upgrade_audit_path)"
+ mkdir -p "$(get_upgrade_audit_dir)"
+ node - "${audit_path}" \
+ "${UPGRADE_AUDIT_OPERATION}" \
+ "${UPGRADE_AUDIT_CREATED_AT}" \
+ "${UPGRADE_AUDIT_FROM_VERSION}" \
+ "${UPGRADE_AUDIT_TO_VERSION}" \
+ "${UPGRADE_AUDIT_CONFIG_BACKUP_PATH}" \
+ "${UPGRADE_AUDIT_RUNTIME_MODE}" \
+ "${UPGRADE_AUDIT_COMPLETED_AT}" \
+ "${UPGRADE_AUDIT_ROLLED_BACK_AT}" \
+ "${UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH}" \
+ "${UPGRADE_AUDIT_PLUGIN_BACKUPS[@]}" <<'NODE'
+const fs = require("fs");
+const path = require("path");
+
+const [
+ auditPath,
+ operation,
+ createdAt,
+ fromVersion,
+ toVersion,
+ configBackupPath,
+ runtimeMode,
+ completedAt,
+ rolledBackAt,
+ rollbackConfigPath,
+ ...backupArgs
+] = process.argv.slice(2);
+
+const pluginBackups = backupArgs
+ .filter(Boolean)
+ .map((item) => {
+ const [pluginId, ...rest] = item.split("|");
+ return { pluginId, backupDir: rest.join("|") };
+ })
+ .filter((item) => item.pluginId && item.backupDir);
+
+const data = {
+ operation,
+ createdAt,
+ fromVersion,
+ toVersion,
+ configBackupPath,
+ pluginBackups,
+ runtimeMode,
+};
+
+if (completedAt) data.completedAt = completedAt;
+if (rolledBackAt) data.rolledBackAt = rolledBackAt;
+if (rollbackConfigPath) data.rollbackConfigPath = rollbackConfigPath;
+
+fs.mkdirSync(path.dirname(auditPath), { recursive: true });
+fs.writeFileSync(auditPath, `${JSON.stringify(data, null, 2)}\n`);
+NODE
+}
+
+load_upgrade_audit_file() {
+ local audit_path
+ audit_path="$(get_upgrade_audit_path)"
+ [[ -f "${audit_path}" ]] || return 1
+
+ UPGRADE_AUDIT_OPERATION=""
+ UPGRADE_AUDIT_CREATED_AT=""
+ UPGRADE_AUDIT_FROM_VERSION=""
+ UPGRADE_AUDIT_TO_VERSION=""
+ UPGRADE_AUDIT_CONFIG_BACKUP_PATH=""
+ UPGRADE_AUDIT_RUNTIME_MODE=""
+ UPGRADE_AUDIT_COMPLETED_AT=""
+ UPGRADE_AUDIT_ROLLED_BACK_AT=""
+ UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH=""
+ UPGRADE_AUDIT_PLUGIN_BACKUPS=()
+
+ local line key value
+ while IFS= read -r line; do
+ key="${line%%=*}"
+ value="${line#*=}"
+ case "${key}" in
+ operation) UPGRADE_AUDIT_OPERATION="$(decode_base64_with_node "${value}")" ;;
+ createdAt) UPGRADE_AUDIT_CREATED_AT="$(decode_base64_with_node "${value}")" ;;
+ fromVersion) UPGRADE_AUDIT_FROM_VERSION="$(decode_base64_with_node "${value}")" ;;
+ toVersion) UPGRADE_AUDIT_TO_VERSION="$(decode_base64_with_node "${value}")" ;;
+ configBackupPath) UPGRADE_AUDIT_CONFIG_BACKUP_PATH="$(decode_base64_with_node "${value}")" ;;
+ runtimeMode) UPGRADE_AUDIT_RUNTIME_MODE="$(decode_base64_with_node "${value}")" ;;
+ completedAt) UPGRADE_AUDIT_COMPLETED_AT="$(decode_base64_with_node "${value}")" ;;
+ rolledBackAt) UPGRADE_AUDIT_ROLLED_BACK_AT="$(decode_base64_with_node "${value}")" ;;
+ rollbackConfigPath) UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH="$(decode_base64_with_node "${value}")" ;;
+ pluginBackup) UPGRADE_AUDIT_PLUGIN_BACKUPS+=("$(decode_base64_with_node "${value}")") ;;
+ esac
+ done < <(node - "${audit_path}" <<'NODE'
+const fs = require("fs");
+
+const auditPath = process.argv[2];
+const data = JSON.parse(fs.readFileSync(auditPath, "utf8"));
+const enc = (value) => Buffer.from(String(value ?? ""), "utf8").toString("base64");
+
+console.log(`operation=${enc(data.operation || "")}`);
+console.log(`createdAt=${enc(data.createdAt || "")}`);
+console.log(`fromVersion=${enc(data.fromVersion || "")}`);
+console.log(`toVersion=${enc(data.toVersion || "")}`);
+console.log(`configBackupPath=${enc(data.configBackupPath || "")}`);
+console.log(`runtimeMode=${enc(data.runtimeMode || "")}`);
+console.log(`completedAt=${enc(data.completedAt || "")}`);
+console.log(`rolledBackAt=${enc(data.rolledBackAt || "")}`);
+console.log(`rollbackConfigPath=${enc(data.rollbackConfigPath || "")}`);
+for (const backup of Array.isArray(data.pluginBackups) ? data.pluginBackups : []) {
+ const item = `${backup.pluginId || ""}|${backup.backupDir || ""}`;
+ console.log(`pluginBackup=${enc(item)}`);
+}
+NODE
+)
+}
+
+write_install_state_file() {
+ local operation="$1"
+ local from_version="$2"
+ local install_state_path
+ install_state_path="$(get_install_state_path_for_plugin "${RESOLVED_PLUGIN_ID:-openviking}")"
+ mkdir -p "$(dirname "${install_state_path}")"
+ node - "${install_state_path}" \
+ "${RESOLVED_PLUGIN_ID:-openviking}" \
+ "${PLUGIN_VERSION}" \
+ "${RESOLVED_PLUGIN_RELEASE_ID}" \
+ "${REPO}" \
+ "${operation}" \
+ "${from_version}" \
+ "${UPGRADE_AUDIT_CONFIG_BACKUP_PATH}" \
+ "${UPGRADE_AUDIT_PLUGIN_BACKUPS[@]}" <<'NODE'
+const fs = require("fs");
+const path = require("path");
+
+const [installStatePath, pluginId, requestedRef, releaseId, repo, operation, fromVersion, configBackupPath, ...backupArgs] = process.argv.slice(2);
+const generation = pluginId === "memory-openviking" ? "legacy" : pluginId === "openviking" ? "current" : "unknown";
+const pluginBackups = backupArgs
+ .filter(Boolean)
+ .map((item) => {
+ const [backupPluginId, ...rest] = item.split("|");
+ return { pluginId: backupPluginId, backupDir: rest.join("|") };
+ })
+ .filter((item) => item.pluginId && item.backupDir);
+
+const state = {
+ pluginId,
+ generation,
+ requestedRef,
+ releaseId,
+ operation,
+ fromVersion,
+ configBackupPath,
+ pluginBackups,
+ installedAt: new Date().toISOString(),
+ repo,
+};
+
+fs.mkdirSync(path.dirname(installStatePath), { recursive: true });
+fs.writeFileSync(installStatePath, `${JSON.stringify(state, null, 2)}\n`);
+NODE
+}
+
+stop_openclaw_gateway_for_upgrade() {
+ if run_openclaw_cmd openclaw gateway stop >/dev/null 2>&1; then
+ info "Stopped OpenClaw gateway before plugin upgrade"
+ else
+ warn "OpenClaw gateway may not be running; continuing"
+ fi
+}
+
+prune_previous_upgrade_backups() {
+ local plugin_id="$1"
+ local keep_dir="$2"
+ local disabled_dir="${OPENCLAW_DIR}/disabled-extensions"
+ local keep_name=""
+ [[ -n "${keep_dir}" ]] && keep_name="$(basename "${keep_dir}")"
+ [[ -d "${disabled_dir}" ]] || return 0
+
+ local entry
+ shopt -s nullglob
+ for entry in "${disabled_dir}/${plugin_id}-upgrade-backup-"*; do
+ [[ -d "${entry}" ]] || continue
+ [[ -n "${keep_name}" && "$(basename "${entry}")" == "${keep_name}" ]] && continue
+ rm -rf "${entry}"
+ done
+ shopt -u nullglob
+}
+
+backup_plugin_directory() {
+ local plugin_id="$1"
+ local plugin_dir="${OPENCLAW_DIR}/extensions/${plugin_id}"
+ [[ -d "${plugin_dir}" ]] || return 0
+
+ local disabled_dir="${OPENCLAW_DIR}/disabled-extensions"
+ local timestamp
+ local backup_dir
+ timestamp="$(node -e "process.stdout.write(String(Date.now()))")"
+ backup_dir="${disabled_dir}/${plugin_id}-upgrade-backup-${timestamp}"
+ mkdir -p "${disabled_dir}"
+ if ! mv "${plugin_dir}" "${backup_dir}" 2>/dev/null; then
+ cp -R "${plugin_dir}" "${backup_dir}"
+ rm -rf "${plugin_dir}"
+ fi
+ info "$(tr "Backed up plugin directory: ${backup_dir}" "已备份插件目录: ${backup_dir}")" >&2
+ prune_previous_upgrade_backups "${plugin_id}" "${backup_dir}"
+ printf "%s\n" "${backup_dir}"
+}
+
+detect_installed_plugin_state() {
+ local config_path
+ config_path="$(get_openclaw_config_path)"
+
+ UPGRADE_DETECTED_GENERATION="none"
+ UPGRADE_DETECTED_FROM_VERSION=""
+ UPGRADE_RUNTIME_MODE="local"
+ UPGRADE_RUNTIME_CONFIG_PATH=""
+ UPGRADE_RUNTIME_PORT=""
+ UPGRADE_RUNTIME_BASE_URL=""
+ UPGRADE_RUNTIME_API_KEY=""
+ UPGRADE_RUNTIME_AGENT_ID=""
+ UPGRADE_CLAIM_SLOT="1"
+ UPGRADE_DETECTED_IDS=()
+
+ local line key value
+ while IFS= read -r line; do
+ key="${line%%=*}"
+ value="${line#*=}"
+ case "${key}" in
+ generation) UPGRADE_DETECTED_GENERATION="${value}" ;;
+ fromVersion) UPGRADE_DETECTED_FROM_VERSION="$(decode_base64_with_node "${value}")" ;;
+ claimSlot) UPGRADE_CLAIM_SLOT="${value}" ;;
+ mode) UPGRADE_RUNTIME_MODE="${value}" ;;
+ configPath) UPGRADE_RUNTIME_CONFIG_PATH="$(decode_base64_with_node "${value}")" ;;
+ port) UPGRADE_RUNTIME_PORT="${value}" ;;
+ baseUrl) UPGRADE_RUNTIME_BASE_URL="$(decode_base64_with_node "${value}")" ;;
+ apiKey) UPGRADE_RUNTIME_API_KEY="$(decode_base64_with_node "${value}")" ;;
+ agentId) UPGRADE_RUNTIME_AGENT_ID="$(decode_base64_with_node "${value}")" ;;
+ detectionId) UPGRADE_DETECTED_IDS+=("${value}") ;;
+ esac
+ done < <(node - "${config_path}" "${OPENCLAW_DIR}" "${RESOLVED_PLUGIN_ID}" "${RESOLVED_PLUGIN_SLOT}" "${OPENVIKING_DIR}" "${DEFAULT_SERVER_PORT}" <<'NODE'
+const fs = require("fs");
+const path = require("path");
+
+const [configPath, openclawDir, resolvedPluginId, resolvedPluginSlot, openvikingDir, defaultServerPortRaw] = process.argv.slice(2);
+const defaultServerPort = Number.parseInt(defaultServerPortRaw, 10) || 1933;
+const enc = (value) => Buffer.from(String(value ?? ""), "utf8").toString("base64");
+const variants = [
+ { id: "memory-openviking", dir: "openclaw-memory-plugin", generation: "legacy", slot: "memory", slotFallback: "none" },
+ { id: "openviking", dir: "openclaw-plugin", generation: "current", slot: "contextEngine", slotFallback: "legacy" },
+];
+
+function readJson(filePath) {
+ if (!filePath || !fs.existsSync(filePath)) return null;
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
+}
+
+function getInstallStatePath(pluginId) {
+ return path.join(openclawDir, "extensions", pluginId, ".ov-install-state.json");
+}
+
+function detectPresence(config, variant) {
+ const plugins = config?.plugins;
+ const reasons = [];
+ if (plugins) {
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) reasons.push("entry");
+ if (plugins.slots?.[variant.slot] === variant.id) reasons.push("slot");
+ if (Array.isArray(plugins.allow) && plugins.allow.includes(variant.id)) reasons.push("allow");
+ if (Array.isArray(plugins.load?.paths) && plugins.load.paths.some((item) => typeof item === "string" && (item.includes(variant.id) || item.includes(variant.dir)))) {
+ reasons.push("loadPath");
+ }
+ }
+ if (fs.existsSync(path.join(openclawDir, "extensions", variant.id))) reasons.push("dir");
+ return { variant, present: reasons.length > 0, reasons };
+}
+
+function formatDetectionLabel(detection) {
+ const requestedRef = detection.installState?.requestedRef;
+ const releaseId = detection.installState?.releaseId;
+ if (requestedRef) return `${detection.variant.id}@${requestedRef}`;
+ if (releaseId) return `${detection.variant.id}#${releaseId}`;
+ return `${detection.variant.id} (${detection.variant.generation}, exact version unknown)`;
+}
+
+function extractRuntimeConfig(entryConfig) {
+ if (!entryConfig || typeof entryConfig !== "object") return null;
+ const mode = entryConfig.mode === "remote" ? "remote" : "local";
+ const runtime = { mode };
+ if (mode === "remote") {
+ if (typeof entryConfig.baseUrl === "string" && entryConfig.baseUrl.trim()) runtime.baseUrl = entryConfig.baseUrl.trim();
+ if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) runtime.apiKey = entryConfig.apiKey;
+ if (typeof entryConfig.agentId === "string" && entryConfig.agentId.trim()) runtime.agentId = entryConfig.agentId.trim();
+ return runtime;
+ }
+ if (typeof entryConfig.configPath === "string" && entryConfig.configPath.trim()) runtime.configPath = entryConfig.configPath.trim();
+ if (entryConfig.port !== undefined && entryConfig.port !== null && `${entryConfig.port}`.trim()) {
+ const port = Number.parseInt(String(entryConfig.port), 10);
+ if (Number.isFinite(port) && port > 0) runtime.port = port;
+ }
+ return runtime;
+}
+
+function readPortFromOvConf(filePath) {
+ const targetPath = filePath || path.join(openvikingDir, "ov.conf");
+ if (!fs.existsSync(targetPath)) return null;
+ try {
+ const data = JSON.parse(fs.readFileSync(targetPath, "utf8"));
+ const port = Number.parseInt(String(data?.server?.port ?? ""), 10);
+ return Number.isFinite(port) && port > 0 ? port : null;
+ } catch {
+ return null;
+ }
+}
+
+function shouldClaimTargetSlot(config, detections) {
+ const currentOwner = config?.plugins?.slots?.[resolvedPluginSlot];
+ if (!currentOwner || currentOwner === "none" || currentOwner === "legacy" || currentOwner === resolvedPluginId) return true;
+ return detections.some((item) => item.variant.id === currentOwner);
+}
+
+const config = readJson(configPath);
+const detections = variants
+ .map((variant) => {
+ const detection = detectPresence(config, variant);
+ if (!detection.present) return null;
+ detection.installState = readJson(getInstallStatePath(variant.id));
+ return detection;
+ })
+ .filter(Boolean);
+
+let generation = "none";
+if (detections.length === 1) generation = detections[0].variant.generation;
+if (detections.length > 1) generation = "mixed";
+
+let runtime = null;
+const candidateOrder = [...detections].sort((left, right) => (right.variant.generation === "current" ? 1 : 0) - (left.variant.generation === "current" ? 1 : 0));
+for (const detection of candidateOrder) {
+ const entryConfig = extractRuntimeConfig(config?.plugins?.entries?.[detection.variant.id]?.config);
+ if (entryConfig) {
+ runtime = entryConfig;
+ break;
+ }
+}
+
+if (!runtime) runtime = { mode: "local" };
+if (runtime.mode === "remote") {
+ runtime.baseUrl = runtime.baseUrl || "http://127.0.0.1:1933";
+} else {
+ runtime.configPath = runtime.configPath || path.join(openvikingDir, "ov.conf");
+ runtime.port = runtime.port || readPortFromOvConf(runtime.configPath) || defaultServerPort;
+}
+
+const fromVersion = detections.length
+ ? detections.map(formatDetectionLabel).join(" + ")
+ : "not-installed";
+
+console.log(`generation=${generation}`);
+console.log(`fromVersion=${enc(fromVersion)}`);
+console.log(`claimSlot=${shouldClaimTargetSlot(config, detections) ? "1" : "0"}`);
+console.log(`mode=${runtime.mode === "remote" ? "remote" : "local"}`);
+console.log(`configPath=${enc(runtime.configPath || "")}`);
+console.log(`port=${runtime.port || ""}`);
+console.log(`baseUrl=${enc(runtime.baseUrl || "")}`);
+console.log(`apiKey=${enc(runtime.apiKey || "")}`);
+console.log(`agentId=${enc(runtime.agentId || "")}`);
+for (const detection of detections) {
+ console.log(`detectionId=${detection.variant.id}`);
+}
+NODE
+)
+}
+
+cleanup_installed_plugin_config() {
+ local config_path
+ config_path="$(get_openclaw_config_path)"
+ [[ -f "${config_path}" ]] || return 0
+ [[ ${#UPGRADE_DETECTED_IDS[@]} -gt 0 ]] || return 0
+
+ local status
+ status="$(node - "${config_path}" "${UPGRADE_DETECTED_IDS[@]}" <<'NODE'
+const fs = require("fs");
+
+const [configPath, ...pluginIds] = process.argv.slice(2);
+const variantMap = {
+ "memory-openviking": { id: "memory-openviking", dir: "openclaw-memory-plugin", slot: "memory", slotFallback: "none" },
+ "openviking": { id: "openviking", dir: "openclaw-plugin", slot: "contextEngine", slotFallback: "legacy" },
+};
+
+const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
+const plugins = config?.plugins;
+if (!plugins) {
+ console.log("no-plugins");
+ process.exit(0);
+}
+
+let changed = false;
+for (const pluginId of pluginIds) {
+ const variant = variantMap[pluginId];
+ if (!variant) continue;
+ if (Array.isArray(plugins.allow)) {
+ const nextAllow = plugins.allow.filter((item) => item !== variant.id);
+ changed = changed || nextAllow.length !== plugins.allow.length;
+ plugins.allow = nextAllow;
+ }
+ if (Array.isArray(plugins.load?.paths)) {
+ const nextPaths = plugins.load.paths.filter((item) => typeof item !== "string" || (!item.includes(variant.id) && !item.includes(variant.dir)));
+ changed = changed || nextPaths.length !== plugins.load.paths.length;
+ plugins.load.paths = nextPaths;
+ }
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) {
+ delete plugins.entries[variant.id];
+ changed = true;
+ }
+ if (plugins.slots?.[variant.slot] === variant.id) {
+ plugins.slots[variant.slot] = variant.slotFallback;
+ changed = true;
+ }
+}
+
+if (changed) {
+ fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
+ console.log("changed");
+} else {
+ console.log("unchanged");
+}
+NODE
+)"
+
+ case "${status}" in
+ changed)
+ info "Cleaned existing OpenViking plugin config only"
+ ;;
+ no-plugins)
+ warn "openclaw.json has no plugins section; skipped targeted plugin cleanup"
+ ;;
+ *)
+ info "No OpenViking plugin config changes were required"
+ ;;
+ esac
+}
+
+prepare_strong_plugin_upgrade() {
+ detect_installed_plugin_state
+ if [[ "${UPGRADE_DETECTED_GENERATION}" == "none" ]]; then
+ err "Plugin upgrade mode requires an existing OpenViking plugin entry in openclaw.json."
+ exit 1
+ fi
+
+ SELECTED_MODE="${UPGRADE_RUNTIME_MODE:-local}"
+ if [[ "${SELECTED_MODE}" == "remote" ]]; then
+ remote_base_url="${UPGRADE_RUNTIME_BASE_URL:-http://127.0.0.1:1933}"
+ remote_api_key="${UPGRADE_RUNTIME_API_KEY:-}"
+ remote_agent_id="${UPGRADE_RUNTIME_AGENT_ID:-}"
+ else
+ SELECTED_CONFIG_PATH="${UPGRADE_RUNTIME_CONFIG_PATH:-${OPENVIKING_DIR}/ov.conf}"
+ SELECTED_SERVER_PORT="${UPGRADE_RUNTIME_PORT:-${DEFAULT_SERVER_PORT}}"
+ fi
+
+ local to_version
+ to_version="$(format_target_version_label)"
+ info "$(tr "Detected installed OpenViking plugin state: ${UPGRADE_DETECTED_GENERATION}" "检测到已安装的 OpenViking 插件状态: ${UPGRADE_DETECTED_GENERATION}")"
+ info "$(tr "Upgrade runtime mode: ${SELECTED_MODE}" "升级运行模式: ${SELECTED_MODE}")"
+ info "$(tr "Upgrade path: ${UPGRADE_DETECTED_FROM_VERSION} -> ${to_version}" "升级路径: ${UPGRADE_DETECTED_FROM_VERSION} -> ${to_version}")"
+
+ stop_openclaw_gateway_for_upgrade
+
+ local config_path
+ config_path="$(get_openclaw_config_path)"
+ if [[ ! -f "${config_path}" ]]; then
+ err "Plugin upgrade mode requires ${config_path} to exist."
+ exit 1
+ fi
+
+ UPGRADE_AUDIT_PLUGIN_BACKUPS=()
+ UPGRADE_AUDIT_OPERATION="upgrade"
+ UPGRADE_AUDIT_CREATED_AT="$(iso_now)"
+ UPGRADE_AUDIT_FROM_VERSION="${UPGRADE_DETECTED_FROM_VERSION}"
+ UPGRADE_AUDIT_TO_VERSION="${to_version}"
+ UPGRADE_AUDIT_CONFIG_BACKUP_PATH="$(backup_openclaw_config "${config_path}")"
+ UPGRADE_AUDIT_RUNTIME_MODE="${SELECTED_MODE}"
+ UPGRADE_AUDIT_COMPLETED_AT=""
+ UPGRADE_AUDIT_ROLLED_BACK_AT=""
+ UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH=""
+
+ info "$(tr "Backed up openclaw.json: ${UPGRADE_AUDIT_CONFIG_BACKUP_PATH}" "已备份 openclaw.json: ${UPGRADE_AUDIT_CONFIG_BACKUP_PATH}")"
+
+ local detected_id backup_dir
+ for detected_id in "${UPGRADE_DETECTED_IDS[@]}"; do
+ backup_dir="$(backup_plugin_directory "${detected_id}")"
+ if [[ -n "${backup_dir}" ]]; then
+ UPGRADE_AUDIT_PLUGIN_BACKUPS+=("${detected_id}|${backup_dir}")
+ fi
+ done
+
+ write_upgrade_audit_file
+ cleanup_installed_plugin_config
+ info "Upgrade will keep the existing OpenViking runtime file and re-apply only the minimum plugin runtime settings."
+ info "Upgrade audit file: $(get_upgrade_audit_path)"
+}
+
+rollback_last_upgrade_operation() {
+ local audit_path
+ audit_path="$(get_upgrade_audit_path)"
+ if ! load_upgrade_audit_file; then
+ err "No rollback audit file found at ${audit_path}."
+ exit 1
+ fi
+
+ if [[ -n "${UPGRADE_AUDIT_ROLLED_BACK_AT}" ]]; then
+ warn "The last recorded upgrade was already rolled back at ${UPGRADE_AUDIT_ROLLED_BACK_AT}."
+ fi
+
+ local config_backup_path="${UPGRADE_AUDIT_CONFIG_BACKUP_PATH:-$(get_openclaw_config_backup_path)}"
+ if [[ ! -f "${config_backup_path}" ]]; then
+ err "Rollback config backup is missing: ${config_backup_path}"
+ exit 1
+ fi
+
+ if [[ ${#UPGRADE_AUDIT_PLUGIN_BACKUPS[@]} -eq 0 ]]; then
+ err "Rollback audit file contains no plugin backups."
+ exit 1
+ fi
+
+ local backup_item plugin_id backup_dir
+ for backup_item in "${UPGRADE_AUDIT_PLUGIN_BACKUPS[@]}"; do
+ plugin_id="${backup_item%%|*}"
+ backup_dir="${backup_item#*|}"
+ if [[ -z "${plugin_id}" || -z "${backup_dir}" || ! -d "${backup_dir}" ]]; then
+ err "Rollback plugin backup is missing: ${backup_dir:-<unknown>}"
+ exit 1
+ fi
+ done
+
+ info "Rolling back last upgrade: ${UPGRADE_AUDIT_FROM_VERSION:-unknown} <- ${UPGRADE_AUDIT_TO_VERSION:-unknown}"
+ stop_openclaw_gateway_for_upgrade
+
+ cp "${config_backup_path}" "$(get_openclaw_config_path)"
+ info "Restored openclaw.json from backup: ${config_backup_path}"
+
+ local extensions_dir="${OPENCLAW_DIR}/extensions"
+ mkdir -p "${extensions_dir}"
+ rm -rf "${extensions_dir}/memory-openviking" "${extensions_dir}/openviking"
+
+ for backup_item in "${UPGRADE_AUDIT_PLUGIN_BACKUPS[@]}"; do
+ plugin_id="${backup_item%%|*}"
+ backup_dir="${backup_item#*|}"
+ local dest_dir="${extensions_dir}/${plugin_id}"
+ if ! mv "${backup_dir}" "${dest_dir}" 2>/dev/null; then
+ cp -R "${backup_dir}" "${dest_dir}"
+ rm -rf "${backup_dir}"
+ fi
+ info "Restored plugin directory: ${dest_dir}"
+ done
+
+ UPGRADE_AUDIT_ROLLED_BACK_AT="$(iso_now)"
+ UPGRADE_AUDIT_ROLLBACK_CONFIG_PATH="${config_backup_path}"
+ write_upgrade_audit_file
+
+ echo ""
+ bold "Rollback complete!"
+ echo ""
+ info "Rollback audit file: ${audit_path}"
+ info "Run \`openclaw gateway\` and \`openclaw status\` to verify the restored plugin state."
+}
+
# Prefer interactive mode. Even with curl | bash, try reading from /dev/tty.
# Fall back to defaults only when no interactive TTY is available.
if [[ ! -t 0 && "$INSTALL_YES" != "1" ]]; then
if [[ ! -r /dev/tty ]]; then
INSTALL_YES="1"
- echo "[WARN] $(tr "No interactive TTY detected. Falling back to defaults (-y)." "未检测到可交互终端,自动切换为默认配置模式(等同于 -y)")"
+ echo "[WARN] No interactive TTY detected. Falling back to defaults (-y)."
else
- echo "[INFO] $(tr "Pipeline execution detected. Interactive prompts will use /dev/tty." "检测到管道执行,将通过 /dev/tty 进入交互配置")"
+ echo "[INFO] Pipeline execution detected. Interactive prompts will use /dev/tty."
fi
fi
-# 颜色与输出
+# Colors and terminal attributes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
@@ -113,7 +896,7 @@ detect_os() {
*) OS="unknown";;
esac
if [[ "$OS" == "windows" ]]; then
- err "$(tr "Windows is not supported by this installer yet. Please follow the docs for manual setup." "Windows 暂不支持此一键安装脚本,请参考文档手动安装。")"
+ err "Windows is not supported by this installer yet. Please follow the docs for manual setup."
exit 1
fi
}
@@ -135,7 +918,7 @@ detect_distro() {
fi
}
-# ─── Workdir detection & mode selection ───
+# ---- Workdir detection & mode selection ----
detect_openclaw_instances() {
local instances=()
@@ -154,28 +937,28 @@ select_workdir() {
local instances=($(detect_openclaw_instances))
- # Only default instance or none — keep default
+ # Only default instance or none 鈥?keep default
if [[ ${#instances[@]} -le 1 ]]; then
return 0
fi
- # Multiple instances found — let user pick
+ # Multiple instances found 鈥?let user pick
if [[ "$INSTALL_YES" != "1" ]]; then
echo ""
- bold "$(tr "Found multiple OpenClaw instances:" "发现多个 OpenClaw 实例:")"
+ bold "Found multiple OpenClaw instances:"
local i=1
for inst in "${instances[@]}"; do
echo " ${i}) ${inst}"
i=$((i + 1))
done
echo ""
- read -r -p "$(tr "Select instance number [1]: " "选择实例编号 [1]: ")" _choice < /dev/tty || true
+ read -r -p "Select instance number [1]: " _choice < /dev/tty || true
if [[ -n "$_choice" && "$_choice" =~ ^[0-9]+$ ]]; then
local idx=$((_choice - 1))
if [[ $idx -ge 0 && $idx -lt ${#instances[@]} ]]; then
OPENCLAW_DIR="${instances[$idx]}"
else
- warn "$(tr "Invalid selection, using default" "无效选择,使用默认")"
+ warn "Invalid selection, using default"
OPENCLAW_DIR="${instances[0]}"
fi
else
@@ -205,7 +988,7 @@ collect_remote_config() {
remote_api_key=""
remote_agent_id=""
if [[ "$INSTALL_YES" != "1" ]]; then
- read -r -p "$(tr "OpenViking server URL [${remote_base_url}]: " "OpenViking 服务器地址 [${remote_base_url}]: ")" _base_url < /dev/tty || true
+ read -r -p "$(tr "OpenViking server URL [${remote_base_url}]: " "OpenViking 服务地址 [${remote_base_url}]: ")" _base_url < /dev/tty || true
read -r -p "$(tr "API Key (optional): " "API Key(可选): ")" _api_key < /dev/tty || true
read -r -p "$(tr "Agent ID (optional): " "Agent ID(可选): ")" _agent_id < /dev/tty || true
remote_base_url="${_base_url:-$remote_base_url}"
@@ -214,19 +997,19 @@ collect_remote_config() {
fi
}
-# ─── Environment checks ───
+# ---- Environment checks ----
check_python() {
local py="${OPENVIKING_PYTHON:-python3}"
local out
if ! out=$("$py" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null); then
- echo "fail|$py|$(tr "Python not found. Install Python >= 3.10." "Python 未找到,请安装 Python >= 3.10")"
+ echo "fail|$py|$(tr "Python not found. Install Python >= 3.10." "未找到 Python,请安装 Python >= 3.10。")"
return 1
fi
local major minor
IFS=. read -r major minor <<< "$out"
if [[ "$major" -lt 3 ]] || [[ "$major" -eq 3 && "$minor" -lt 10 ]]; then
- echo "fail|$out|$(tr "Python $out is too old. Need >= 3.10." "Python 版本 $out 过低,需要 >= 3.10")"
+ echo "fail|$out|$(tr "Python $out is too old. Need >= 3.10." "Python 版本 $out 过低,需要 >= 3.10。")"
return 1
fi
echo "ok|$out|$py"
@@ -236,14 +1019,14 @@ check_python() {
check_node() {
local out
if ! out=$(node -v 2>/dev/null); then
- echo "fail||$(tr "Node.js not found. Install Node.js >= 22." "Node.js 未找到,请安装 Node.js >= 22")"
+ echo "fail||$(tr "Node.js not found. Install Node.js >= 22." "未找到 Node.js,请安装 Node.js >= 22。")"
return 1
fi
local v="${out#v}"
local major
major="${v%%.*}"
if [[ -z "$major" ]] || [[ "$major" -lt 22 ]]; then
- echo "fail|$out|$(tr "Node.js $out is too old. Need >= 22." "Node.js 版本 $out 过低,需要 >= 22")"
+ echo "fail|$out|$(tr "Node.js $out is too old. Need >= 22." "Node.js 版本 $out 过低,需要 >= 22。")"
return 1
fi
echo "ok|$out|node"
@@ -253,9 +1036,9 @@ check_node() {
# Print guidance for missing dependencies
print_install_hints() {
local missing=("$@")
- bold "\n═══════════════════════════════════════════════════════════"
- bold " $(tr "Environment check failed. Install missing dependencies first:" "环境校验未通过,请先安装以下缺失组件:")"
- bold "═══════════════════════════════════════════════════════════\n"
+ bold "\n============================================================"
+ bold " $(tr "Environment check failed. Install missing dependencies first:" "环境校验未通过,请先安装以下缺失项:")"
+ bold "============================================================\n"
for item in "${missing[@]}"; do
local name="${item%%|*}"
@@ -266,39 +1049,39 @@ print_install_hints() {
done
detect_distro
- echo "$(tr "Based on your system ($DISTRO), you can run:" "根据你的系统 ($DISTRO),可执行以下命令安装:")"
+ echo "Based on your system (${DISTRO}), you can run:"
echo ""
if printf '%s\n' "${missing[@]}" | grep -q "Python"; then
- echo " # $(tr "Install Python 3.10+ (pyenv recommended)" "安装 Python 3.10+(推荐 pyenv)")"
+ echo " # Install Python 3.10+ (pyenv recommended)"
echo " curl https://pyenv.run | bash"
echo " export PATH=\"\$HOME/.pyenv/bin:\$PATH\""
echo " eval \"\$(pyenv init -)\""
echo " pyenv install 3.11.12"
echo " pyenv global 3.11.12"
- echo " python3 --version # $(tr "verify >= 3.10" "确认 >= 3.10")"
+ echo " python3 --version # verify >= 3.10"
echo ""
fi
if printf '%s\n' "${missing[@]}" | grep -q "Node"; then
- echo " # $(tr "Install Node.js 22+ (nvm)" "安装 Node.js 22+(nvm)")"
+ echo " # Install Node.js 22+ (nvm)"
echo " curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash"
echo " source ~/.bashrc"
echo " nvm install 22"
echo " nvm use 22"
- echo " node -v # $(tr "verify >= v22" "确认 >= v22")"
+ echo " node -v # verify >= v22"
echo ""
fi
- bold "$(tr "After installation, rerun this script." "安装完成后,请重新运行本脚本。")"
- bold "$(tr "See details: https://github.com/${REPO}/blob/${BRANCH}/examples/openclaw-plugin/INSTALL.md" "详细说明见: https://github.com/${REPO}/blob/${BRANCH}/examples/openclaw-plugin/INSTALL-ZH.md")"
+ bold "After installation, rerun this script."
+ bold "See details: https://github.com/${REPO}/blob/${PLUGIN_VERSION}/examples/openclaw-plugin/INSTALL.md"
echo ""
exit 1
}
# Validate environment
validate_environment() {
- info "$(tr "Checking OpenViking runtime environment..." "正在校验 OpenViking 运行环境...")"
+ info "Checking OpenViking runtime environment..."
echo ""
local missing=()
@@ -306,12 +1089,12 @@ validate_environment() {
r=$(check_python) || missing+=("Python 3.10+ | $(echo "$r" | cut -d'|' -f3)")
if [[ "${r%%|*}" == "ok" ]]; then
- info " Python: $(echo "$r" | cut -d'|' -f2) ✓"
+ info " Python: $(echo "$r" | cut -d'|' -f2) OK"
fi
r=$(check_node) || missing+=("Node.js 22+ | $(echo "$r" | cut -d'|' -f3)")
if [[ "${r%%|*}" == "ok" ]]; then
- info " Node.js: $(echo "$r" | cut -d'|' -f2) ✓"
+ info " Node.js: $(echo "$r" | cut -d'|' -f2) OK"
fi
if [[ ${#missing[@]} -gt 0 ]]; then
@@ -320,71 +1103,345 @@ validate_environment() {
fi
echo ""
- info "$(tr "Environment check passed ✓" "环境校验通过 ✓")"
+ info "$(tr "Environment check passed." "环境校验通过。")"
echo ""
}
-# ─── Install flow ───
+# ---- Version detection & manifest ----
+
+# Compare versions: version_gte "3.7.0" "3.7" returns 0 (true) if v1 >= v2
+version_gte() {
+ local v1="${1#v}"
+ local v2="${2#v}"
+ v1="${v1%%-*}"
+ v2="${v2%%-*}"
+ if [[ "$(printf '%s\n%s' "$v2" "$v1" | sort -V | head -1)" == "$v2" ]]; then
+ return 0
+ else
+ return 1
+ fi
+}
+
+is_semver_like() {
+ [[ "$1" =~ ^v?[0-9]+(\.[0-9]+){1,2}$ ]]
+}
+
+# Detect OpenClaw version
+detect_openclaw_version() {
+ local version_output
+ version_output=$(openclaw --version 2>/dev/null || echo "0.0.0")
+ local version
+ version=$(echo "$version_output" | grep -oE '[0-9]+\.[0-9]+(\.[0-9]+)?' | head -1)
+ if [[ -z "$version" ]]; then
+ version="0.0.0"
+ fi
+ echo "$version"
+}
+
+# Parse JSON using Python (available since we need Python for OpenViking)
+parse_json() {
+ local json_file="$1"
+ local key="$2"
+ local py_json="${OPENVIKING_PYTHON:-}"
+ [[ -z "$py_json" ]] && py_json="$(command -v python3 || command -v python || true)"
+ [[ -z "$py_json" ]] && py_json="python3"
+ "$py_json" -c "
+import json
+with open('$json_file') as f:
+ data = json.load(f)
+keys = '$key'.split('.')
+for k in keys:
+ if k.startswith('[') and k.endswith(']'):
+ data = data[int(k[1:-1])]
+ elif isinstance(data, dict):
+ data = data.get(k)
+ else:
+ data = None
+ break
+if isinstance(data, list):
+ print('\\n'.join(str(x) for x in data))
+elif data is not None:
+ print(data)
+" 2>/dev/null || echo ""
+}
+
+# Fallback configs for old versions without manifest
+# Format: plugin_dir|plugin_id|plugin_kind|plugin_slot|required_files|optional_files
+FALLBACK_LEGACY="openclaw-memory-plugin|memory-openviking|memory|memory|index.ts,config.ts,openclaw.plugin.json,package.json|package-lock.json,.gitignore"
+# Must match examples/openclaw-plugin/install-manifest.json files.*
+FALLBACK_CURRENT="openclaw-plugin|openviking|context-engine|contextEngine|index.ts,config.ts,package.json|context-engine.ts,client.ts,process-manager.ts,memory-ranking.ts,text-utils.ts,tool-call-id.ts,session-transcript-repair.ts,openclaw.plugin.json,tsconfig.json,package-lock.json,.gitignore"
+
+# Resolve plugin configuration from manifest or fallback
+resolve_plugin_config() {
+ local tag="$PLUGIN_VERSION"
+ local gh_raw="https://raw.githubusercontent.com/${REPO}/${tag}"
+ local manifest_file
+ manifest_file=$(mktemp)
+ local plugin_dir=""
+
+ info "$(tr "Resolving plugin configuration for version: ${tag}" "正在解析插件配置,版本: ${tag}")"
+
+ # Try to detect plugin directory
+ if curl -fsSL --connect-timeout 10 "${gh_raw}/examples/openclaw-plugin/install-manifest.json" -o "$manifest_file" 2>/dev/null && [[ -s "$manifest_file" ]]; then
+ plugin_dir="openclaw-plugin"
+ info "$(tr "Found manifest in openclaw-plugin" "在 openclaw-plugin 中找到 manifest")"
+ elif curl -fsSL --connect-timeout 10 "${gh_raw}/examples/openclaw-memory-plugin/install-manifest.json" -o "$manifest_file" 2>/dev/null && [[ -s "$manifest_file" ]]; then
+ plugin_dir="openclaw-memory-plugin"
+ info "Found manifest in openclaw-memory-plugin"
+ elif curl -fsSL --connect-timeout 10 --head "${gh_raw}/examples/openclaw-plugin/index.ts" 2>/dev/null | grep -q "200"; then
+ plugin_dir="openclaw-plugin"
+ info "No manifest found, using fallback for openclaw-plugin"
+ rm -f "$manifest_file"
+ elif curl -fsSL --connect-timeout 10 --head "${gh_raw}/examples/openclaw-memory-plugin/index.ts" 2>/dev/null | grep -q "200"; then
+ plugin_dir="openclaw-memory-plugin"
+ info "No manifest found, using fallback for openclaw-memory-plugin"
+ rm -f "$manifest_file"
+ else
+ rm -f "$manifest_file"
+ err "Cannot find plugin directory for version: ${tag}"
+ exit 1
+ fi
+
+ RESOLVED_PLUGIN_DIR="$plugin_dir"
+
+ # Parse manifest or use fallback
+ if [[ -s "$manifest_file" ]]; then
+ RESOLVED_PLUGIN_ID=$(parse_json "$manifest_file" "plugin.id")
+ RESOLVED_PLUGIN_KIND=$(parse_json "$manifest_file" "plugin.kind")
+ RESOLVED_PLUGIN_SLOT=$(parse_json "$manifest_file" "plugin.slot")
+ RESOLVED_MIN_OPENCLAW_VERSION=$(parse_json "$manifest_file" "compatibility.minOpenclawVersion")
+ RESOLVED_MIN_OPENVIKING_VERSION=$(parse_json "$manifest_file" "compatibility.minOpenvikingVersion")
+ RESOLVED_PLUGIN_RELEASE_ID=$(parse_json "$manifest_file" "release.id")
+ RESOLVED_NPM_OMIT_DEV=$(parse_json "$manifest_file" "npm.omitDev")
+ [[ -z "$RESOLVED_NPM_OMIT_DEV" ]] && RESOLVED_NPM_OMIT_DEV="true"
+
+ # Parse file lists
+ local required_str optional_str
+ required_str=$(parse_json "$manifest_file" "files.required")
+ optional_str=$(parse_json "$manifest_file" "files.optional")
+
+ IFS=$'\n' read -r -d '' -a RESOLVED_FILES_REQUIRED <<< "$required_str" || true
+ IFS=$'\n' read -r -d '' -a RESOLVED_FILES_OPTIONAL <<< "$optional_str" || true
+
+ rm -f "$manifest_file"
+ else
+ # No manifest: determine plugin identity by package.json name
+ local fallback_key="current"
+ [[ "$plugin_dir" == "openclaw-memory-plugin" ]] && fallback_key="legacy"
+ local compat_ver=""
+
+ local pkg_json_file
+ pkg_json_file=$(mktemp)
+ if curl -fsSL --connect-timeout 10 "${gh_raw}/examples/${plugin_dir}/package.json" -o "$pkg_json_file" 2>/dev/null && [[ -s "$pkg_json_file" ]]; then
+ local pkg_name
+ pkg_name=$(parse_json "$pkg_json_file" "name")
+ if [[ -n "$pkg_name" && "$pkg_name" != "@openclaw/openviking" ]]; then
+ fallback_key="legacy"
+ info "$(tr "Detected legacy plugin by package name: ${pkg_name}" "通过 package.json 名称检测到旧版插件: ${pkg_name}")"
+ elif [[ -n "$pkg_name" ]]; then
+ fallback_key="current"
+ fi
+
+ local engines_ver
+ engines_ver=$(parse_json "$pkg_json_file" "engines.openclaw")
+ engines_ver="${engines_ver#>=}"
+ engines_ver="${engines_ver#>}"
+ engines_ver="${engines_ver// /}"
+ if [[ -n "$engines_ver" ]]; then
+ compat_ver="$engines_ver"
+ info "$(tr "Read minOpenclawVersion from package.json engines.openclaw: >=${engines_ver}" "从 package.json engines.openclaw 读取最低版本: >=${engines_ver}")"
+ fi
+ fi
+ rm -f "$pkg_json_file"
+
+ local fallback=""
+ if [[ "$fallback_key" == "legacy" ]]; then
+ fallback="$FALLBACK_LEGACY"
+ else
+ fallback="$FALLBACK_CURRENT"
+ fi
+
+ local fb_dir fb_id fb_kind fb_slot required_csv optional_csv
+ IFS='|' read -r fb_dir fb_id fb_kind fb_slot required_csv optional_csv <<< "$fallback"
+ RESOLVED_PLUGIN_DIR="$plugin_dir"
+ RESOLVED_PLUGIN_ID="$fb_id"
+ RESOLVED_PLUGIN_KIND="$fb_kind"
+ RESOLVED_PLUGIN_SLOT="$fb_slot"
+ IFS=',' read -r -a RESOLVED_FILES_REQUIRED <<< "$required_csv"
+ IFS=',' read -r -a RESOLVED_FILES_OPTIONAL <<< "$optional_csv"
+ RESOLVED_NPM_OMIT_DEV="true"
+ RESOLVED_MIN_OPENVIKING_VERSION=""
+ RESOLVED_PLUGIN_RELEASE_ID=""
+
+ # If no compatVer from package.json, try main branch manifest
+ if [[ -z "$compat_ver" && "$tag" != "main" ]]; then
+ local main_manifest
+ main_manifest=$(mktemp)
+ local main_raw="https://raw.githubusercontent.com/${REPO}/main"
+ if curl -fsSL --connect-timeout 10 "${main_raw}/examples/openclaw-plugin/install-manifest.json" -o "$main_manifest" 2>/dev/null && [[ -s "$main_manifest" ]]; then
+ compat_ver=$(parse_json "$main_manifest" "compatibility.minOpenclawVersion")
+ if [[ -n "$compat_ver" ]]; then
+ info "$(tr "Read minOpenclawVersion from main branch manifest: >=${compat_ver}" "从 main 分支 manifest 读取最低版本: >=${compat_ver}")"
+ fi
+ fi
+ rm -f "$main_manifest"
+ fi
+
+ RESOLVED_MIN_OPENCLAW_VERSION="${compat_ver:-2026.3.7}"
+ fi
+
+ # Set plugin destination
+ PLUGIN_DEST="${OPENCLAW_DIR}/extensions/${RESOLVED_PLUGIN_ID}"
+
+ info "$(tr "Plugin: ${RESOLVED_PLUGIN_ID} (${RESOLVED_PLUGIN_KIND})" "插件: ${RESOLVED_PLUGIN_ID} (${RESOLVED_PLUGIN_KIND})")"
+}
+
+# Check OpenClaw version compatibility
+check_openclaw_compatibility() {
+ if [[ "$SKIP_OC" == "1" ]]; then
+ return 0
+ fi
+
+ local openclaw_version
+ openclaw_version=$(detect_openclaw_version)
+ info "$(tr "Detected OpenClaw version: ${openclaw_version}" "检测到 OpenClaw 版本: ${openclaw_version}")"
+
+ # If no minimum version required, pass
+ if [[ -z "$RESOLVED_MIN_OPENCLAW_VERSION" ]]; then
+ return 0
+ fi
+
+ # If user explicitly requested an old version, pass
+ if [[ "$PLUGIN_VERSION" != "main" ]] && is_semver_like "$PLUGIN_VERSION" && ! version_gte "$PLUGIN_VERSION" "v0.2.8"; then
+ return 0
+ fi
+
+ # Check compatibility
+ if ! version_gte "$openclaw_version" "$RESOLVED_MIN_OPENCLAW_VERSION"; then
+ err "OpenClaw ${openclaw_version} does not support this plugin (requires >= ${RESOLVED_MIN_OPENCLAW_VERSION})"
+ echo ""
+ bold "Please choose one of the following options:"
+ echo ""
+ echo " Option 1: Upgrade OpenClaw"
+ echo " npm update -g openclaw --registry ${NPM_REGISTRY}"
+ echo ""
+ echo " Option 2: Install a legacy plugin release compatible with your current OpenClaw version"
+ echo " $(legacy_plugin_install_hint)"
+ echo ""
+ exit 1
+
+
+
+
+
+
+
+
+ fi
+
+ return 0
+}
+
+check_requested_openviking_compatibility() {
+ if [[ "$SKIP_OV" == "1" || -z "$RESOLVED_MIN_OPENVIKING_VERSION" || -z "$OPENVIKING_VERSION" ]]; then
+ return 0
+ fi
+
+ if ! version_gte "$OPENVIKING_VERSION" "$RESOLVED_MIN_OPENVIKING_VERSION"; then
+ err "OpenViking ${OPENVIKING_VERSION} does not support this plugin (requires >= ${RESOLVED_MIN_OPENVIKING_VERSION})"
+ echo ""
+ echo " Use a newer OpenViking version, or omit --openviking-version to install the latest release."
+ exit 1
+ fi
+}
+
+# ---- Install flow ----
install_openclaw() {
if [[ "$SKIP_OC" == "1" ]]; then
- info "$(tr "Skipping OpenClaw check (SKIP_OPENCLAW=1)" "跳过 OpenClaw 校验 (SKIP_OPENCLAW=1)")"
+ info "$(tr "Skipping OpenClaw check (SKIP_OPENCLAW=1)" "跳过 OpenClaw 检查 (SKIP_OPENCLAW=1)")"
return 0
fi
- info "$(tr "Checking OpenClaw..." "正在校验 OpenClaw...")"
+ info "$(tr "Checking OpenClaw..." "正在检查 OpenClaw...")"
if command -v openclaw >/dev/null 2>&1; then
- info "$(tr "OpenClaw detected ✓" "OpenClaw 已安装 ✓")"
+ info "$(tr "OpenClaw detected." "已检测到 OpenClaw。")"
return 0
fi
- err "$(tr "OpenClaw not found. Install it manually, then rerun this script." "未检测到 OpenClaw,请先手动安装后再执行本脚本")"
+ err "OpenClaw not found. Install it manually, then rerun this script."
echo ""
- echo "$(tr "Recommended command:" "推荐命令:")"
+ echo "Recommended command:"
echo " npm install -g openclaw --registry ${NPM_REGISTRY}"
echo ""
- echo "$(tr "If npm global install fails, install Node via nvm and retry." "如 npm 全局安装失败,建议先用 nvm 安装 Node 后再执行上述命令。")"
- echo "$(tr "After installation, run:" "安装完成后,运行:")"
+ echo "If npm global install fails, install Node via nvm and retry."
+ echo "After installation, run:"
echo " openclaw --version"
echo " openclaw onboard"
echo ""
exit 1
}
+run_pip_install_capture() {
+ local log_file="$1"
+ shift
+ : > "${log_file}"
+ if "$@" > >(tee "${log_file}") 2> >(tee -a "${log_file}" >&2); then
+ return 0
+ fi
+ return 1
+}
+
install_openviking() {
if [[ "$SKIP_OV" == "1" ]]; then
info "$(tr "Skipping OpenViking install (SKIP_OPENVIKING=1)" "跳过 OpenViking 安装 (SKIP_OPENVIKING=1)")"
return 0
fi
local py="${OPENVIKING_PYTHON:-python3}"
- info "$(tr "Installing OpenViking from PyPI..." "正在安装 OpenViking (PyPI)...")"
- info "$(tr "Using pip index: ${PIP_INDEX_URL}" "使用 pip 镜像源: ${PIP_INDEX_URL}")"
+
+ # Determine package spec
+ local pkg_spec="openviking"
+ if [[ -n "$OPENVIKING_VERSION" ]]; then
+ pkg_spec="openviking==${OPENVIKING_VERSION}"
+ info "$(tr "Installing OpenViking ${OPENVIKING_VERSION} from PyPI..." "正在安装 OpenViking ${OPENVIKING_VERSION} (PyPI)...")"
+ else
+ info "$(tr "Installing OpenViking (latest) from PyPI..." "正在安装 OpenViking (最新版) (PyPI)...")"
+ fi
+ info "$(tr "Using pip index: ${PIP_INDEX_URL}" "使用 pip 镜像: ${PIP_INDEX_URL}")"
+
+ info "Package: ${pkg_spec}"
# Try system-wide pip first (works on many systems)
- local err_out
- err_out=$("$py" -m pip install --upgrade pip -q -i "${PIP_INDEX_URL}" 2>&1) || true
- if err_out=$("$py" -m pip install openviking -i "${PIP_INDEX_URL}" 2>&1); then
+ local err_out=""
+ local pip_log
+ pip_log=$(mktemp)
+ "$py" -m pip install --upgrade pip -q -i "${PIP_INDEX_URL}" >/dev/null 2>&1 || true
+ if run_pip_install_capture "${pip_log}" "$py" -m pip install --progress-bar on "$pkg_spec" -i "${PIP_INDEX_URL}"; then
+ rm -f "${pip_log}" 2>/dev/null || true
OPENVIKING_PYTHON_PATH="$(command -v "$py" || true)"
[[ -z "$OPENVIKING_PYTHON_PATH" ]] && OPENVIKING_PYTHON_PATH="$py"
- info "$(tr "OpenViking installed ✓" "OpenViking 安装完成 ✓")"
+ info "$(tr "OpenViking installed." "OpenViking 安装完成。")"
return 0
fi
+ err_out="$(cat "${pip_log}" 2>/dev/null || true)"
+ rm -f "${pip_log}" 2>/dev/null || true
+
# When system has no pip, or PEP 668 (Debian/Ubuntu): use a venv
if echo "$err_out" | grep -q "externally-managed-environment\|externally managed\|No module named pip"; then
if echo "$err_out" | grep -q "No module named pip"; then
- info "$(tr "System Python has no pip. Using a venv at ~/.openviking/venv" "系统 Python 未安装 pip,将使用 ~/.openviking/venv 虚拟环境")"
+ info "System Python has no pip. Using a venv at ~/.openviking/venv"
else
# Opt-in: allow install with --break-system-packages when venv is not available (PEP 668 only, default off)
if [[ "${OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES}" == "1" ]]; then
- info "$(tr "Installing OpenViking with --break-system-packages (OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1)" "正在以 --break-system-packages 安装 OpenViking(已设置 OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1)")"
- if "$py" -m pip install --break-system-packages openviking -i "${PIP_INDEX_URL}"; then
+ info "Installing OpenViking with --break-system-packages (OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1)"
+ if "$py" -m pip install --progress-bar on --break-system-packages "$pkg_spec" -i "${PIP_INDEX_URL}"; then
OPENVIKING_PYTHON_PATH="$(command -v "$py" || true)"
[[ -z "$OPENVIKING_PYTHON_PATH" ]] && OPENVIKING_PYTHON_PATH="$py"
- info "$(tr "OpenViking installed ✓ (system)" "OpenViking 安装完成 ✓(系统)")"
+ info "OpenViking installed (system)"
return 0
fi
fi
- info "$(tr "System Python is externally managed (PEP 668). Using a venv at ~/.openviking/venv" "检测到系统 Python 受管 (PEP 668),将使用 ~/.openviking/venv 虚拟环境")"
+ info "System Python is externally managed (PEP 668). Using a venv at ~/.openviking/venv"
fi
mkdir -p "${OPENVIKING_DIR}"
local venv_dir="${OPENVIKING_DIR}/venv"
@@ -392,10 +1449,10 @@ install_openviking() {
# Reuse existing venv if it has openviking (avoid repeated create on re-run)
if [[ -x "${venv_py}" ]] && "${venv_py}" -c "import openviking" 2>/dev/null; then
- info "$(tr "Using existing venv with openviking: ${venv_dir}" "复用已有虚拟环境(已装 openviking): ${venv_dir}")"
- "${venv_py}" -m pip install -q -U openviking -i "${PIP_INDEX_URL}" 2>/dev/null || true
+ info "Using existing venv with openviking: ${venv_dir}"
+ "${venv_py}" -m pip install --progress-bar on -U "$pkg_spec" -i "${PIP_INDEX_URL}" || true
OPENVIKING_PYTHON_PATH="${venv_dir}/bin/python"
- info "$(tr "OpenViking installed ✓ (venv)" "OpenViking 安装完成 ✓(虚拟环境)")"
+ info "OpenViking installed (venv)"
return 0
fi
@@ -416,7 +1473,7 @@ install_openviking() {
# Prefer mirror for get-pip.py when PIP_INDEX_URL is in China to avoid slow/timeout
if [[ -n "${GET_PIP_URL}" ]]; then
get_pip_url="${GET_PIP_URL}"
- elif echo "${PIP_INDEX_URL}" | grep -q "tuna.tsinghua\|pypi.tuna"; then
+ elif echo "${PIP_INDEX_URL}" | grep -q "volces\|tuna.tsinghua\|pypi.tuna"; then
get_pip_url="https://mirrors.tuna.tsinghua.edu.cn/pypi/web/static/get-pip.py"
else
get_pip_url="https://bootstrap.pypa.io/get-pip.py"
@@ -447,29 +1504,43 @@ install_openviking() {
rm -rf "${venv_dir}" 2>/dev/null || true
local py_ver
py_ver=$("$py" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "3")
- err "$(tr "Could not create venv. Install venv then re-run:" "无法创建虚拟环境。请先安装 venv 后重新执行:")"
+ err "Could not create venv. Install venv then re-run:"
echo " sudo apt install python${py_ver}-venv # or python3-full"
echo ""
- echo "$(tr "Or (may conflict with system packages):" "或允许安装到系统(可能与系统包冲突):")"
+ echo "Or (may conflict with system packages):"
echo " OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1 curl -fsSL ... | bash"
exit 1
fi
- "$venv_py" -m pip install --upgrade pip -q -i "${PIP_INDEX_URL}"
- if ! "$venv_py" -m pip install openviking -i "${PIP_INDEX_URL}"; then
- err "$(tr "OpenViking install failed in venv." "在虚拟环境中安装 OpenViking 失败。")"
+ "$venv_py" -m pip install --upgrade pip -q -i "${PIP_INDEX_URL}" >/dev/null 2>&1
+ if ! "$venv_py" -m pip install --progress-bar on "$pkg_spec" -i "${PIP_INDEX_URL}"; then
+ err "OpenViking install failed in venv."
exit 1
fi
OPENVIKING_PYTHON_PATH="${venv_dir}/bin/python"
- info "$(tr "OpenViking installed ✓ (venv)" "OpenViking 安装完成 ✓(虚拟环境)")"
+ info "OpenViking installed (venv)"
return 0
fi
- err "$(tr "OpenViking install failed. Check Python version (>=3.10) and pip." "OpenViking 安装失败,请检查 Python 版本 (需 >= 3.10) 及 pip")"
+ err "$(tr "OpenViking install failed. Check Python version (>=3.10) and pip." "OpenViking 安装失败,请检查 Python 版本(需 >= 3.10)与 pip。")"
echo "$err_out" >&2
exit 1
}
+normalize_port() {
+ local value="$1"
+ local default_value="$2"
+ local label="$3"
+ if [[ "$value" =~ ^[0-9]+$ ]] && (( value >= 1 && value <= 65535 )); then
+ echo "$value"
+ return 0
+ fi
+ if [[ -n "$value" ]]; then
+ warn "Invalid ${label}: ${value}. Using ${default_value}."
+ fi
+ echo "$default_value"
+}
+
configure_openviking_conf() {
mkdir -p "${OPENVIKING_DIR}"
@@ -481,19 +1552,17 @@ configure_openviking_conf() {
local vlm_api_key="${OPENVIKING_VLM_API_KEY:-${OPENVIKING_ARK_API_KEY:-}}"
local embedding_api_key="${OPENVIKING_EMBEDDING_API_KEY:-${OPENVIKING_ARK_API_KEY:-}}"
local conf_path="${OPENVIKING_DIR}/ov.conf"
- local vlm_api_json="null"
- local embedding_api_json="null"
if [[ "$INSTALL_YES" != "1" ]]; then
echo ""
read -r -p "$(tr "OpenViking workspace path [${workspace}]: " "OpenViking 数据目录 [${workspace}]: ")" _workspace < /dev/tty || true
- read -r -p "$(tr "OpenViking HTTP port [${server_port}]: " "OpenViking HTTP 端口 [${server_port}]: ")" _server_port < /dev/tty || true
- read -r -p "$(tr "AGFS port [${agfs_port}]: " "AGFS 端口 [${agfs_port}]: ")" _agfs_port < /dev/tty || true
- read -r -p "$(tr "VLM model [${vlm_model}]: " "VLM 模型 [${vlm_model}]: ")" _vlm_model < /dev/tty || true
- read -r -p "$(tr "Embedding model [${embedding_model}]: " "Embedding 模型 [${embedding_model}]: ")" _embedding_model < /dev/tty || true
- echo "$(tr "VLM and Embedding API keys can differ. You can leave either empty and edit ov.conf later." "说明:VLM 与 Embedding 的 API Key 可能不同,可分别填写;留空后续可在 ov.conf 修改。")"
- read -r -p "$(tr "VLM API key (optional): " "VLM API Key(可留空): ")" _vlm_api_key < /dev/tty || true
- read -r -p "$(tr "Embedding API key (optional): " "Embedding API Key(可留空): ")" _embedding_api_key < /dev/tty || true
+ read -r -p "OpenViking HTTP port [${server_port}]: " _server_port < /dev/tty || true
+ read -r -p "AGFS port [${agfs_port}]: " _agfs_port < /dev/tty || true
+ read -r -p "VLM model [${vlm_model}]: " _vlm_model < /dev/tty || true
+ read -r -p "Embedding model [${embedding_model}]: " _embedding_model < /dev/tty || true
+ echo "VLM and Embedding API keys can differ. You can leave either empty and edit ov.conf later."
+ read -r -p "VLM API key (optional): " _vlm_api_key < /dev/tty || true
+ read -r -p "Embedding API key (optional): " _embedding_api_key < /dev/tty || true
workspace="${_workspace:-$workspace}"
server_port="${_server_port:-$server_port}"
@@ -504,85 +1573,95 @@ configure_openviking_conf() {
embedding_api_key="${_embedding_api_key:-$embedding_api_key}"
fi
- if [[ -n "${vlm_api_key}" ]]; then
- vlm_api_json="\"${vlm_api_key}\""
- fi
- if [[ -n "${embedding_api_key}" ]]; then
- embedding_api_json="\"${embedding_api_key}\""
- fi
-
+ server_port="$(normalize_port "${server_port}" "${DEFAULT_SERVER_PORT}" "OpenViking HTTP port")"
+ agfs_port="$(normalize_port "${agfs_port}" "${DEFAULT_AGFS_PORT}" "AGFS port")"
mkdir -p "${workspace}"
- cat > "${conf_path}" <<EOF
-{
- "server": {
- "host": "127.0.0.1",
- "port": ${server_port},
- "root_api_key": null,
- "cors_origins": ["*"]
- },
- "storage": {
- "workspace": "${workspace}",
- "vectordb": { "name": "context", "backend": "local", "project": "default" },
- "agfs": { "port": ${agfs_port}, "log_level": "warn", "backend": "local", "timeout": 10, "retry_times": 3 }
- },
- "embedding": {
- "dense": {
- "provider": "volcengine",
- "api_key": ${embedding_api_json},
- "model": "${embedding_model}",
- "api_base": "https://ark.cn-beijing.volces.com/api/v3",
- "dimension": 1024,
- "input": "multimodal"
- }
- },
- "log": {
- "level": "WARNING",
- "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
- "output": "file",
- "rotation": true,
- "rotation_days": 3,
- "rotation_interval": "midnight"
- },
- "vlm": {
- "provider": "volcengine",
- "api_key": ${vlm_api_json},
- "model": "${vlm_model}",
- "api_base": "https://ark.cn-beijing.volces.com/api/v3",
- "temperature": 0.1,
- "max_retries": 3
- }
+ local py_json="${OPENVIKING_PYTHON_PATH:-${OPENVIKING_PYTHON:-}}"
+ [[ -z "$py_json" ]] && py_json="$(command -v python3 || command -v python || true)"
+ [[ -z "$py_json" ]] && py_json="python3"
+ WORKSPACE="${workspace}" \
+ SERVER_PORT="${server_port}" \
+ AGFS_PORT="${agfs_port}" \
+ VLM_MODEL="${vlm_model}" \
+ EMBEDDING_MODEL="${embedding_model}" \
+ VLM_API_KEY="${vlm_api_key}" \
+ EMBEDDING_API_KEY="${embedding_api_key}" \
+ "$py_json" - <<'PY' > "${conf_path}"
+import json
+import os
+
+def maybe_value(name):
+ value = os.environ.get(name, "")
+ return value or None
+
+config = {
+ "server": {
+ "host": "127.0.0.1",
+ "port": int(os.environ["SERVER_PORT"]),
+ "root_api_key": None,
+ "cors_origins": ["*"],
+ },
+ "storage": {
+ "workspace": os.environ["WORKSPACE"],
+ "vectordb": {"name": "context", "backend": "local", "project": "default"},
+ "agfs": {
+ "port": int(os.environ["AGFS_PORT"]),
+ "log_level": "warn",
+ "backend": "local",
+ "timeout": 10,
+ "retry_times": 3,
+ },
+ },
+ "embedding": {
+ "dense": {
+ "provider": "volcengine",
+ "api_key": maybe_value("EMBEDDING_API_KEY"),
+ "model": os.environ["EMBEDDING_MODEL"],
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "input": "multimodal",
+ }
+ },
+ "log": {
+ "level": "WARNING",
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+ "output": "file",
+ "rotation": True,
+ "rotation_days": 3,
+ "rotation_interval": "midnight",
+ },
+ "vlm": {
+ "provider": "volcengine",
+ "api_key": maybe_value("VLM_API_KEY"),
+ "model": os.environ["VLM_MODEL"],
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "temperature": 0.1,
+ "max_retries": 3,
+ },
}
-EOF
+
+print(json.dumps(config, ensure_ascii=False, indent=2))
+PY
SELECTED_SERVER_PORT="${server_port}"
+ SELECTED_CONFIG_PATH="${conf_path}"
info "$(tr "Config generated: ${conf_path}" "已生成配置: ${conf_path}")"
}
download_plugin() {
- local gh_raw="https://raw.githubusercontent.com/${REPO}/${BRANCH}"
- local files=(
- "examples/openclaw-plugin/index.ts"
- "examples/openclaw-plugin/context-engine.ts"
- "examples/openclaw-plugin/config.ts"
- "examples/openclaw-plugin/client.ts"
- "examples/openclaw-plugin/process-manager.ts"
- "examples/openclaw-plugin/memory-ranking.ts"
- "examples/openclaw-plugin/text-utils.ts"
- "examples/openclaw-plugin/openclaw.plugin.json"
- "examples/openclaw-plugin/package.json"
- "examples/openclaw-plugin/package-lock.json"
- "examples/openclaw-plugin/tsconfig.json"
- "examples/openclaw-plugin/.gitignore"
- )
- local total=${#files[@]}
+ local gh_raw="https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}"
+ local plugin_dir="$RESOLVED_PLUGIN_DIR"
+ local total=$(( ${#RESOLVED_FILES_REQUIRED[@]} + ${#RESOLVED_FILES_OPTIONAL[@]} ))
local i=0
+ local max_retries=3
mkdir -p "${PLUGIN_DEST}"
- info "$(tr "Downloading openviking plugin from ${REPO}@${BRANCH} (${total} files)..." "正在从 ${REPO}@${BRANCH} 下载 openviking 插件(共 ${total} 个文件)...")"
- local max_retries=3
- for rel in "${files[@]}"; do
+ info "$(tr "Downloading plugin from ${REPO}@${PLUGIN_VERSION} (${total} files)..." "正在从 ${REPO}@${PLUGIN_VERSION} 下载插件(共 ${total} 个文件)...")"
+
+ # Download required files
+ for name in "${RESOLVED_FILES_REQUIRED[@]}"; do
+ [[ -z "$name" ]] && continue
i=$((i + 1))
- local name="${rel##*/}"
- local url="${gh_raw}/${rel}"
+ local url="${gh_raw}/examples/${plugin_dir}/${name}"
local ok=0
echo -n " [${i}/${total}] ${name} "
local attempt=1
@@ -595,66 +1674,272 @@ download_plugin() {
attempt=$((attempt + 1))
done
if [[ "$ok" -eq 1 ]]; then
- echo "✓"
- elif [[ "$name" == ".gitignore" ]]; then
- echo "$(tr "(retries failed, using minimal .gitignore)" "(重试失败,使用最小 .gitignore)")"
- echo "node_modules/" > "${PLUGIN_DEST}/${name}"
+ echo " OK"
else
echo ""
err "$(tr "Download failed after ${max_retries} retries: ${url}" "下载失败(已重试 ${max_retries} 次): ${url}")"
exit 1
fi
done
- info "$(tr "Installing plugin npm dependencies (may take 1-2 min, npm will show progress)..." "正在安装插件 npm 依赖(约 1–2 分钟,npm 会显示进度)...")"
- (cd "${PLUGIN_DEST}" && npm install --no-audit --no-fund) || {
+
+ # Download optional files (retry like required; HTTP 404 skips silently — only non-404 failures are reported)
+ for name in "${RESOLVED_FILES_OPTIONAL[@]}"; do
+ [[ -z "$name" ]] && continue
+ i=$((i + 1))
+ local url="${gh_raw}/examples/${plugin_dir}/${name}"
+ local dest="${PLUGIN_DEST}/${name}"
+ echo -n " [${i}/${total}] ${name} "
+ local attempt=1
+ local code=""
+ local got404=0
+ while [[ "$attempt" -le "${max_retries}" ]]; do
+ rm -f "${dest}"
+ code="$(curl -o "${dest}" -sS -w "%{http_code}" --connect-timeout 15 --max-time 120 "${url}" 2>/dev/null || echo "000")"
+ if [[ "$code" == "200" ]] && [[ -s "${dest}" ]]; then
+ echo " OK"
+ got404=0
+ break
+ fi
+ rm -f "${dest}"
+ if [[ "$code" == "404" ]]; then
+ got404=1
+ break
+ fi
+ [[ "$attempt" -lt "${max_retries}" ]] && sleep 2
+ attempt=$((attempt + 1))
+ done
+ if [[ "$code" == "200" ]] && [[ -s "${dest}" ]]; then
+ continue
+ fi
+ if [[ "$got404" -eq 1 ]] || [[ "$code" == "404" ]]; then
+ if [[ "$name" == ".gitignore" ]]; then
+ echo "node_modules/" > "${dest}"
+ echo " OK"
+ else
+ echo " $(tr "skip" "跳过")"
+ fi
+ continue
+ fi
+ echo ""
+ err "$(tr "Optional file download failed after ${max_retries} retries (HTTP ${code:-unknown}). Check network or URL: ${url}" "可选文件已重试 ${max_retries} 次仍失败(HTTP ${code:-unknown})。请检查网络或 URL: ${url}")"
+ exit 1
+ done
+
+ # npm install
+ info "$(tr "Installing plugin npm dependencies..." "正在安装插件 npm 依赖...")"
+ local npm_args="--no-audit --no-fund"
+ if [[ "$RESOLVED_NPM_OMIT_DEV" == "true" ]]; then
+ npm_args="--omit=dev $npm_args"
+ fi
+ (cd "${PLUGIN_DEST}" && npm install --registry "${NPM_REGISTRY}" $npm_args) || {
err "$(tr "Plugin dependency install failed: ${PLUGIN_DEST}" "插件依赖安装失败: ${PLUGIN_DEST}")"
exit 1
}
info "$(tr "Plugin deployed: ${PLUGIN_DEST}" "插件部署完成: ${PLUGIN_DEST}")"
}
+ensure_existing_plugin_for_upgrade() {
+ if [[ ! -d "${PLUGIN_DEST}" ]]; then
+ err "Plugin upgrade mode expects an existing plugin install. Run the full installer first."
+ exit 1
+ fi
+}
+
+create_plugin_staging_dir() {
+ local plugin_id="${RESOLVED_PLUGIN_ID:-openviking}"
+ local extensions_dir="${OPENCLAW_DIR}/extensions"
+ local staging_dir="${extensions_dir}/.${plugin_id}.staging.$$.$RANDOM"
+ mkdir -p "${extensions_dir}"
+ rm -rf "${staging_dir}"
+ mkdir -p "${staging_dir}"
+ echo "${staging_dir}"
+}
+
+finalize_plugin_deployment() {
+ local staging_dir="$1"
+ rm -rf "${PLUGIN_DEST}"
+ if ! mv "${staging_dir}" "${PLUGIN_DEST}" 2>/dev/null; then
+ cp -R "${staging_dir}" "${PLUGIN_DEST}"
+ rm -rf "${staging_dir}"
+ fi
+ info "Plugin deployed: ${PLUGIN_DEST}"
+}
+
+deploy_plugin_from_remote() {
+ local final_dest="${PLUGIN_DEST}"
+ local staging_dir
+ staging_dir="$(create_plugin_staging_dir)"
+ PLUGIN_DEST="${staging_dir}"
+ if download_plugin; then
+ PLUGIN_DEST="${final_dest}"
+ finalize_plugin_deployment "${staging_dir}"
+ return 0
+ fi
+
+ local status=$?
+ PLUGIN_DEST="${final_dest}"
+ rm -rf "${staging_dir}"
+ return "${status}"
+}
+
+# Remove stale OpenClaw registration for this plugin id so a fresh deploy can be discovered.
+# Matches INSTALL*.md manual cleanup (stale entries + slot + allow + load.paths).
+resolved_plugin_slot_fallback() {
+ case "${RESOLVED_PLUGIN_ID}" in
+ memory-openviking) printf '%s\n' "none" ;;
+ openviking) printf '%s\n' "legacy" ;;
+ *) printf '%s\n' "none" ;;
+ esac
+}
+
+scrub_stale_openclaw_plugin_registration() {
+ local config_path
+ config_path="$(get_openclaw_config_path)"
+ [[ -f "${config_path}" ]] || return 0
+ local plugin_id="$RESOLVED_PLUGIN_ID"
+ local plugin_slot="$RESOLVED_PLUGIN_SLOT"
+ local slot_fallback
+ slot_fallback="$(resolved_plugin_slot_fallback)"
+
+ node - "${config_path}" "${plugin_id}" "${plugin_slot}" "${slot_fallback}" <<'NODE' || true
+const fs = require("fs");
+const configPath = process.argv[2];
+const pluginId = process.argv[3];
+const slot = process.argv[4];
+const slotFallback = process.argv[5];
+
+let raw;
+try {
+ raw = fs.readFileSync(configPath, "utf8");
+} catch {
+ process.exit(0);
+}
+let cfg;
+try {
+ cfg = JSON.parse(raw);
+} catch {
+ process.exit(0);
+}
+if (!cfg.plugins) process.exit(0);
+
+let changed = false;
+const p = cfg.plugins;
+
+if (p.entries && Object.prototype.hasOwnProperty.call(p.entries, pluginId)) {
+ delete p.entries[pluginId];
+ changed = true;
+}
+
+if (Array.isArray(p.allow)) {
+ const next = p.allow.filter((id) => id !== pluginId);
+ if (next.length !== p.allow.length) {
+ p.allow = next;
+ changed = true;
+ }
+}
+
+if (p.load && Array.isArray(p.load.paths)) {
+ const norm = (s) => String(s).replace(/\\/g, "/");
+ const extNeedle = `/extensions/${pluginId}`;
+ const next = p.load.paths.filter((path) => {
+ if (typeof path !== "string") return true;
+ const n = norm(path);
+ return !n.includes(extNeedle);
+ });
+ if (next.length !== p.load.paths.length) {
+ p.load.paths = next;
+ changed = true;
+ }
+}
+
+if (p.slots && p.slots[slot] === pluginId) {
+ p.slots[slot] = slotFallback;
+ changed = true;
+}
+
+if (!changed) process.exit(0);
+
+const out = JSON.stringify(cfg, null, 2) + "\n";
+const tmp = `${configPath}.ov-install-tmp.${process.pid}`;
+fs.writeFileSync(tmp, out, "utf8");
+fs.renameSync(tmp, configPath);
+NODE
+}
+
configure_openclaw_plugin() {
+ local preserve_existing_config="${1:-0}"
+ local skip_gateway_mode="${2:-0}"
+ local claim_slot="${3:-1}"
info "$(tr "Configuring OpenClaw plugin..." "正在配置 OpenClaw 插件...")"
+ local plugin_id="$RESOLVED_PLUGIN_ID"
+ local plugin_slot="$RESOLVED_PLUGIN_SLOT"
+
local oc_env=()
if [[ "$OPENCLAW_DIR" != "${HOME_DIR}/.openclaw" ]]; then
oc_env=(env OPENCLAW_STATE_DIR="$OPENCLAW_DIR")
fi
+ # Stale plugins.entries / slots / allow from a previous partial install break `config set plugins.slots.*`.
+ if [[ "${preserve_existing_config}" != "1" ]]; then
+ scrub_stale_openclaw_plugin_registration
+ fi
+
# Enable plugin (files already deployed to extensions dir by deploy_plugin)
- "${oc_env[@]}" openclaw plugins enable openviking || { err "$(tr "openclaw plugins enable failed" "openclaw 插件启用失败")"; exit 1; }
- "${oc_env[@]}" openclaw config set plugins.slots.contextEngine openviking
+ "${oc_env[@]}" openclaw plugins enable "$plugin_id" || { err "openclaw plugins enable failed"; exit 1; }
+ if [[ "${claim_slot}" == "1" ]]; then
+ "${oc_env[@]}" openclaw config set "plugins.slots.${plugin_slot}" "$plugin_id"
+ else
+ warn "Skipped claiming plugins.slots.${plugin_slot}; it is currently owned by another plugin."
+ fi
+ if [[ "${preserve_existing_config}" == "1" ]]; then
+ info "Preserved existing plugin runtime config"
+ return 0
+ fi
# Set gateway mode
- "${oc_env[@]}" openclaw config set gateway.mode local
+ if [[ "${skip_gateway_mode}" != "1" ]]; then
+ "${oc_env[@]}" openclaw config set gateway.mode "${SELECTED_MODE}"
+ fi
# Set plugin config for the selected mode
if [[ "$SELECTED_MODE" == "local" ]]; then
- local ov_conf_path="${OPENVIKING_DIR}/ov.conf"
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.mode local
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.configPath "${ov_conf_path}"
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.port "${SELECTED_SERVER_PORT}"
+ local ov_conf_path="${SELECTED_CONFIG_PATH:-${OPENVIKING_DIR}/ov.conf}"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.mode" local
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.configPath" "${ov_conf_path}"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.port" "${SELECTED_SERVER_PORT}"
else
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.mode remote
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.baseUrl "${remote_base_url}"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.mode" remote
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.baseUrl" "${remote_base_url}"
if [[ -n "${remote_api_key}" ]]; then
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.apiKey "${remote_api_key}"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.apiKey" "${remote_api_key}"
fi
if [[ -n "${remote_agent_id}" ]]; then
- "${oc_env[@]}" openclaw config set plugins.entries.openviking.config.agentId "${remote_agent_id}"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.agentId" "${remote_agent_id}"
fi
fi
+ # Legacy (memory) plugins need explicit targetUri/autoRecall/autoCapture (new version has defaults in config.ts)
+ if [[ "${RESOLVED_PLUGIN_KIND}" == "memory" ]]; then
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.targetUri" "viking://user/memories"
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.autoRecall" true --json
+ "${oc_env[@]}" openclaw config set "plugins.entries.${plugin_id}.config.autoCapture" true --json
+ fi
+
info "$(tr "OpenClaw plugin configured" "OpenClaw 插件配置完成")"
}
-write_openviking_env() {
+_deprecated_write_openviking_env() {
local py_path
if [[ -n "${OPENVIKING_PYTHON_PATH}" ]]; then
py_path="${OPENVIKING_PYTHON_PATH}"
else
py_path="$(command -v python3 || command -v python || true)"
fi
+ if [[ -z "$py_path" ]]; then
+ py_path="${OPENVIKING_PYTHON:-python3}"
+ warn "Could not resolve Python path; using OPENVIKING_PYTHON or python3 in openviking.env. Edit the file if startup fails."
+ fi
mkdir -p "${OPENCLAW_DIR}"
cat > "${OPENCLAW_DIR}/openviking.env" <<EOF
export OPENVIKING_PYTHON='${py_path}'
@@ -662,58 +1947,180 @@ EOF
info "$(tr "Environment file generated: ${OPENCLAW_DIR}/openviking.env" "已生成环境文件: ${OPENCLAW_DIR}/openviking.env")"
}
-# ─── 主流程 ───
+# ---- Main flow ----
+
+write_openviking_env() {
+ local include_python="${1:-1}"
+ local py_path=""
+ local lines=()
+
+ if [[ "$OPENCLAW_DIR" != "$DEFAULT_OPENCLAW_DIR" ]]; then
+ lines+=("export OPENCLAW_STATE_DIR='$(shell_single_quote "${OPENCLAW_DIR}")'")
+ fi
+
+ if [[ "$include_python" == "1" ]]; then
+ if [[ -n "${OPENVIKING_PYTHON_PATH}" ]]; then
+ py_path="${OPENVIKING_PYTHON_PATH}"
+ else
+ py_path="$(command -v python3 || command -v python || true)"
+ fi
+ if [[ -z "$py_path" ]]; then
+ py_path="${OPENVIKING_PYTHON:-python3}"
+ warn "Could not resolve Python path; using OPENVIKING_PYTHON or python3 in openviking.env. Edit the file if startup fails."
+ fi
+
+ # Verify the resolved Python can actually import openviking
+ if ! "$py_path" -c "import openviking" 2>/dev/null; then
+ warn "Resolved Python (${py_path}) cannot import openviking. Searching for the correct Python..."
+ local corrected=""
+ for candidate in python3.13 python3.12 python3.11 python3.10 python3 python; do
+ local cpath
+ cpath="$(command -v "$candidate" 2>/dev/null || true)"
+ [[ -z "$cpath" || "$cpath" == "$py_path" ]] && continue
+ if "$cpath" -c "import openviking" 2>/dev/null; then
+ corrected="$cpath"
+ break
+ fi
+ done
+ if [[ -n "$corrected" ]]; then
+ info "Auto-corrected OPENVIKING_PYTHON to ${corrected}"
+ py_path="$corrected"
+ else
+ warn "Could not auto-detect the correct Python. Edit OPENVIKING_PYTHON in the env file manually."
+ fi
+ fi
+
+ lines+=("export OPENVIKING_PYTHON='$(shell_single_quote "${py_path}")'")
+ fi
+
+ if [[ ${#lines[@]} -eq 0 ]]; then
+ return 0
+ fi
+
+ mkdir -p "${OPENCLAW_DIR}"
+ printf "%s\n" "${lines[@]}" > "${OPENCLAW_DIR}/openviking.env"
+ info "$(tr "Environment file generated: ${OPENCLAW_DIR}/openviking.env" "已生成环境文件: ${OPENCLAW_DIR}/openviking.env")"
+}
+
+wrap_command() {
+ local cmd="$1"
+ local env_file="${OPENCLAW_DIR}/openviking.env"
+ if [[ -f "${env_file}" ]]; then
+ printf "source '%s' && %s" "$(shell_single_quote "${env_file}")" "${cmd}"
+ else
+ printf "%s" "${cmd}"
+ fi
+}
main() {
echo ""
- bold "$(tr "🦣 OpenClaw + OpenViking Installer" "🦣 OpenClaw + OpenViking 一键安装")"
+ bold "OpenClaw + OpenViking Installer"
echo ""
detect_os
+ ensure_plugin_only_operation_args
select_workdir
- info "$(tr "Target: ${OPENCLAW_DIR}" "目标实例: ${OPENCLAW_DIR}")"
+ info "Target: ${OPENCLAW_DIR}"
+ info "Repository: ${REPO}"
+ info "Plugin version: ${PLUGIN_VERSION}"
+ [[ -n "$OPENVIKING_VERSION" ]] && info "OpenViking version: ${OPENVIKING_VERSION}"
+
+ if [[ "$ROLLBACK_LAST_UPGRADE" == "1" ]]; then
+ info "Mode: rollback last plugin upgrade"
+ if [[ "${PLUGIN_VERSION}" != "main" ]]; then
+ warn "--plugin-version is ignored in --rollback mode."
+ fi
+ rollback_last_upgrade_operation
+ return 0
+ fi
+ validate_requested_plugin_version
- select_mode
- info "$(tr "Mode: ${SELECTED_MODE}" "模式: ${SELECTED_MODE}")"
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ SELECTED_MODE="local"
+ info "Mode: plugin upgrade only (backup old plugin, clean only OpenViking plugin config, keep ov.conf)"
+ else
+ select_mode
+ fi
+ info "Mode: ${SELECTED_MODE}"
- if [[ "$SELECTED_MODE" == "local" ]]; then
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ install_openclaw
+ resolve_plugin_config
+ check_openclaw_compatibility
+ prepare_strong_plugin_upgrade
+ elif [[ "$SELECTED_MODE" == "local" ]]; then
validate_environment
install_openclaw
+ # Resolve plugin config after OpenClaw is available (for version detection)
+ resolve_plugin_config
+ check_openclaw_compatibility
+ check_requested_openviking_compatibility
install_openviking
configure_openviking_conf
else
install_openclaw
+ resolve_plugin_config
+ check_openclaw_compatibility
collect_remote_config
fi
- download_plugin
- configure_openclaw_plugin
+ deploy_plugin_from_remote
+ local install_state_operation="install"
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ configure_openclaw_plugin "0" "1" "${UPGRADE_CLAIM_SLOT}"
+ install_state_operation="upgrade"
+ else
+ configure_openclaw_plugin "0" "0" "1"
+ fi
- if [[ "$SELECTED_MODE" == "local" ]]; then
- write_openviking_env
+ write_install_state_file "${install_state_operation}" "${UPGRADE_AUDIT_FROM_VERSION}"
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ UPGRADE_AUDIT_COMPLETED_AT="$(iso_now)"
+ write_upgrade_audit_file
+ fi
+
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ if [[ "$OPENCLAW_DIR" != "$DEFAULT_OPENCLAW_DIR" && ! -f "${OPENCLAW_DIR}/openviking.env" ]]; then
+ write_openviking_env 0
+ fi
+ elif [[ "$SELECTED_MODE" == "local" ]]; then
+ write_openviking_env 1
+ elif [[ "$OPENCLAW_DIR" != "$DEFAULT_OPENCLAW_DIR" ]]; then
+ write_openviking_env 0
fi
echo ""
- bold "═══════════════════════════════════════════════════════════"
- bold " $(tr "Installation complete!" "安装完成!")"
- bold "═══════════════════════════════════════════════════════════"
+ bold "============================================================"
+ bold " Installation complete!"
+ bold "============================================================"
echo ""
+ if [[ "$UPGRADE_PLUGIN_ONLY" == "1" ]]; then
+ info "Upgrade path recorded: ${UPGRADE_AUDIT_FROM_VERSION} -> ${UPGRADE_AUDIT_TO_VERSION}"
+ info "Rollback config backup: ${UPGRADE_AUDIT_CONFIG_BACKUP_PATH}"
+ local backup_item
+ for backup_item in "${UPGRADE_AUDIT_PLUGIN_BACKUPS[@]}"; do
+ info "Rollback plugin backup: ${backup_item#*|}"
+ done
+ info "Rollback audit file: $(get_upgrade_audit_path)"
+ echo ""
+ fi
if [[ "$SELECTED_MODE" == "local" ]]; then
- info "$(tr "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")"
- echo " 1) openclaw --version"
- echo " 2) openclaw onboard"
- echo " 3) source ${OPENCLAW_DIR}/openviking.env && openclaw gateway"
- echo " 4) openclaw status"
+ info "Run these commands to start OpenClaw + OpenViking:"
+ echo " 1) $(wrap_command "openclaw --version")"
+ echo " 2) $(wrap_command "openclaw onboard")"
+ echo " 3) $(wrap_command "openclaw gateway")"
+ echo " 4) $(wrap_command "openclaw status")"
echo ""
- info "$(tr "You can edit the config freely: ${OPENVIKING_DIR}/ov.conf" "你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf")"
+ info "If source fails (e.g. file missing), run: export OPENVIKING_PYTHON=\"\$(command -v python3)\""
+ info "You can edit the config freely: ${OPENVIKING_DIR}/ov.conf"
else
- info "$(tr "Run these commands to start OpenClaw:" "请按以下命令启动 OpenClaw:")"
- echo " 1) openclaw --version"
- echo " 2) openclaw onboard"
- echo " 3) openclaw gateway"
- echo " 4) openclaw status"
+ info "Run these commands to start OpenClaw:"
+ echo " 1) $(wrap_command "openclaw --version")"
+ echo " 2) $(wrap_command "openclaw onboard")"
+ echo " 3) $(wrap_command "openclaw gateway")"
+ echo " 4) $(wrap_command "openclaw status")"
echo ""
- info "$(tr "Remote server: ${remote_base_url}" "远程服务器: ${remote_base_url}")"
+ info "Remote server: ${remote_base_url}"
fi
echo ""
}
diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.json
index 46c093a55..5dd464750 100644
--- a/examples/openclaw-plugin/package.json
+++ b/examples/openclaw-plugin/package.json
@@ -1,12 +1,15 @@
{
"name": "@openclaw/openviking",
- "version": "2026.2.6-3",
+ "version": "2026.3.25",
"description": "OpenClaw OpenViking-backed long-term memory plugin (install to ~/.openclaw/extensions)",
"type": "module",
"scripts": {
"test": "vitest run",
"test:watch": "vitest"
},
+ "engines": {
+ "openclaw": ">=2026.3.7"
+ },
"dependencies": {
"@sinclair/typebox": "0.34.48"
},
diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.js
index 719595fd2..02924e466 100644
--- a/examples/openclaw-plugin/setup-helper/install.js
+++ b/examples/openclaw-plugin/setup-helper/install.js
@@ -10,11 +10,11 @@
* openclaw-openviking-install
*
* Direct run:
- * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ]
- * [ --openviking-version=V ] [ --repo=PATH ]
+ * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --upgrade-plugin ]
+ * [ --plugin-version=TAG ] [ --openviking-version=V ] [ --repo=PATH ]
*
* Environment variables:
- * REPO, BRANCH, OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING
+ * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING
* OPENVIKING_VERSION Pip install openviking==VERSION (omit for latest)
* OPENVIKING_REPO Repo path: source install (pip -e) + local plugin (default: off)
* NPM_REGISTRY, PIP_INDEX_URL
@@ -23,26 +23,26 @@
*/
import { spawn } from "node:child_process";
-import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { cp, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { existsSync, readdirSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { basename, dirname, join, relative } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
-const REPO = process.env.REPO || "volcengine/OpenViking";
-const BRANCH = process.env.BRANCH || "main";
-const GH_RAW = `https://raw.githubusercontent.com/${REPO}/${BRANCH}`;
+let REPO = process.env.REPO || "volcengine/OpenViking";
+// PLUGIN_VERSION takes precedence over BRANCH (legacy)
+let PLUGIN_VERSION = process.env.PLUGIN_VERSION || process.env.BRANCH || "main";
const NPM_REGISTRY = process.env.NPM_REGISTRY || "https://registry.npmmirror.com";
-const PIP_INDEX_URL = process.env.PIP_INDEX_URL || "https://pypi.tuna.tsinghua.edu.cn/simple";
+const PIP_INDEX_URL = process.env.PIP_INDEX_URL || "https://mirrors.volces.com/pypi/simple/";
const IS_WIN = process.platform === "win32";
const HOME = process.env.HOME || process.env.USERPROFILE || "";
const DEFAULT_OPENCLAW_DIR = join(HOME, ".openclaw");
let OPENCLAW_DIR = DEFAULT_OPENCLAW_DIR;
-let PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "openviking");
+let PLUGIN_DEST = ""; // Will be set after resolving plugin config
const OPENVIKING_DIR = join(HOME, ".openviking");
@@ -51,28 +51,62 @@ const DEFAULT_AGFS_PORT = 1833;
const DEFAULT_VLM_MODEL = "doubao-seed-2-0-pro-260215";
const DEFAULT_EMBED_MODEL = "doubao-embedding-vision-251215";
-const REQUIRED_PLUGIN_FILES = [
- "examples/openclaw-plugin/index.ts",
- "examples/openclaw-plugin/context-engine.ts",
- "examples/openclaw-plugin/config.ts",
- "examples/openclaw-plugin/openclaw.plugin.json",
- "examples/openclaw-plugin/package.json",
- "examples/openclaw-plugin/package-lock.json",
- "examples/openclaw-plugin/.gitignore",
+// Fallback configs for old versions without manifest
+const FALLBACK_LEGACY = {
+ dir: "openclaw-memory-plugin",
+ id: "memory-openviking",
+ kind: "memory",
+ slot: "memory",
+ required: ["index.ts", "config.ts", "openclaw.plugin.json", "package.json"],
+ optional: ["package-lock.json", ".gitignore"],
+};
+
+// Must match examples/openclaw-plugin/install-manifest.json (npm only installs package deps, not these .ts files).
+const FALLBACK_CURRENT = {
+ dir: "openclaw-plugin",
+ id: "openviking",
+ kind: "context-engine",
+ slot: "contextEngine",
+ required: ["index.ts", "config.ts", "package.json"],
+ optional: [
+ "context-engine.ts",
+ "client.ts",
+ "process-manager.ts",
+ "memory-ranking.ts",
+ "text-utils.ts",
+ "tool-call-id.ts",
+ "session-transcript-repair.ts",
+ "openclaw.plugin.json",
+ "tsconfig.json",
+ "package-lock.json",
+ ".gitignore",
+ ],
+};
+
+const PLUGIN_VARIANTS = [
+ { ...FALLBACK_LEGACY, generation: "legacy", slotFallback: "none" },
+ { ...FALLBACK_CURRENT, generation: "current", slotFallback: "legacy" },
];
-const OPTIONAL_PLUGIN_FILES = [
- "examples/openclaw-plugin/client.ts",
- "examples/openclaw-plugin/process-manager.ts",
- "examples/openclaw-plugin/memory-ranking.ts",
- "examples/openclaw-plugin/text-utils.ts",
-];
+// Resolved plugin config (set by resolvePluginConfig)
+let resolvedPluginDir = "";
+let resolvedPluginId = "";
+let resolvedPluginKind = "";
+let resolvedPluginSlot = "";
+let resolvedFilesRequired = [];
+let resolvedFilesOptional = [];
+let resolvedNpmOmitDev = true;
+let resolvedMinOpenclawVersion = "";
+let resolvedMinOpenvikingVersion = "";
+let resolvedPluginReleaseId = "";
let installYes = process.env.OPENVIKING_INSTALL_YES === "1";
let langZh = false;
let openvikingVersion = process.env.OPENVIKING_VERSION || "";
let openvikingRepo = process.env.OPENVIKING_REPO || "";
let workdirExplicit = false;
+let upgradePluginOnly = false;
+let rollbackLastUpgrade = false;
let selectedMode = "local";
let selectedServerPort = DEFAULT_SERVER_PORT;
@@ -80,6 +114,9 @@ let remoteBaseUrl = "http://127.0.0.1:1933";
let remoteApiKey = "";
let remoteAgentId = "";
let openvikingPythonPath = "";
+let upgradeRuntimeConfig = null;
+let installedUpgradeState = null;
+let upgradeAudit = null;
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
@@ -92,6 +129,14 @@ for (let i = 0; i < argv.length; i++) {
langZh = true;
continue;
}
+ if (arg === "--upgrade-plugin" || arg === "--update" || arg === "--upgrade") {
+ upgradePluginOnly = true;
+ continue;
+ }
+ if (arg === "--rollback" || arg === "--rollback-last-upgrade") {
+ rollbackLastUpgrade = true;
+ continue;
+ }
if (arg === "--workdir") {
const workdir = argv[i + 1]?.trim();
if (!workdir) {
@@ -103,38 +148,128 @@ for (let i = 0; i < argv.length; i++) {
i += 1;
continue;
}
+ if (arg.startsWith("--plugin-version=")) {
+ PLUGIN_VERSION = arg.slice("--plugin-version=".length).trim();
+ continue;
+ }
+ if (arg === "--plugin-version") {
+ const version = argv[i + 1]?.trim();
+ if (!version) {
+ console.error("--plugin-version requires a value");
+ process.exit(1);
+ }
+ PLUGIN_VERSION = version;
+ i += 1;
+ continue;
+ }
if (arg.startsWith("--openviking-version=")) {
openvikingVersion = arg.slice("--openviking-version=".length).trim();
continue;
}
+ if (arg === "--openviking-version") {
+ const version = argv[i + 1]?.trim();
+ if (!version) {
+ console.error("--openviking-version requires a value");
+ process.exit(1);
+ }
+ openvikingVersion = version;
+ i += 1;
+ continue;
+ }
if (arg.startsWith("--repo=")) {
openvikingRepo = arg.slice("--repo=".length).trim();
continue;
}
+ if (arg.startsWith("--github-repo=")) {
+ REPO = arg.slice("--github-repo=".length).trim();
+ continue;
+ }
+ if (arg === "--github-repo") {
+ const repo = argv[i + 1]?.trim();
+ if (!repo) {
+ console.error("--github-repo requires a value (e.g. owner/repo)");
+ process.exit(1);
+ }
+ REPO = repo;
+ i += 1;
+ continue;
+ }
if (arg === "-h" || arg === "--help") {
printHelp();
process.exit(0);
}
}
-const OPENVIKING_PIP_SPEC = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";
-
function setOpenClawDir(dir) {
OPENCLAW_DIR = dir;
- PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "openviking");
}
function printHelp() {
- console.log("Usage: node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --openviking-version=V ] [ --repo=PATH ]");
+ console.log("Usage: node install.js [ OPTIONS ]");
+ console.log("");
+ console.log("Options:");
+ console.log(" --github-repo=OWNER/REPO GitHub repository (default: volcengine/OpenViking)");
+ console.log(" --plugin-version=TAG Plugin version (Git tag, e.g. v0.2.9, default: main)");
+ console.log(" --openviking-version=V OpenViking PyPI version (e.g. 0.2.9, default: latest)");
+ console.log(" --workdir PATH OpenClaw config directory (default: ~/.openclaw)");
+ console.log(" --repo=PATH Use local OpenViking repo at PATH (pip -e + local plugin)");
+ console.log(" --update, --upgrade-plugin");
+ console.log(" Upgrade only the plugin to the requested --plugin-version; keep ov.conf and do not change the OpenViking service");
+ console.log(" --rollback, --rollback-last-upgrade");
+ console.log(" Roll back the last plugin upgrade using the saved audit/backup files");
+ console.log(" -y, --yes Non-interactive (use defaults)");
+ console.log(" --zh Chinese prompts");
+ console.log(" -h, --help This help");
console.log("");
- console.log(" -y, --yes Non-interactive (use defaults)");
- console.log(" --zh Chinese prompts");
- console.log(" --workdir OpenClaw config directory (default: ~/.openclaw)");
- console.log(" --openviking-version=VERSION Pip install openviking==VERSION (default: latest)");
- console.log(" --repo=PATH Use OpenViking repo at PATH: pip install -e PATH, plugin from repo (default: off)");
- console.log(" -h, --help This help");
+ console.log("Examples:");
+ console.log(" # Install latest version");
+ console.log(" node install.js");
console.log("");
- console.log("Env: OPENVIKING_REPO, REPO, BRANCH, SKIP_OPENCLAW, SKIP_OPENVIKING, OPENVIKING_VERSION, NPM_REGISTRY, PIP_INDEX_URL");
+ console.log(" # Install from a fork repository");
+ console.log(" node install.js --github-repo=yourname/OpenViking --plugin-version=dev-branch");
+ console.log("");
+ console.log(" # Install specific plugin version");
+ console.log(" node install.js --plugin-version=v0.2.8");
+ console.log("");
+ console.log(" # Upgrade only the plugin files");
+ console.log(" node install.js --update --plugin-version=main");
+ console.log("");
+ console.log(" # Roll back the last plugin upgrade");
+ console.log(" node install.js --rollback");
+ console.log("");
+ console.log("Env: REPO, PLUGIN_VERSION, OPENVIKING_VERSION, SKIP_OPENCLAW, SKIP_OPENVIKING, NPM_REGISTRY, PIP_INDEX_URL");
+}
+
+function formatCliArg(value) {
+ if (!value) {
+ return "";
+ }
+ return /[\s"]/u.test(value) ? JSON.stringify(value) : value;
+}
+
+function getLegacyInstallCommandHint() {
+ const override = process.env.OPENVIKING_INSTALL_LEGACY_HINT?.trim();
+ if (override) {
+ return override;
+ }
+
+ const invokedScript = process.argv[1] ? basename(process.argv[1]) : "";
+ const args = ["--plugin-version", "<legacy-version>"];
+ if (workdirExplicit || OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
+ args.push("--workdir", formatCliArg(OPENCLAW_DIR));
+ }
+ if (REPO !== "volcengine/OpenViking") {
+ args.push("--github-repo", formatCliArg(REPO));
+ }
+ if (langZh) {
+ args.push("--zh");
+ }
+
+ if (invokedScript === "install.js") {
+ return `node install.js ${args.join(" ")}`;
+ }
+
+ return `ov-install ${args.join(" ")}`;
}
function tr(en, zh) {
@@ -235,8 +370,19 @@ function question(prompt, defaultValue = "") {
});
}
+async function resolveAbsoluteCommand(cmd) {
+ if (cmd.startsWith("/") || (IS_WIN && /^[A-Za-z]:[/\\]/.test(cmd))) return cmd;
+ if (IS_WIN) {
+ const r = await runCapture("where", [cmd], { shell: true });
+ return r.out.split(/\r?\n/)[0]?.trim() || cmd;
+ }
+ const r = await runCapture("which", [cmd], { shell: false });
+ return r.out.trim() || cmd;
+}
+
async function checkPython() {
- const py = process.env.OPENVIKING_PYTHON || (IS_WIN ? "python" : "python3");
+ const raw = process.env.OPENVIKING_PYTHON || (IS_WIN ? "python" : "python3");
+ const py = await resolveAbsoluteCommand(raw);
const result = await runCapture(py, ["-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"]);
if (result.code !== 0 || !result.out) {
return {
@@ -390,6 +536,250 @@ async function checkOpenClaw() {
process.exit(1);
}
+// Compare versions: returns true if v1 >= v2
+function versionGte(v1, v2) {
+ const parseVersion = (v) => {
+ const cleaned = v.replace(/^v/, "").replace(/-.*$/, "");
+ const parts = cleaned.split(".").map((p) => Number.parseInt(p, 10) || 0);
+ while (parts.length < 3) parts.push(0);
+ return parts;
+ };
+ const [a1, a2, a3] = parseVersion(v1);
+ const [b1, b2, b3] = parseVersion(v2);
+ if (a1 !== b1) return a1 > b1;
+ if (a2 !== b2) return a2 > b2;
+ return a3 >= b3;
+}
+
+function isSemverLike(value) {
+ return /^v?\d+(\.\d+){1,2}$/.test(value);
+}
+
+function validateRequestedPluginVersion() {
+ if (!isSemverLike(PLUGIN_VERSION)) return;
+ if (versionGte(PLUGIN_VERSION, "v0.2.7") && !versionGte(PLUGIN_VERSION, "v0.2.8")) {
+ err(tr("Plugin version v0.2.7 does not exist.", "插件版本 v0.2.7 不存在。"));
+ process.exit(1);
+ }
+}
+
+if (upgradePluginOnly && rollbackLastUpgrade) {
+ console.error("--update/--upgrade-plugin and --rollback cannot be used together");
+ process.exit(1);
+}
+
+function ensurePluginOnlyOperationArgs() {
+ if ((upgradePluginOnly || rollbackLastUpgrade) && openvikingVersion) {
+ err(
+ tr(
+ "Plugin-only upgrade/rollback does not support --openviking-version. Use --plugin-version to choose the plugin release, and run a full install if you need to change the OpenViking service version.",
+ "仅插件升级或回滚不支持 --openviking-version。请使用 --plugin-version 指定插件版本;如果需要调整 OpenViking 服务版本,请执行完整安装流程。",
+ ),
+ );
+ process.exit(1);
+ }
+}
+
+// Detect OpenClaw version
+async function detectOpenClawVersion() {
+ try {
+ const result = await runCapture("openclaw", ["--version"], { shell: IS_WIN });
+ if (result.code === 0 && result.out) {
+ const match = result.out.match(/\d+\.\d+(\.\d+)?/);
+ if (match) return match[0];
+ }
+ } catch {}
+ return "0.0.0";
+}
+
+// Try to fetch a URL, return response text or null
+async function tryFetch(url, timeout = 15000) {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
+ const response = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeoutId);
+ if (response.ok) {
+ return await response.text();
+ }
+ } catch {}
+ return null;
+}
+
+// Check if a remote file exists
+async function testRemoteFile(url) {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000);
+ const response = await fetch(url, { method: "HEAD", signal: controller.signal });
+ clearTimeout(timeoutId);
+ return response.ok;
+ } catch {}
+ return false;
+}
+
+// Resolve plugin configuration from manifest or fallback
+async function resolvePluginConfig() {
+ const ghRaw = `https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}`;
+
+ info(tr(`Resolving plugin configuration for version: ${PLUGIN_VERSION}`, `正在解析插件配置,版本: ${PLUGIN_VERSION}`));
+
+ let pluginDir = "";
+ let manifestData = null;
+
+ // Try to detect plugin directory and download manifest
+ const manifestCurrent = await tryFetch(`${ghRaw}/examples/openclaw-plugin/install-manifest.json`);
+ if (manifestCurrent) {
+ pluginDir = "openclaw-plugin";
+ try {
+ manifestData = JSON.parse(manifestCurrent);
+ } catch {}
+ info(tr("Found manifest in openclaw-plugin", "在 openclaw-plugin 中找到 manifest"));
+ } else {
+ const manifestLegacy = await tryFetch(`${ghRaw}/examples/openclaw-memory-plugin/install-manifest.json`);
+ if (manifestLegacy) {
+ pluginDir = "openclaw-memory-plugin";
+ try {
+ manifestData = JSON.parse(manifestLegacy);
+ } catch {}
+ info(tr("Found manifest in openclaw-memory-plugin", "在 openclaw-memory-plugin 中找到 manifest"));
+ } else if (await testRemoteFile(`${ghRaw}/examples/openclaw-plugin/index.ts`)) {
+ pluginDir = "openclaw-plugin";
+ info(tr("No manifest found, using fallback for openclaw-plugin", "未找到 manifest,使用 openclaw-plugin 回退配置"));
+ } else if (await testRemoteFile(`${ghRaw}/examples/openclaw-memory-plugin/index.ts`)) {
+ pluginDir = "openclaw-memory-plugin";
+ info(tr("No manifest found, using fallback for openclaw-memory-plugin", "未找到 manifest,使用 openclaw-memory-plugin 回退配置"));
+ } else {
+ err(tr(`Cannot find plugin directory for version: ${PLUGIN_VERSION}`, `无法找到版本 ${PLUGIN_VERSION} 的插件目录`));
+ process.exit(1);
+ }
+ }
+
+ resolvedPluginDir = pluginDir;
+ resolvedPluginReleaseId = "";
+
+ if (manifestData) {
+ resolvedPluginId = manifestData.plugin?.id || "";
+ resolvedPluginKind = manifestData.plugin?.kind || "";
+ resolvedPluginSlot = manifestData.plugin?.slot || "";
+ resolvedMinOpenclawVersion = manifestData.compatibility?.minOpenclawVersion || "";
+ resolvedMinOpenvikingVersion = manifestData.compatibility?.minOpenvikingVersion || "";
+ resolvedPluginReleaseId = manifestData.pluginVersion || manifestData.release?.id || "";
+ resolvedNpmOmitDev = manifestData.npm?.omitDev !== false;
+ resolvedFilesRequired = manifestData.files?.required || [];
+ resolvedFilesOptional = manifestData.files?.optional || [];
+ } else {
+ // No manifest — determine plugin identity by package.json name
+ let fallbackKey = pluginDir === "openclaw-memory-plugin" ? "legacy" : "current";
+ let compatVer = "";
+
+ const pkgJson = await tryFetch(`${ghRaw}/examples/${pluginDir}/package.json`);
+ if (pkgJson) {
+ try {
+ const pkg = JSON.parse(pkgJson);
+ const pkgName = pkg.name || "";
+ resolvedPluginReleaseId = pkg.version || "";
+ if (pkgName && pkgName !== "@openclaw/openviking") {
+ fallbackKey = "legacy";
+ info(tr(`Detected legacy plugin by package name: ${pkgName}`, `通过 package.json 名称检测到旧版插件: ${pkgName}`));
+ } else if (pkgName) {
+ fallbackKey = "current";
+ }
+ compatVer = (pkg.engines?.openclaw || "").replace(/^>=?\s*/, "").trim();
+ if (compatVer) {
+ info(tr(`Read minOpenclawVersion from package.json engines.openclaw: >=${compatVer}`, `从 package.json engines.openclaw 读取到最低版本: >=${compatVer}`));
+ }
+ } catch {}
+ }
+
+ const fallback = fallbackKey === "legacy" ? FALLBACK_LEGACY : FALLBACK_CURRENT;
+ resolvedPluginDir = pluginDir;
+ resolvedPluginId = fallback.id;
+ resolvedPluginKind = fallback.kind;
+ resolvedPluginSlot = fallback.slot;
+ resolvedFilesRequired = fallback.required;
+ resolvedFilesOptional = fallback.optional;
+ resolvedNpmOmitDev = true;
+
+ // If no compatVer from package.json, try main branch manifest
+ if (!compatVer && PLUGIN_VERSION !== "main") {
+ const mainRaw = `https://raw.githubusercontent.com/${REPO}/main`;
+ const mainManifest = await tryFetch(`${mainRaw}/examples/openclaw-plugin/install-manifest.json`);
+ if (mainManifest) {
+ try {
+ const m = JSON.parse(mainManifest);
+ compatVer = m.compatibility?.minOpenclawVersion || "";
+ if (compatVer) {
+ info(tr(`Read minOpenclawVersion from main branch manifest: >=${compatVer}`, `从 main 分支 manifest 读取到最低版本: >=${compatVer}`));
+ }
+ } catch {}
+ }
+ }
+
+ resolvedMinOpenclawVersion = compatVer || "2026.3.7";
+ resolvedMinOpenvikingVersion = "";
+ }
+
+ // Set plugin destination
+ PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", resolvedPluginId);
+
+ info(tr(`Plugin: ${resolvedPluginId} (${resolvedPluginKind})`, `插件: ${resolvedPluginId} (${resolvedPluginKind})`));
+}
+
+// Check OpenClaw version compatibility
+async function checkOpenClawCompatibility() {
+ if (process.env.SKIP_OPENCLAW === "1") {
+ return;
+ }
+
+ const ocVersion = await detectOpenClawVersion();
+ info(tr(`Detected OpenClaw version: ${ocVersion}`, `检测到 OpenClaw 版本: ${ocVersion}`));
+
+ // If no minimum version required, pass
+ if (!resolvedMinOpenclawVersion) {
+ return;
+ }
+
+ // If user explicitly requested an old version, pass
+ if (PLUGIN_VERSION !== "main" && isSemverLike(PLUGIN_VERSION) && !versionGte(PLUGIN_VERSION, "v0.2.8")) {
+ return;
+ }
+
+ // Check compatibility
+ if (!versionGte(ocVersion, resolvedMinOpenclawVersion)) {
+ err(tr(
+ `OpenClaw ${ocVersion} does not support this plugin (requires >= ${resolvedMinOpenclawVersion})`,
+ `OpenClaw ${ocVersion} 不支持此插件(需要 >= ${resolvedMinOpenclawVersion})`
+ ));
+ console.log("");
+ bold(tr("Please choose one of the following options:", "请选择以下方案之一:"));
+ console.log("");
+ console.log(` ${tr("Option 1: Upgrade OpenClaw", "方案 1:升级 OpenClaw")}`);
+ console.log(` npm update -g openclaw --registry ${NPM_REGISTRY}`);
+ console.log("");
+ console.log(` ${tr("Option 2: Install a legacy plugin release compatible with your current OpenClaw version", "方案 2:安装与当前 OpenClaw 版本兼容的旧版插件")}`);
+ console.log(` ${getLegacyInstallCommandHint()}`);
+ console.log("");
+ process.exit(1);
+ }
+}
+
+function checkRequestedOpenVikingCompatibility() {
+ if (!resolvedMinOpenvikingVersion || !openvikingVersion) return;
+ if (versionGte(openvikingVersion, resolvedMinOpenvikingVersion)) return;
+
+ err(tr(
+ `OpenViking ${openvikingVersion} does not support this plugin (requires >= ${resolvedMinOpenvikingVersion})`,
+ `OpenViking ${openvikingVersion} 不支持此插件(需要 >= ${resolvedMinOpenvikingVersion})`,
+ ));
+ console.log("");
+ console.log(tr(
+ "Use a newer OpenViking version, or omit --openviking-version to install the latest release.",
+ "请使用更新版本的 OpenViking,或省略 --openviking-version 以安装最新版本。",
+ ));
+ process.exit(1);
+}
+
async function installOpenViking() {
if (process.env.SKIP_OPENVIKING === "1") {
info(tr("Skipping OpenViking install (SKIP_OPENVIKING=1)", "跳过 OpenViking 安装 (SKIP_OPENVIKING=1)"));
@@ -401,6 +791,12 @@ async function installOpenViking() {
err(tr("Python check failed.", "Python 校验失败"));
process.exit(1);
}
+ if (!python.ok) {
+ warn(tr(
+ `${python.detail}. Will attempt to find a suitable Python for pip install.`,
+ `${python.detail}。将尝试查找合适的 Python 进行 pip 安装。`,
+ ));
+ }
const py = python.cmd;
@@ -413,14 +809,20 @@ async function installOpenViking() {
return;
}
- info(tr("Installing OpenViking from PyPI...", "正在安装 OpenViking (PyPI)..."));
+ // Determine package spec
+ const pkgSpec = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";
+ if (openvikingVersion) {
+ info(tr(`Installing OpenViking ${openvikingVersion} from PyPI...`, `正在安装 OpenViking ${openvikingVersion} (PyPI)...`));
+ } else {
+ info(tr("Installing OpenViking (latest) from PyPI...", "正在安装 OpenViking (最新版) (PyPI)..."));
+ }
info(tr(`Using pip index: ${PIP_INDEX_URL}`, `使用 pip 镜像源: ${PIP_INDEX_URL}`));
- info(`Package: ${OPENVIKING_PIP_SPEC}`);
+ info(`Package: ${pkgSpec}`);
await runCapture(py, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });
const installResult = await runLiveCapture(
py,
- ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ ["-m", "pip", "install", "--progress-bar", "on", pkgSpec, "-i", PIP_INDEX_URL],
{ shell: false },
);
if (installResult.code === 0) {
@@ -440,7 +842,7 @@ async function installOpenViking() {
if (reuseCheck.code === 0) {
await runLiveCapture(
venvPy,
- ["-m", "pip", "install", "--progress-bar", "on", "-U", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ ["-m", "pip", "install", "--progress-bar", "on", "-U", pkgSpec, "-i", PIP_INDEX_URL],
{ shell: false },
);
openvikingPythonPath = venvPy;
@@ -476,7 +878,7 @@ async function installOpenViking() {
await runCapture(venvPy, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });
const venvInstall = await runLiveCapture(
venvPy,
- ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ ["-m", "pip", "install", "--progress-bar", "on", pkgSpec, "-i", PIP_INDEX_URL],
{ shell: false },
);
if (venvInstall.code === 0) {
@@ -493,7 +895,7 @@ async function installOpenViking() {
if (process.env.OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES === "1") {
const systemInstall = await runLiveCapture(
py,
- ["-m", "pip", "install", "--progress-bar", "on", "--break-system-packages", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ ["-m", "pip", "install", "--progress-bar", "on", "--break-system-packages", pkgSpec, "-i", PIP_INDEX_URL],
{ shell: false },
);
if (systemInstall.code === 0) {
@@ -560,7 +962,7 @@ async function configureOvConf() {
},
embedding: {
dense: {
- backend: "volcengine",
+ provider: "volcengine",
api_key: embeddingApiKey || null,
model: embeddingModel,
api_base: "https://ark.cn-beijing.volces.com/api/v3",
@@ -569,7 +971,7 @@ async function configureOvConf() {
},
},
vlm: {
- backend: "volcengine",
+ provider: "volcengine",
api_key: vlmApiKey || null,
model: vlmModel,
api_base: "https://ark.cn-beijing.volces.com/api/v3",
@@ -583,118 +985,886 @@ async function configureOvConf() {
info(tr(`Config generated: ${configPath}`, `已生成配置: ${configPath}`));
}
-async function downloadPluginFile(relPath, required, index, total) {
- const fileName = relPath.split("/").pop();
- const url = `${GH_RAW}/${relPath}`;
+function getOpenClawConfigPath() {
+ return join(OPENCLAW_DIR, "openclaw.json");
+}
+
+function getOpenClawEnv() {
+ if (OPENCLAW_DIR === DEFAULT_OPENCLAW_DIR) {
+ return { ...process.env };
+ }
+ return { ...process.env, OPENCLAW_STATE_DIR: OPENCLAW_DIR };
+}
+
+async function readJsonFileIfExists(filePath) {
+ if (!existsSync(filePath)) return null;
+ const raw = await readFile(filePath, "utf8");
+ return JSON.parse(raw);
+}
+
+function getInstallStatePathForPlugin(pluginId) {
+ return join(OPENCLAW_DIR, "extensions", pluginId, ".ov-install-state.json");
+}
+
+function getUpgradeAuditDir() {
+ return join(OPENCLAW_DIR, ".openviking-upgrade-backup");
+}
+
+function getUpgradeAuditPath() {
+ return join(getUpgradeAuditDir(), "last-upgrade.json");
+}
+
+function getOpenClawConfigBackupPath() {
+ return join(getUpgradeAuditDir(), "openclaw.json.bak");
+}
+
+function normalizePluginMode(value) {
+ return value === "remote" ? "remote" : "local";
+}
+
+function getPluginVariantById(pluginId) {
+ return PLUGIN_VARIANTS.find((variant) => variant.id === pluginId) || null;
+}
+
+function detectPluginPresence(config, variant) {
+ const plugins = config?.plugins;
+ const reasons = [];
+ if (!plugins) {
+ return { variant, present: false, reasons };
+ }
+
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) {
+ reasons.push("entry");
+ }
+ if (plugins.slots?.[variant.slot] === variant.id) {
+ reasons.push("slot");
+ }
+ if (Array.isArray(plugins.allow) && plugins.allow.includes(variant.id)) {
+ reasons.push("allow");
+ }
+ if (
+ Array.isArray(plugins.load?.paths)
+ && plugins.load.paths.some((item) => typeof item === "string" && (item.includes(variant.id) || item.includes(variant.dir)))
+ ) {
+ reasons.push("loadPath");
+ }
+ if (existsSync(join(OPENCLAW_DIR, "extensions", variant.id))) {
+ reasons.push("dir");
+ }
+
+ return { variant, present: reasons.length > 0, reasons };
+}
+
+async function detectInstalledPluginState() {
+ const configPath = getOpenClawConfigPath();
+ const config = await readJsonFileIfExists(configPath);
+ const detections = [];
+ for (const variant of PLUGIN_VARIANTS) {
+ const detection = detectPluginPresence(config, variant);
+ if (!detection.present) continue;
+ detection.installState = await readJsonFileIfExists(getInstallStatePathForPlugin(variant.id));
+ detections.push(detection);
+ }
+
+ let generation = "none";
+ if (detections.length === 1) {
+ generation = detections[0].variant.generation;
+ } else if (detections.length > 1) {
+ generation = "mixed";
+ }
+
+ return {
+ config,
+ configPath,
+ detections,
+ generation,
+ };
+}
+
+function formatInstalledDetectionLabel(detection) {
+ const requestedRef = detection.installState?.requestedRef;
+ const releaseId = detection.installState?.releaseId;
+ if (requestedRef) return `${detection.variant.id}@${requestedRef}`;
+ if (releaseId) return `${detection.variant.id}#${releaseId}`;
+ return `${detection.variant.id} (${detection.variant.generation}, exact version unknown)`;
+}
+
+function formatInstalledStateLabel(installedState) {
+ if (!installedState?.detections?.length) {
+ return "not-installed";
+ }
+ return installedState.detections.map(formatInstalledDetectionLabel).join(" + ");
+}
+
+function formatTargetVersionLabel() {
+ const base = `${resolvedPluginId || "openviking"}@${PLUGIN_VERSION}`;
+ if (resolvedPluginReleaseId && resolvedPluginReleaseId !== PLUGIN_VERSION) {
+ return `${base} (${resolvedPluginReleaseId})`;
+ }
+ return base;
+}
+
+function extractRuntimeConfigFromPluginEntry(entryConfig) {
+ if (!entryConfig || typeof entryConfig !== "object") return null;
+
+ const mode = normalizePluginMode(entryConfig.mode);
+ const runtime = { mode };
+
+ if (mode === "remote") {
+ if (typeof entryConfig.baseUrl === "string" && entryConfig.baseUrl.trim()) {
+ runtime.baseUrl = entryConfig.baseUrl.trim();
+ }
+ if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) {
+ runtime.apiKey = entryConfig.apiKey;
+ }
+ if (typeof entryConfig.agentId === "string" && entryConfig.agentId.trim()) {
+ runtime.agentId = entryConfig.agentId.trim();
+ }
+ return runtime;
+ }
+
+ if (typeof entryConfig.configPath === "string" && entryConfig.configPath.trim()) {
+ runtime.configPath = entryConfig.configPath.trim();
+ }
+ if (entryConfig.port !== undefined && entryConfig.port !== null && `${entryConfig.port}`.trim()) {
+ const parsedPort = Number.parseInt(String(entryConfig.port), 10);
+ if (Number.isFinite(parsedPort) && parsedPort > 0) {
+ runtime.port = parsedPort;
+ }
+ }
+ return runtime;
+}
+
+async function readPortFromOvConf(configPath) {
+ const filePath = configPath || join(OPENVIKING_DIR, "ov.conf");
+ if (!existsSync(filePath)) return null;
+ try {
+ const ovConf = await readJsonFileIfExists(filePath);
+ const parsedPort = Number.parseInt(String(ovConf?.server?.port ?? ""), 10);
+ return Number.isFinite(parsedPort) && parsedPort > 0 ? parsedPort : null;
+ } catch {
+ return null;
+ }
+}
+
+async function backupOpenClawConfig(configPath) {
+ await mkdir(getUpgradeAuditDir(), { recursive: true });
+ const backupPath = getOpenClawConfigBackupPath();
+ const configText = await readFile(configPath, "utf8");
+ await writeFile(backupPath, configText, "utf8");
+ return backupPath;
+}
+
+async function writeUpgradeAuditFile(data) {
+ await mkdir(getUpgradeAuditDir(), { recursive: true });
+ await writeFile(getUpgradeAuditPath(), `${JSON.stringify(data, null, 2)}\n`, "utf8");
+}
+
+async function writeInstallStateFile({ operation, fromVersion, configBackupPath, pluginBackups }) {
+ const installStatePath = getInstallStatePathForPlugin(resolvedPluginId || "openviking");
+ const state = {
+ pluginId: resolvedPluginId || "openviking",
+ generation: getPluginVariantById(resolvedPluginId || "openviking")?.generation || "unknown",
+ requestedRef: PLUGIN_VERSION,
+ releaseId: resolvedPluginReleaseId || "",
+ operation,
+ fromVersion: fromVersion || "",
+ configBackupPath: configBackupPath || "",
+ pluginBackups: pluginBackups || [],
+ installedAt: new Date().toISOString(),
+ repo: REPO,
+ };
+ await writeFile(installStatePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
+}
+
+async function moveDirWithFallback(sourceDir, destDir) {
+ try {
+ await rename(sourceDir, destDir);
+ } catch {
+ await cp(sourceDir, destDir, { recursive: true, force: true });
+ await rm(sourceDir, { recursive: true, force: true });
+ }
+}
+
+async function rollbackLastUpgradeOperation() {
+ const auditPath = getUpgradeAuditPath();
+ const audit = await readJsonFileIfExists(auditPath);
+ if (!audit) {
+ err(
+ tr(
+ `No rollback audit file found at ${auditPath}.`,
+ `未找到回滚审计文件: ${auditPath}`,
+ ),
+ );
+ process.exit(1);
+ }
+
+ if (audit.rolledBackAt) {
+ warn(
+ tr(
+ `The last recorded upgrade was already rolled back at ${audit.rolledBackAt}.`,
+ `最近一次升级已在 ${audit.rolledBackAt} 回滚。`,
+ ),
+ );
+ }
+
+ const configBackupPath = audit.configBackupPath || getOpenClawConfigBackupPath();
+ if (!existsSync(configBackupPath)) {
+ err(
+ tr(
+ `Rollback config backup is missing: ${configBackupPath}`,
+ `回滚配置备份缺失: ${configBackupPath}`,
+ ),
+ );
+ process.exit(1);
+ }
+
+ const pluginBackups = Array.isArray(audit.pluginBackups) ? audit.pluginBackups : [];
+ if (pluginBackups.length === 0) {
+ err(tr("Rollback audit file contains no plugin backups.", "回滚审计文件中没有插件备份信息。"));
+ process.exit(1);
+ }
+ for (const pluginBackup of pluginBackups) {
+ if (!pluginBackup?.pluginId || !pluginBackup?.backupDir || !existsSync(pluginBackup.backupDir)) {
+ err(
+ tr(
+ `Rollback plugin backup is missing: ${pluginBackup?.backupDir || "<unknown>"}`,
+ `回滚插件备份缺失: ${pluginBackup?.backupDir || "<unknown>"}`,
+ ),
+ );
+ process.exit(1);
+ }
+ }
+
+ info(tr(`Rolling back last upgrade: ${audit.fromVersion || "unknown"} <- ${audit.toVersion || "unknown"}`, `开始回滚最近一次升级: ${audit.fromVersion || "unknown"} <- ${audit.toVersion || "unknown"}`));
+ await stopOpenClawGatewayForUpgrade();
+
+ const configText = await readFile(configBackupPath, "utf8");
+ await writeFile(getOpenClawConfigPath(), configText, "utf8");
+ info(tr(`Restored openclaw.json from backup: ${configBackupPath}`, `已从备份恢复 openclaw.json: ${configBackupPath}`));
+
+ const extensionsDir = join(OPENCLAW_DIR, "extensions");
+ await mkdir(extensionsDir, { recursive: true });
+ for (const variant of PLUGIN_VARIANTS) {
+ const liveDir = join(extensionsDir, variant.id);
+ if (existsSync(liveDir)) {
+ await rm(liveDir, { recursive: true, force: true });
+ }
+ }
+
+ for (const pluginBackup of pluginBackups) {
+ if (!pluginBackup?.pluginId || !pluginBackup?.backupDir) continue;
+ if (!existsSync(pluginBackup.backupDir)) {
+ err(
+ tr(
+ `Rollback plugin backup is missing: ${pluginBackup.backupDir}`,
+ `回滚插件备份缺失: ${pluginBackup.backupDir}`,
+ ),
+ );
+ process.exit(1);
+ }
+ const destDir = join(extensionsDir, pluginBackup.pluginId);
+ await moveDirWithFallback(pluginBackup.backupDir, destDir);
+ info(tr(`Restored plugin directory: ${destDir}`, `已恢复插件目录: ${destDir}`));
+ }
+
+ audit.rolledBackAt = new Date().toISOString();
+ audit.rollbackConfigPath = configBackupPath;
+ await writeUpgradeAuditFile(audit);
+
+ console.log("");
+ bold(tr("Rollback complete!", "回滚完成!"));
+ console.log("");
+ info(tr(`Rollback audit file: ${auditPath}`, `回滚审计文件: ${auditPath}`));
+ info(tr("Run `openclaw gateway` and `openclaw status` to verify the restored plugin state.", "请运行 `openclaw gateway` 和 `openclaw status` 验证恢复后的插件状态。"));
+}
+
+async function prepareUpgradeRuntimeConfig(installedState) {
+ const plugins = installedState.config?.plugins ?? {};
+ const candidateOrder = installedState.detections
+ .map((item) => item.variant)
+ .sort((left, right) => (right.generation === "current" ? 1 : 0) - (left.generation === "current" ? 1 : 0));
+
+ let runtime = null;
+ for (const variant of candidateOrder) {
+ const entryConfig = extractRuntimeConfigFromPluginEntry(plugins.entries?.[variant.id]?.config);
+ if (entryConfig) {
+ runtime = entryConfig;
+ break;
+ }
+ }
+
+ if (!runtime) {
+ runtime = { mode: "local" };
+ }
+
+ if (runtime.mode === "remote") {
+ runtime.baseUrl = runtime.baseUrl || remoteBaseUrl;
+ return runtime;
+ }
+
+ runtime.configPath = runtime.configPath || join(OPENVIKING_DIR, "ov.conf");
+ runtime.port = runtime.port || await readPortFromOvConf(runtime.configPath) || DEFAULT_SERVER_PORT;
+ return runtime;
+}
+
+function removePluginConfig(config, variant) {
+ const plugins = config?.plugins;
+ if (!plugins) return false;
+
+ let changed = false;
+
+ if (Array.isArray(plugins.allow)) {
+ const nextAllow = plugins.allow.filter((item) => item !== variant.id);
+ changed = changed || nextAllow.length !== plugins.allow.length;
+ plugins.allow = nextAllow;
+ }
+
+ if (Array.isArray(plugins.load?.paths)) {
+ const nextPaths = plugins.load.paths.filter(
+ (item) => typeof item !== "string" || (!item.includes(variant.id) && !item.includes(variant.dir)),
+ );
+ changed = changed || nextPaths.length !== plugins.load.paths.length;
+ plugins.load.paths = nextPaths;
+ }
+
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) {
+ delete plugins.entries[variant.id];
+ changed = true;
+ }
+
+ if (plugins.slots?.[variant.slot] === variant.id) {
+ plugins.slots[variant.slot] = variant.slotFallback;
+ changed = true;
+ }
+
+ return changed;
+}
+
+async function prunePreviousUpgradeBackups(disabledDir, variant, keepDir) {
+ if (!existsSync(disabledDir)) return;
+
+ const prefix = `${variant.id}-upgrade-backup-`;
+ const keepName = keepDir ? keepDir.split(/[\\/]/).pop() : "";
+ const entries = readdirSync(disabledDir, { withFileTypes: true });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (!entry.name.startsWith(prefix)) continue;
+ if (keepName && entry.name === keepName) continue;
+ await rm(join(disabledDir, entry.name), { recursive: true, force: true });
+ }
+}
+
+async function backupPluginDirectory(variant) {
+ const pluginDir = join(OPENCLAW_DIR, "extensions", variant.id);
+ if (!existsSync(pluginDir)) return null;
+
+ const disabledDir = join(OPENCLAW_DIR, "disabled-extensions");
+ const backupDir = join(disabledDir, `${variant.id}-upgrade-backup-${Date.now()}`);
+ await mkdir(disabledDir, { recursive: true });
+ try {
+ await rename(pluginDir, backupDir);
+ } catch {
+ await cp(pluginDir, backupDir, { recursive: true, force: true });
+ await rm(pluginDir, { recursive: true, force: true });
+ }
+ info(tr(`Backed up plugin directory: ${backupDir}`, `已备份插件目录: ${backupDir}`));
+ await prunePreviousUpgradeBackups(disabledDir, variant, backupDir);
+ return backupDir;
+}
+
+async function stopOpenClawGatewayForUpgrade() {
+ const result = await runCapture("openclaw", ["gateway", "stop"], {
+ env: getOpenClawEnv(),
+ shell: IS_WIN,
+ });
+ if (result.code === 0) {
+ info(tr("Stopped OpenClaw gateway before plugin upgrade", "升级插件前已停止 OpenClaw gateway"));
+ } else {
+ warn(tr("OpenClaw gateway may not be running; continuing", "OpenClaw gateway 可能未在运行,继续执行"));
+ }
+}
+
+function shouldClaimTargetSlot(installedState) {
+ const currentOwner = installedState.config?.plugins?.slots?.[resolvedPluginSlot];
+ if (!currentOwner || currentOwner === "none" || currentOwner === "legacy" || currentOwner === resolvedPluginId) {
+ return true;
+ }
+ const currentOwnerVariant = getPluginVariantById(currentOwner);
+ if (currentOwnerVariant && installedState.detections.some((item) => item.variant.id === currentOwnerVariant.id)) {
+ return true;
+ }
+ return false;
+}
+
+async function cleanupInstalledPluginConfig(installedState) {
+ if (!installedState.config || !installedState.config.plugins) {
+ warn(tr("openclaw.json has no plugins section; skipped targeted plugin cleanup", "openclaw.json 中没有 plugins 配置,已跳过定向插件清理"));
+ return;
+ }
+
+ const nextConfig = structuredClone(installedState.config);
+ let changed = false;
+ for (const detection of installedState.detections) {
+ changed = removePluginConfig(nextConfig, detection.variant) || changed;
+ }
+
+ if (!changed) {
+ info(tr("No OpenViking plugin config changes were required", "无需修改 OpenViking 插件配置"));
+ return;
+ }
+
+ await writeFile(installedState.configPath, `${JSON.stringify(nextConfig, null, 2)}\n`, "utf8");
+ info(tr("Cleaned existing OpenViking plugin config only", "已仅清理 OpenViking 自身插件配置"));
+}
+
+async function prepareStrongPluginUpgrade() {
+ const installedState = await detectInstalledPluginState();
+ if (installedState.generation === "none") {
+ err(
+ tr(
+ "Plugin upgrade mode requires an existing OpenViking plugin entry in openclaw.json.",
+ "插件升级模式要求 openclaw.json 中已经存在 OpenViking 插件记录。",
+ ),
+ );
+ process.exit(1);
+ }
+
+ installedUpgradeState = installedState;
+ upgradeRuntimeConfig = await prepareUpgradeRuntimeConfig(installedState);
+ const fromVersion = formatInstalledStateLabel(installedState);
+ const toVersion = formatTargetVersionLabel();
+ selectedMode = upgradeRuntimeConfig.mode;
+ info(
+ tr(
+ `Detected installed OpenViking plugin state: ${installedState.generation}`,
+ `检测到已安装 OpenViking 插件状态: ${installedState.generation}`,
+ ),
+ );
+ if (upgradeRuntimeConfig.mode === "remote") {
+ remoteBaseUrl = upgradeRuntimeConfig.baseUrl || remoteBaseUrl;
+ remoteApiKey = upgradeRuntimeConfig.apiKey || "";
+ remoteAgentId = upgradeRuntimeConfig.agentId || "";
+ } else {
+ selectedServerPort = upgradeRuntimeConfig.port || DEFAULT_SERVER_PORT;
+ }
+ info(tr(`Upgrade runtime mode: ${selectedMode}`, `升级运行模式: ${selectedMode}`));
+
+ info(tr(`Upgrade path: ${fromVersion} -> ${toVersion}`, `升级路径: ${fromVersion} -> ${toVersion}`));
+
+ await stopOpenClawGatewayForUpgrade();
+ const configBackupPath = await backupOpenClawConfig(installedState.configPath);
+ info(tr(`Backed up openclaw.json: ${configBackupPath}`, `已备份 openclaw.json: ${configBackupPath}`));
+ const pluginBackups = [];
+ for (const detection of installedState.detections) {
+ const backupDir = await backupPluginDirectory(detection.variant);
+ if (backupDir) {
+ pluginBackups.push({ pluginId: detection.variant.id, backupDir });
+ }
+ }
+ upgradeAudit = {
+ operation: "upgrade",
+ createdAt: new Date().toISOString(),
+ fromVersion,
+ toVersion,
+ configBackupPath,
+ pluginBackups,
+ runtimeMode: selectedMode,
+ };
+ await writeUpgradeAuditFile(upgradeAudit);
+ await cleanupInstalledPluginConfig(installedState);
+
+ info(
+ tr(
+ "Upgrade will keep the existing OpenViking runtime file and re-apply only the minimum plugin runtime settings.",
+ "升级将保留现有 OpenViking 运行时文件,并只回填最小插件运行配置。",
+ ),
+ );
+ info(tr(`Upgrade audit file: ${getUpgradeAuditPath()}`, `升级审计文件: ${getUpgradeAuditPath()}`));
+}
+
+async function downloadPluginFile(destDir, fileName, url, required, index, total) {
const maxRetries = 3;
+ const destPath = join(destDir, fileName);
process.stdout.write(` [${index}/${total}] ${fileName} `);
+ let lastStatus = 0;
+ let saw404 = false;
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url);
+ lastStatus = response.status;
if (response.ok) {
const buffer = Buffer.from(await response.arrayBuffer());
- await writeFile(join(PLUGIN_DEST, fileName), buffer);
- console.log("✓");
- return;
+ if (buffer.length === 0) {
+ lastStatus = 0;
+ } else {
+ await mkdir(dirname(destPath), { recursive: true });
+ await writeFile(destPath, buffer);
+ console.log(" OK");
+ return;
+ }
+ } else if (!required && response.status === 404) {
+ saw404 = true;
+ break;
}
- if (!required && response.status === 404) {
- console.log(tr("(not present in target branch, skipped)", "(目标分支不存在,已跳过)"));
- return;
- }
- } catch {}
+ } catch {
+ lastStatus = 0;
+ }
if (attempt < maxRetries) {
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
- if (fileName === ".gitignore") {
- console.log(tr("(retries failed, using minimal .gitignore)", "(重试失败,使用最小 .gitignore)"));
- await writeFile(join(PLUGIN_DEST, fileName), "node_modules/\n", "utf8");
+ if (saw404 || lastStatus === 404) {
+ if (fileName === ".gitignore") {
+ await mkdir(dirname(destPath), { recursive: true });
+ await writeFile(destPath, "node_modules/\n", "utf8");
+ console.log(" OK");
+ return;
+ }
+ console.log(tr(" skip", " 跳过"));
return;
}
+ if (!required) {
+ console.log("");
+ err(
+ tr(
+ `Optional file failed after ${maxRetries} retries (HTTP ${lastStatus || "network"}): ${url}`,
+ `可选文件已重试 ${maxRetries} 次仍失败(HTTP ${lastStatus || "网络错误"}): ${url}`,
+ ),
+ );
+ process.exit(1);
+ }
+
console.log("");
- err(tr(`Download failed: ${url}`, `下载失败: ${url}`));
+ err(tr(`Download failed after ${maxRetries} retries: ${url}`, `下载失败(已重试 ${maxRetries} 次): ${url}`));
process.exit(1);
}
-async function downloadPlugin() {
- await mkdir(PLUGIN_DEST, { recursive: true });
- const files = [
- ...REQUIRED_PLUGIN_FILES.map((relPath) => ({ relPath, required: true })),
- ...OPTIONAL_PLUGIN_FILES.map((relPath) => ({ relPath, required: false })),
- ];
+async function downloadPlugin(destDir) {
+ const ghRaw = `https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}`;
+ const pluginDir = resolvedPluginDir;
+ const total = resolvedFilesRequired.length + resolvedFilesOptional.length;
+
+ await mkdir(destDir, { recursive: true });
+
+ info(tr(`Downloading plugin from ${REPO}@${PLUGIN_VERSION} (${total} files)...`, `正在从 ${REPO}@${PLUGIN_VERSION} 下载插件(共 ${total} 个文件)...`));
- info(tr(`Downloading openviking plugin from ${REPO}@${BRANCH}...`, `正在从 ${REPO}@${BRANCH} 下载 openviking 插件...`));
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- await downloadPluginFile(file.relPath, file.required, i + 1, files.length);
+ let i = 0;
+ // Download required files
+ for (const name of resolvedFilesRequired) {
+ if (!name) continue;
+ i++;
+ const url = `${ghRaw}/examples/${pluginDir}/${name}`;
+ await downloadPluginFile(destDir, name, url, true, i, total);
}
+ // Download optional files
+ for (const name of resolvedFilesOptional) {
+ if (!name) continue;
+ i++;
+ const url = `${ghRaw}/examples/${pluginDir}/${name}`;
+ await downloadPluginFile(destDir, name, url, false, i, total);
+ }
+
+ // npm install
info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: PLUGIN_DEST, silent: false });
+ const npmArgs = resolvedNpmOmitDev
+ ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
+ : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
+ await run("npm", npmArgs, { cwd: destDir, silent: false });
info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
}
-async function configureOpenClawPlugin(pluginPath = PLUGIN_DEST) {
- info(tr("Configuring OpenClaw plugin...", "正在配置 OpenClaw 插件..."));
+async function deployLocalPlugin(localPluginDir, destDir) {
+ await rm(destDir, { recursive: true, force: true });
+ await mkdir(destDir, { recursive: true });
+ await cp(localPluginDir, destDir, {
+ recursive: true,
+ force: true,
+ filter: (sourcePath) => {
+ const rel = relative(localPluginDir, sourcePath);
+ if (!rel) return true;
+ const firstSegment = rel.split(/[\\/]/)[0];
+ return firstSegment !== "node_modules" && firstSegment !== ".git";
+ },
+ });
+}
- const ocEnv = { ...process.env };
- if (OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
- ocEnv.OPENCLAW_STATE_DIR = OPENCLAW_DIR;
+async function installPluginDependencies(destDir) {
+ info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
+ const npmArgs = resolvedNpmOmitDev
+ ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
+ : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
+ await run("npm", npmArgs, { cwd: destDir, silent: false });
+ return info(tr(`Plugin prepared: ${destDir}`, `插件已准备: ${destDir}`));
+}
+
+async function createPluginStagingDir() {
+ const pluginId = resolvedPluginId || "openviking";
+ const extensionsDir = join(OPENCLAW_DIR, "extensions");
+ const stagingDir = join(extensionsDir, `.${pluginId}.staging-${process.pid}-${Date.now()}`);
+ await mkdir(extensionsDir, { recursive: true });
+ await rm(stagingDir, { recursive: true, force: true });
+ await mkdir(stagingDir, { recursive: true });
+ return stagingDir;
+}
+
+async function finalizePluginDeployment(stagingDir) {
+ await rm(PLUGIN_DEST, { recursive: true, force: true });
+ try {
+ await rename(stagingDir, PLUGIN_DEST);
+ } catch {
+ await cp(stagingDir, PLUGIN_DEST, { recursive: true, force: true });
+ await rm(stagingDir, { recursive: true, force: true });
+ }
+ return info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
+}
+
+async function deployPluginFromRemote() {
+ const stagingDir = await createPluginStagingDir();
+ try {
+ await downloadPlugin(stagingDir);
+ await finalizePluginDeployment(stagingDir);
+ } catch (error) {
+ await rm(stagingDir, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+/** Same as INSTALL*.md manual cleanup: stale entries block `plugins.slots.*` validation after reinstall. */
+function resolvedPluginSlotFallback() {
+ if (resolvedPluginId === "memory-openviking") return "none";
+ if (resolvedPluginId === "openviking") return "legacy";
+ return "none";
+}
+
+async function scrubStaleOpenClawPluginRegistration() {
+ const configPath = getOpenClawConfigPath();
+ if (!existsSync(configPath)) return;
+ const pluginId = resolvedPluginId;
+ const slot = resolvedPluginSlot;
+ const slotFallback = resolvedPluginSlotFallback();
+ let raw;
+ try {
+ raw = await readFile(configPath, "utf8");
+ } catch {
+ return;
+ }
+ let cfg;
+ try {
+ cfg = JSON.parse(raw);
+ } catch {
+ return;
+ }
+ if (!cfg.plugins) return;
+ const p = cfg.plugins;
+ let changed = false;
+ if (p.entries && Object.prototype.hasOwnProperty.call(p.entries, pluginId)) {
+ delete p.entries[pluginId];
+ changed = true;
+ }
+ if (Array.isArray(p.allow)) {
+ const next = p.allow.filter((id) => id !== pluginId);
+ if (next.length !== p.allow.length) {
+ p.allow = next;
+ changed = true;
+ }
+ }
+ if (p.load && Array.isArray(p.load.paths)) {
+ const norm = (s) => String(s).replace(/\\/g, "/");
+ const extNeedle = `/extensions/${pluginId}`;
+ const next = p.load.paths.filter((path) => {
+ if (typeof path !== "string") return true;
+ return !norm(path).includes(extNeedle);
+ });
+ if (next.length !== p.load.paths.length) {
+ p.load.paths = next;
+ changed = true;
+ }
}
+ if (p.slots && p.slots[slot] === pluginId) {
+ p.slots[slot] = slotFallback;
+ changed = true;
+ }
+ if (!changed) return;
+ const out = JSON.stringify(cfg, null, 2) + "\n";
+ const tmp = `${configPath}.ov-install-tmp.${process.pid}`;
+ await writeFile(tmp, out, "utf8");
+ await rename(tmp, configPath);
+}
+
+async function deployPluginFromLocal(localPluginDir) {
+ const stagingDir = await createPluginStagingDir();
+ try {
+ await deployLocalPlugin(localPluginDir, stagingDir);
+ await installPluginDependencies(stagingDir);
+ await finalizePluginDeployment(stagingDir);
+ } catch (error) {
+ await rm(stagingDir, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+async function configureOpenClawPlugin({
+ preserveExistingConfig = false,
+ runtimeConfig = null,
+ skipGatewayMode = false,
+ claimSlot = true,
+} = {}) {
+ info(tr("Configuring OpenClaw plugin...", "正在配置 OpenClaw 插件..."));
+
+ const pluginId = resolvedPluginId;
+ const pluginSlot = resolvedPluginSlot;
+
+ const ocEnv = getOpenClawEnv();
+
+ const oc = async (args) => {
+ const result = await runCapture("openclaw", args, { env: ocEnv, shell: IS_WIN });
+ if (result.code !== 0) {
+ const detail = result.err || result.out;
+ throw new Error(`openclaw ${args.join(" ")} failed (exit code ${result.code})${detail ? `: ${detail}` : ""}`);
+ }
+ return result;
+ };
- const oc = (args) => runCapture("openclaw", args, { env: ocEnv, shell: IS_WIN });
+ if (!preserveExistingConfig) {
+ await scrubStaleOpenClawPluginRegistration();
+ }
// Enable plugin (files already deployed to extensions dir by deployPlugin)
- const enableResult = await oc(["plugins", "enable", "openviking"]);
- if (enableResult.code !== 0) throw new Error(`openclaw plugins enable failed (exit code ${enableResult.code})`);
- await oc(["config", "set", "plugins.slots.contextEngine", "openviking"]);
+ await oc(["plugins", "enable", pluginId]);
+ if (claimSlot) {
+ await oc(["config", "set", `plugins.slots.${pluginSlot}`, pluginId]);
+ } else {
+ warn(
+ tr(
+ `Skipped claiming plugins.slots.${pluginSlot}; it is currently owned by another plugin.`,
+ `已跳过设置 plugins.slots.${pluginSlot},当前该 slot 由其他插件占用。`,
+ ),
+ );
+ }
- // Set gateway mode
- await oc(["config", "set", "gateway.mode", "local"]);
+ if (preserveExistingConfig) {
+ info(
+ tr(
+ `Preserved existing plugin runtime config for ${pluginId}`,
+ `已保留 ${pluginId} 的现有插件运行时配置`,
+ ),
+ );
+ return;
+ }
+
+ const effectiveRuntimeConfig = runtimeConfig || (
+ selectedMode === "remote"
+ ? { mode: "remote", baseUrl: remoteBaseUrl, apiKey: remoteApiKey, agentId: remoteAgentId }
+ : { mode: "local", configPath: join(OPENVIKING_DIR, "ov.conf"), port: selectedServerPort }
+ );
+
+ if (!skipGatewayMode) {
+ await oc(["config", "set", "gateway.mode", effectiveRuntimeConfig.mode === "remote" ? "remote" : "local"]);
+ }
// Set plugin config for the selected mode
- if (selectedMode === "local") {
- const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
- await oc(["config", "set", "plugins.entries.openviking.config.mode", "local"]);
- await oc(["config", "set", "plugins.entries.openviking.config.configPath", ovConfPath]);
- await oc(["config", "set", "plugins.entries.openviking.config.port", String(selectedServerPort)]);
+ if (effectiveRuntimeConfig.mode === "local") {
+ const ovConfPath = effectiveRuntimeConfig.configPath || join(OPENVIKING_DIR, "ov.conf");
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.mode`, "local"]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.configPath`, ovConfPath]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.port`, String(effectiveRuntimeConfig.port || DEFAULT_SERVER_PORT)]);
} else {
- await oc(["config", "set", "plugins.entries.openviking.config.mode", "remote"]);
- await oc(["config", "set", "plugins.entries.openviking.config.baseUrl", remoteBaseUrl]);
- if (remoteApiKey) {
- await oc(["config", "set", "plugins.entries.openviking.config.apiKey", remoteApiKey]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.mode`, "remote"]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.baseUrl`, effectiveRuntimeConfig.baseUrl || remoteBaseUrl]);
+ if (effectiveRuntimeConfig.apiKey) {
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.apiKey`, effectiveRuntimeConfig.apiKey]);
}
- if (remoteAgentId) {
- await oc(["config", "set", "plugins.entries.openviking.config.agentId", remoteAgentId]);
+ if (effectiveRuntimeConfig.agentId) {
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.agentId`, effectiveRuntimeConfig.agentId]);
}
}
+ // Legacy (memory) plugins need explicit targetUri/autoRecall/autoCapture (new version has defaults in config.ts)
+ if (resolvedPluginKind === "memory") {
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.targetUri`, "viking://user/memories"]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.autoRecall`, "true", "--json"]);
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.autoCapture`, "true", "--json"]);
+ }
+
info(tr("OpenClaw plugin configured", "OpenClaw 插件配置完成"));
}
+async function discoverOpenvikingPython(failedPy) {
+ const candidates = IS_WIN
+ ? ["python3", "python", "py -3"]
+ : ["python3.13", "python3.12", "python3.11", "python3.10", "python3", "python"];
+ for (const candidate of candidates) {
+ if (candidate === failedPy) continue;
+ const resolved = await resolveAbsoluteCommand(candidate);
+ if (!resolved || resolved === candidate || resolved === failedPy) continue;
+ const check = await runCapture(resolved, ["-c", "import openviking"], { shell: false });
+ if (check.code === 0) return resolved;
+ }
+ return "";
+}
+
async function resolvePythonPath() {
if (openvikingPythonPath) return openvikingPythonPath;
const python = await checkPython();
- const py = python.cmd;
- if (!py) return "";
-
- if (IS_WIN) {
- const result = await runCapture("where", [py], { shell: true });
- return result.out.split(/\r?\n/)[0]?.trim() || py;
- }
-
- const result = await runCapture("which", [py], { shell: false });
- return result.out.trim() || py;
+ return python.cmd || "";
}
async function writeOpenvikingEnv({ includePython }) {
const needStateDir = OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR;
- const pythonPath = includePython ? await resolvePythonPath() : "";
+ let pythonPath = "";
+ if (includePython) {
+ pythonPath = await resolvePythonPath();
+ if (!pythonPath) {
+ pythonPath = (process.env.OPENVIKING_PYTHON || "").trim() || (IS_WIN ? "python" : "python3");
+ warn(
+ tr(
+ "Could not resolve absolute Python path; wrote fallback OPENVIKING_PYTHON to openviking.env. Edit that file if OpenViking fails to start.",
+ "未能解析 Python 绝对路径,已在 openviking.env 中写入后备值。若启动失败请手动修改为虚拟环境中的 python 可执行文件路径。",
+ ),
+ );
+ }
+
+ // Verify the resolved Python can actually import openviking
+ if (pythonPath) {
+ const verify = await runCapture(pythonPath, ["-c", "import openviking"], { shell: false });
+ if (verify.code !== 0) {
+ warn(
+ tr(
+ `Resolved Python (${pythonPath}) cannot import openviking. The pip install target may differ from the runtime python3.`,
+ `解析到的 Python(${pythonPath})无法 import openviking。pip 安装目标可能与运行时的 python3 不一致。`,
+ ),
+ );
+ // Try to discover the correct Python via pip show
+ const corrected = await discoverOpenvikingPython(pythonPath);
+ if (corrected) {
+ info(
+ tr(
+ `Auto-corrected OPENVIKING_PYTHON to ${corrected}`,
+ `已自动修正 OPENVIKING_PYTHON 为 ${corrected}`,
+ ),
+ );
+ pythonPath = corrected;
+ } else {
+ warn(
+ tr(
+ `Could not auto-detect the correct Python. Edit OPENVIKING_PYTHON in the env file manually.`,
+ `无法自动检测正确的 Python。请手动修改 env 文件中的 OPENVIKING_PYTHON。`,
+ ),
+ );
+ }
+ }
+ }
+ }
+
+ // Remote mode + default state dir + no python line → nothing to persist
if (!needStateDir && !pythonPath) return null;
await mkdir(OPENCLAW_DIR, { recursive: true });
@@ -741,45 +1911,128 @@ function wrapCommand(command, envFiles) {
return `source '${envFiles.shellPath.replace(/'/g, "'\"'\"'")}' && ${command}`;
}
+function getExistingEnvFiles() {
+ if (IS_WIN) {
+ const batPath = join(OPENCLAW_DIR, "openviking.env.bat");
+ const ps1Path = join(OPENCLAW_DIR, "openviking.env.ps1");
+ if (existsSync(batPath)) {
+ return { shellPath: batPath, powershellPath: existsSync(ps1Path) ? ps1Path : undefined };
+ }
+ if (existsSync(ps1Path)) {
+ return { shellPath: ps1Path, powershellPath: ps1Path };
+ }
+ return null;
+ }
+
+ const envPath = join(OPENCLAW_DIR, "openviking.env");
+ return existsSync(envPath) ? { shellPath: envPath } : null;
+}
+
+function ensureExistingPluginForUpgrade() {
+ if (!existsSync(PLUGIN_DEST)) {
+ err(
+ tr(
+ `Plugin upgrade mode expects an existing plugin at ${PLUGIN_DEST}. Run the full installer first if this is a fresh install.`,
+ `插件升级模式要求 ${PLUGIN_DEST} 处已存在插件安装。若是首次安装,请先运行完整安装流程。`,
+ ),
+ );
+ process.exit(1);
+ }
+}
+
async function main() {
console.log("");
bold(tr("🦣 OpenClaw + OpenViking Installer", "🦣 OpenClaw + OpenViking 一键安装"));
console.log("");
+ ensurePluginOnlyOperationArgs();
await selectWorkdir();
+ if (rollbackLastUpgrade) {
+ info(tr("Mode: rollback last plugin upgrade", "模式: 回滚最近一次插件升级"));
+ if (PLUGIN_VERSION !== "main") {
+ warn("--plugin-version is ignored in --rollback mode.");
+ }
+ await rollbackLastUpgradeOperation();
+ return;
+ }
+ validateRequestedPluginVersion();
info(tr(`Target: ${OPENCLAW_DIR}`, `目标实例: ${OPENCLAW_DIR}`));
+ info(tr(`Repository: ${REPO}`, `仓库: ${REPO}`));
+ info(tr(`Plugin version: ${PLUGIN_VERSION}`, `插件版本: ${PLUGIN_VERSION}`));
+ if (openvikingVersion) {
+ info(tr(`OpenViking version: ${openvikingVersion}`, `OpenViking 版本: ${openvikingVersion}`));
+ }
- await selectMode();
+ if (upgradePluginOnly) {
+ selectedMode = "local";
+ info("Mode: plugin upgrade only (backup old plugin, clean only OpenViking plugin config, keep ov.conf)");
+ } else {
+ await selectMode();
+ }
info(tr(`Mode: ${selectedMode}`, `模式: ${selectedMode}`));
- if (selectedMode === "local") {
+ if (upgradePluginOnly) {
+ await checkOpenClaw();
+ await resolvePluginConfig();
+ await checkOpenClawCompatibility();
+ await prepareStrongPluginUpgrade();
+ } else if (selectedMode === "local") {
await validateEnvironment();
await checkOpenClaw();
+ // Resolve plugin config after OpenClaw is available (for version detection)
+ await resolvePluginConfig();
+ await checkOpenClawCompatibility();
+ checkRequestedOpenVikingCompatibility();
await installOpenViking();
await configureOvConf();
} else {
await checkOpenClaw();
+ await resolvePluginConfig();
+ await checkOpenClawCompatibility();
await collectRemoteConfig();
}
let pluginPath;
- const localPluginDir = openvikingRepo ? join(openvikingRepo, "examples", "openclaw-plugin") : "";
+ const localPluginDir = openvikingRepo ? join(openvikingRepo, "examples", resolvedPluginDir || "openclaw-plugin") : "";
if (openvikingRepo && existsSync(join(localPluginDir, "index.ts"))) {
pluginPath = localPluginDir;
+ PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", resolvedPluginId || "openviking");
info(tr(`Using local plugin from repo: ${pluginPath}`, `使用仓库内插件: ${pluginPath}`));
- if (!existsSync(join(pluginPath, "node_modules"))) {
+ await deployPluginFromLocal(pluginPath);
info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: pluginPath, silent: false });
- }
+ pluginPath = PLUGIN_DEST;
} else {
- await downloadPlugin();
+ await deployPluginFromRemote();
pluginPath = PLUGIN_DEST;
}
- await configureOpenClawPlugin(pluginPath);
- const envFiles = await writeOpenvikingEnv({
- includePython: selectedMode === "local",
+ await configureOpenClawPlugin(
+ upgradePluginOnly
+ ? {
+ runtimeConfig: upgradeRuntimeConfig,
+ skipGatewayMode: true,
+ claimSlot: installedUpgradeState ? shouldClaimTargetSlot(installedUpgradeState) : true,
+ }
+ : { preserveExistingConfig: false },
+ );
+ await writeInstallStateFile({
+ operation: upgradePluginOnly ? "upgrade" : "install",
+ fromVersion: upgradeAudit?.fromVersion || "",
+ configBackupPath: upgradeAudit?.configBackupPath || "",
+ pluginBackups: upgradeAudit?.pluginBackups || [],
});
+ if (upgradeAudit) {
+ upgradeAudit.completedAt = new Date().toISOString();
+ await writeUpgradeAuditFile(upgradeAudit);
+ }
+ let envFiles = getExistingEnvFiles();
+ if (!upgradePluginOnly) {
+ envFiles = await writeOpenvikingEnv({
+ includePython: selectedMode === "local",
+ });
+ } else if (!envFiles && OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
+ envFiles = await writeOpenvikingEnv({ includePython: false });
+ }
console.log("");
bold("═══════════════════════════════════════════════════════════");
@@ -787,6 +2040,16 @@ async function main() {
bold("═══════════════════════════════════════════════════════════");
console.log("");
+ if (upgradeAudit) {
+ info(tr(`Upgrade path recorded: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`, `已记录升级路径: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`));
+ info(tr(`Rollback config backup: ${upgradeAudit.configBackupPath}`, `回滚配置备份: ${upgradeAudit.configBackupPath}`));
+ for (const pluginBackup of upgradeAudit.pluginBackups || []) {
+ info(tr(`Rollback plugin backup: ${pluginBackup.backupDir}`, `回滚插件备份: ${pluginBackup.backupDir}`));
+ }
+ info(tr(`Rollback audit file: ${getUpgradeAuditPath()}`, `回滚审计文件: ${getUpgradeAuditPath()}`));
+ console.log("");
+ }
+
if (selectedMode === "local") {
info(tr("Run these commands to start OpenClaw + OpenViking:", "请按以下命令启动 OpenClaw + OpenViking:"));
} else {
@@ -799,6 +2062,14 @@ async function main() {
console.log("");
if (selectedMode === "local") {
+ if (envFiles?.shellPath && !IS_WIN) {
+ info(
+ tr(
+ 'If source fails, set: export OPENVIKING_PYTHON="$(command -v python3)"',
+ '若 source 失败,可执行: export OPENVIKING_PYTHON="$(command -v python3)"',
+ ),
+ );
+ }
info(tr(`You can edit the config freely: ${OPENVIKING_DIR}/ov.conf`, `你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf`));
} else {
info(tr(`Remote server: ${remoteBaseUrl}`, `远程服务器: ${remoteBaseUrl}`));
diff --git a/examples/openclaw-plugin/setup-helper/package.json b/examples/openclaw-plugin/setup-helper/package.json
index f205d34d5..b3666e8f4 100644
--- a/examples/openclaw-plugin/setup-helper/package.json
+++ b/examples/openclaw-plugin/setup-helper/package.json
@@ -1,6 +1,6 @@
{
"name": "openclaw-openviking-setup-helper",
- "version": "0.2.8",
+ "version": "0.2.10",
"description": "Setup helper for installing OpenViking memory plugin into OpenClaw",
"type": "module",
"bin": {