Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
refactor(openclaw-plugin): remove local mode and rename agentId to agent_prefix (#1783)
LinQiang391dac750e144aa
diff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.mdindex 66207b61b..7ccd777b0 100644--- a/examples/openclaw-plugin/INSTALL-AGENT.md+++ b/examples/openclaw-plugin/INSTALL-AGENT.md@@ -11,7 +11,7 @@ Choose the smallest action that matches the user's intent:| User intent | Command || --- | --- || Fresh install, latest | `npm install -g openclaw-openviking-setup-helper@latest && ov-install` |-| Upgrade plugin + OpenViking to latest | `npm install -g openclaw-openviking-setup-helper@latest && ov-install -y` |+| Upgrade plugin to latest | `npm install -g openclaw-openviking-setup-helper@latest && ov-install -y` || Install or upgrade a specific release | `npm install -g openclaw-openviking-setup-helper@latest && ov-install -y --version 0.2.9` || Upgrade only the plugin | `ov-install --update` || Show installed versions | `ov-install --current-version` |@@ -37,14 +37,12 @@ ls -d ~/.openclaw* 2>/dev/nullVerify:```bash-python3 --versionnode -vopenclaw --version```Requirements:-- Python >= 3.10- Node.js >= 22- OpenClaw >= 2026.3.7@@ -66,7 +64,6 @@ This reports:- installed plugin release- requested plugin ref-- installed OpenViking version- installation time## Standard Workflows@@ -83,12 +80,11 @@ ov-installNotes:- `ov-install` is interactive on first install.-- In local mode, it generates `~/.openviking/ov.conf` and `~/.openclaw/openviking.env`.-- In remote mode, it stores remote connection settings in `plugins.entries.openviking.config`.+- It stores remote connection settings in `plugins.entries.openviking.config`.### Latest Upgrade-Use when the user wants both the plugin and OpenViking runtime upgraded:+Use when the user wants the plugin upgraded:```bashnpm install -g openclaw-openviking-setup-helper@latest@@ -98,7 +94,6 @@ ov-install -yCurrent behavior:- plugin version defaults to the latest repo tag-- OpenViking runtime is upgraded through pip during install- `-y` runs the non-interactive path; verify the resulting plugin config after upgrade if the target instance has custom settings### Release-Pinned Install or Upgrade@@ -110,21 +105,16 @@ npm install -g openclaw-openviking-setup-helper@latestov-install -y --version 0.2.9```-This is shorthand for:--- plugin version `v0.2.9`-- OpenViking version `0.2.9`+This sets the plugin version to `v0.2.9`.### Plugin-Only Upgrade-Use only when the user explicitly wants to keep the current OpenViking runtime version unchanged:+Use only when the user explicitly wants to upgrade just the plugin:```bashov-install --update```-Do not combine `--update` with `--version` or `--openviking-version`.-### Legacy Plugin CleanupIf the machine previously used `memory-openviking`, run the bundled cleanup script from this repository:@@ -169,7 +159,7 @@ Look for:openviking: registered context-engine```-OpenViking service log, default local path:+OpenViking service log, default path:```bashcat ~/.openviking/data/log/openviking.log@@ -185,15 +175,7 @@ python examples/openclaw-plugin/health_check_tools/ov-healthcheck.pyThis injects a real conversation through Gateway and verifies from the OpenViking side that the session was captured, committed, archived, and had memories extracted. See [health_check_tools/HEALTHCHECK.md](./health_check_tools/HEALTHCHECK.md) for full details.-### Start commands--Local mode:--```bash-source ~/.openclaw/openviking.env && openclaw gateway restart-```--Remote mode:+### Start command```bashopenclaw gateway restart@@ -201,31 +183,6 @@ openclaw gateway restart## Plugin Config Reference-### Local Mode--Check the whole config first:--```bash-openclaw config get plugins.entries.openviking.config-```--Core OpenClaw plugin fields:--- `mode=local`-- `configPath`-- `port`-- `agentId`--Service-side model configuration is not stored in the OpenClaw plugin config. It lives in `~/.openviking/ov.conf`, especially:--- `vlm.api_key`-- `vlm.model`-- `embedding.dense.api_key`-- `embedding.dense.model`-- `server.port`--### Remote Mode-Check the whole config first:```bash@@ -234,10 +191,9 @@ openclaw config get plugins.entries.openviking.configCore OpenClaw plugin fields:-- `mode=remote`- `baseUrl`- `apiKey`-- `agentId`+- `agent_prefix`## Uninstall@@ -246,9 +202,3 @@ Plugin only:```bashbash examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh```--Plugin + local OpenViking runtime:--```bash-python3 -m pip uninstall openviking -y && rm -rf ~/.openviking-```diff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.mdindex 2dd59bc18..92c7328be 100644--- a/examples/openclaw-plugin/INSTALL-ZH.md+++ b/examples/openclaw-plugin/INSTALL-ZH.md@@ -8,14 +8,14 @@| 组件 | 版本要求 || --- | --- |-| Python | >= 3.10 || Node.js | >= 22 || OpenClaw | >= 2026.3.7 |+插件以远程模式连接到已有的 OpenViking 服务。安装前请确保已有可访问的 OpenViking HTTP 服务。+快速检查:```bash-python3 --versionnode -vopenclaw --version```@@ -44,11 +44,11 @@ openclaw plugins install clawhub:@openclaw/openvikingopenclaw openviking setup```-向导会检测 Python 环境、验证 OpenViking 包是否可用,并将配置写入 `$OPENCLAW_STATE_DIR/openclaw.json`(默认:`~/.openclaw/openclaw.json`)。+向导会提示你填写远程 OpenViking 服务地址和可选的 API Key,并将配置写入 `$OPENCLAW_STATE_DIR/openclaw.json`(默认:`~/.openclaw/openclaw.json`)。## 通过 ov-install 安装(替代方案)-`ov-install` 一键完成 Python/OpenViking 安装和插件部署。macOS、Linux、Windows 的流程相同。+`ov-install` 一键完成插件部署。macOS、Linux、Windows 的流程相同。```bashnpm install -g openclaw-openviking-setup-helper@@ -62,7 +62,7 @@ ov-install --workdir ~/.openclaw-second## 升级-要把 OpenViking 和插件一起升级到最新版本,执行:+要把插件升级到最新版本,执行:```bashnpm install -g openclaw-openviking-setup-helper@latest && ov-install -y@@ -81,12 +81,11 @@ ov-install -y --version 0.2.9| 参数 | 含义 || --- | --- || `--workdir PATH` | 指定 OpenClaw 数据目录 |-| `--version VER` | 同时指定插件版本和 OpenViking 版本,例如 `0.2.9` 会对应插件 `v0.2.9` |-| `--current-version` | 查看当前已安装的插件版本和 OpenViking 版本 |+| `--version VER` | 指定插件版本,例如 `0.2.9` 会对应插件 `v0.2.9` |+| `--current-version` | 查看当前已安装的插件版本 || `--plugin-version REF` | 指定插件版本,支持 tag、分支或 commit |-| `--openviking-version VER` | 指定 PyPI 上的 OpenViking 版本 || `--github-repo owner/repo` | 指定插件来源仓库,默认 `volcengine/OpenViking` |-| `--update` | 只升级插件,不升级 OpenViking 服务版本 |+| `--update` | 只升级插件 || `-y` | 非交互模式,使用默认配置 |## OpenClaw 插件参数说明@@ -99,51 +98,22 @@ ov-install -y --version 0.2.9openclaw config get plugins.entries.openviking.config```-### Local 模式+### 配置参数-适用于由 OpenClaw 插件在本机拉起 OpenViking 服务的场景。+插件连接到已有的远端 OpenViking 服务。| 参数 | 默认值 | 含义 || --- | --- | --- |-| `mode` | `local` | `local` 表示由插件拉起本机 OpenViking;`remote` 表示连接已有远端 OpenViking 服务 |-| `agentId` | `default` | 当前 OpenClaw 实例在 OpenViking 侧使用的标识 |-| `configPath` | `~/.openviking/ov.conf` | 本机 OpenViking 配置文件路径 |-| `port` | `1933` | 本机 OpenViking HTTP 端口 |--`local` 模式下,VLM、Embedding、API Key 等服务端配置写在 `~/.openviking/ov.conf`,不写在 OpenClaw 插件参数里。常见项包括:--| 配置项 | 含义 |-| --- | --- |-| `vlm.api_key` / `vlm.model` / `vlm.api_base` | 记忆抽取使用的 VLM 模型配置 |-| `embedding.dense.api_key` / `embedding.dense.model` / `embedding.dense.api_base` | 向量化使用的 Embedding 模型配置 |-| `server.port` | OpenViking 服务监听端口 |--常见设置:--```bash-openclaw config set plugins.entries.openviking.config.mode local-openclaw config set plugins.entries.openviking.config.configPath ~/.openviking/ov.conf-openclaw config set plugins.entries.openviking.config.port 1933-```--### Remote 模式--适用于连接已有远端 OpenViking 服务的场景。--| 参数 | 默认值 | 含义 |-| --- | --- | --- |-| `mode` | `remote` | 使用已有远端 OpenViking 服务 || `baseUrl` | `http://127.0.0.1:1933` | 远端 OpenViking 服务地址 || `apiKey` | 空 | 远端 OpenViking API Key;服务端未开启认证时可不填 |-| `agentId` | `default` | 当前 OpenClaw 实例在远端 OpenViking 上的标识 |+| `agent_prefix` | `default` | 当前 OpenClaw 实例在远端 OpenViking 上的 agent 前缀 |常见设置:```bash-openclaw config set plugins.entries.openviking.config.mode remoteopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933openclaw config set plugins.entries.openviking.config.apiKey your-api-key-openclaw config set plugins.entries.openviking.config.agentId your-agent-id+openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix```## 启动@@ -151,13 +121,12 @@ openclaw config set plugins.entries.openviking.config.agentId your-agent-id安装完成后,运行:```bash-source ~/.openclaw/openviking.env && openclaw gateway restart+openclaw gateway restart```Windows PowerShell:```powershell-. "$HOME/.openclaw/openviking.env.ps1"openclaw gateway restart```@@ -205,7 +174,7 @@ python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py## 卸载-只卸载 OpenClaw 插件、保留 OpenViking 运行时:+卸载 OpenClaw 插件:```bashcurl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh@@ -218,9 +187,3 @@ bash uninstall-openviking.shcurl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.shbash uninstall-openviking.sh --workdir ~/.openclaw-second```--如果还要一并删除本机 OpenViking 运行时和数据,再执行:--```bash-python3 -m pip uninstall openviking -y && rm -rf ~/.openviking-```diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.mdindex ddc33552c..26160d638 100644--- a/examples/openclaw-plugin/INSTALL.md+++ b/examples/openclaw-plugin/INSTALL.md@@ -8,14 +8,14 @@ Use [OpenViking](https://github.com/volcengine/OpenViking) as the long-term memo| Component | Required Version || --- | --- |-| Python | >= 3.10 || Node.js | >= 22 || OpenClaw | >= 2026.3.7 |+The plugin connects to an existing OpenViking server. Make sure you have a running OpenViking service accessible via HTTP before proceeding.+Quick check:```bash-python3 --versionnode -vopenclaw --version```@@ -44,11 +44,11 @@ After installation, run the interactive setup wizard:openclaw openviking setup```-The wizard detects your Python environment, verifies the OpenViking package, and writes configuration to `$OPENCLAW_STATE_DIR/openclaw.json` (default: `~/.openclaw/openclaw.json`).+The wizard prompts for your remote OpenViking server URL and optional API key, then writes configuration to `$OPENCLAW_STATE_DIR/openclaw.json` (default: `~/.openclaw/openclaw.json`).## Install via ov-install (Alternative)-The `ov-install` helper automates both the Python/OpenViking installation and plugin deployment:+The `ov-install` helper automates plugin deployment:```bashnpm install -g openclaw-openviking-setup-helper@@ -63,7 +63,7 @@ ov-install --workdir ~/.openclaw-second## Upgrade-To upgrade both OpenViking and the plugin to the latest version:+To upgrade the plugin to the latest version:```bashnpm install -g openclaw-openviking-setup-helper@latest && ov-install -y@@ -82,12 +82,11 @@ ov-install -y --version 0.2.9| Parameter | Meaning || --- | --- || `--workdir PATH` | Target OpenClaw data directory |-| `--version VER` | Set both plugin version and OpenViking version. For example, `0.2.9` maps to plugin `v0.2.9` |-| `--current-version` | Print the currently installed plugin version and OpenViking version |+| `--version VER` | Set plugin version. For example, `0.2.9` maps to plugin `v0.2.9` |+| `--current-version` | Print the currently installed plugin version || `--plugin-version REF` | Set only the plugin version. Supports tag, branch, or commit |-| `--openviking-version VER` | Set only the PyPI OpenViking version || `--github-repo owner/repo` | Use a different GitHub repository for plugin files. Default: `volcengine/OpenViking` |-| `--update` | Upgrade only the plugin, without upgrading the OpenViking runtime |+| `--update` | Upgrade only the plugin || `-y` | Non-interactive mode, use default values |If you need to pin the installer itself:@@ -106,51 +105,22 @@ Get the current full plugin configuration:openclaw config get plugins.entries.openviking.config```-### Local Mode--Use this mode when the OpenClaw plugin should start and manage a local OpenViking process.--| Parameter | Default | Meaning |-| --- | --- | --- |-| `mode` | `local` | Start a local OpenViking process |-| `agentId` | `default` | Logical identifier used by this OpenClaw instance in OpenViking |-| `configPath` | `~/.openviking/ov.conf` | Path to the local OpenViking config file |-| `port` | `1933` | Local OpenViking HTTP port |--In `local` mode, service-side settings such as VLM, embedding, API keys, and storage live in `~/.openviking/ov.conf`, not in the OpenClaw plugin config. The most important `ov.conf` fields are:--| Config Key | Meaning |-| --- | --- |-| `vlm.api_key` / `vlm.model` / `vlm.api_base` | VLM used for memory extraction |-| `embedding.dense.api_key` / `embedding.dense.model` / `embedding.dense.api_base` | Embedding model used for vectorization |-| `server.port` | OpenViking service port |--Common local-mode settings:--```bash-openclaw config set plugins.entries.openviking.config.mode local-openclaw config set plugins.entries.openviking.config.configPath ~/.openviking/ov.conf-openclaw config set plugins.entries.openviking.config.port 1933-```--### Remote Mode+### Configuration Parameters-Use this mode when you already have a running OpenViking server and want OpenClaw to connect to it.+The plugin connects to an existing remote OpenViking server.| Parameter | Default | Meaning || --- | --- | --- |-| `mode` | `remote` | Connect to an existing OpenViking server || `baseUrl` | `http://127.0.0.1:1933` | Remote OpenViking HTTP endpoint || `apiKey` | empty | Optional OpenViking API key |-| `agentId` | `default` | Logical identifier used by this OpenClaw instance on the remote server |+| `agent_prefix` | `default` | Agent prefix used by this OpenClaw instance on the remote server |-Common remote-mode settings:+Common settings:```bash-openclaw config set plugins.entries.openviking.config.mode remoteopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933openclaw config set plugins.entries.openviking.config.apiKey your-api-key-openclaw config set plugins.entries.openviking.config.agentId your-agent-id+openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix```## Start@@ -158,13 +128,12 @@ openclaw config set plugins.entries.openviking.config.agentId your-agent-idAfter installation:```bash-source ~/.openclaw/openviking.env && openclaw gateway restart+openclaw gateway restart```Windows PowerShell:```powershell-. "$HOME/.openclaw/openviking.env.ps1"openclaw gateway restart```@@ -212,7 +181,7 @@ This script injects a real conversation through Gateway and then verifies from t## Uninstall-To remove only the OpenClaw plugin and keep the OpenViking runtime:+To remove the OpenClaw plugin:```bashcurl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh@@ -226,12 +195,6 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examplesbash uninstall-openviking.sh --workdir ~/.openclaw-second```-To also remove the local OpenViking runtime and data:--```bash-python3 -m pip uninstall openviking -y && rm -rf ~/.openviking-```----See also: [INSTALL-ZH.md](./INSTALL-ZH.md)diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex c767a728f..1da870868 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -14,14 +14,14 @@ This document is not an installation guide. It is an implementation-focused desi- OpenClaw still owns the agent runtime, prompt orchestration, and tool execution.- OpenViking owns long-term memory retrieval, session archiving, archive summaries, and memory extraction.-- `examples/openclaw-plugin` is not a narrow “memory lookup” plugin. It is an integration layer that spans the OpenClaw lifecycle.+- `examples/openclaw-plugin` is not a narrow "memory lookup" plugin. It is an integration layer that spans the OpenClaw lifecycle.In the current implementation, the plugin plays four roles at once:- `context-engine`: implements `assemble`, `afterTurn`, and `compact`- hook layer: handles `before_prompt_build`, `session_start`, `session_end`, `agent_end`, and `before_reset`- tool provider: registers memory/archive tools plus OpenViking resource and skill import tools-- runtime manager: starts and monitors an OpenViking subprocess in `local` mode+- runtime manager: connects to and monitors a remote OpenViking service## Overall Architecture@@ -46,7 +46,7 @@ The main rules are:- prefer `sessionKey` when deriving a stable `ovSessionId`- normalize unsafe path characters, or fall back to a stable SHA-256 when needed- resolve `X-OpenViking-Agent` per session, not per process-- when `plugins.entries.openviking.config.agentId` is not `default`, prefix the session agent as `<configAgentId>_<sessionAgent>`+- when `plugins.entries.openviking.config.agent_prefix` is not `default`, prefix the session agent as `<agent_prefix>_<sessionAgent>`- add `X-OpenViking-Account`, `X-OpenViking-User`, and `X-OpenViking-Agent` in the client layerThis matters because the plugin is built to support multi-agent and multi-session OpenClaw usage without mixing memories across sessions.@@ -55,7 +55,7 @@ The recommended remote-mode configuration only needs:- `baseUrl`- `apiKey`-- `agentId`+- `agent_prefix`In this setup:@@ -114,7 +114,7 @@ Session handling is the main axis of this design. In the current implementation- tool output becomes separate `toolResult`- the final message list goes through a tool-use/result pairing repair pass-That means OpenClaw sees “compressed history summary + archive index + active messages”, not an ever-growing raw transcript.+That means OpenClaw sees "compressed history summary + archive index + active messages", not an ever-growing raw transcript.### What `afterTurn()` does@@ -141,7 +141,7 @@ After that, the plugin checks `pending_tokens`. Once the session crosses `commit- it returns updated token estimates, the latest archive id, and summary content- if the summary is too coarse, the model can call `ov_archive_expand` to reopen a specific archive-So `afterTurn()` is closer to “incremental append plus threshold-triggered async commit”, while `compact()` is the explicit “wait for archive and compaction to finish” boundary.+So `afterTurn()` is closer to "incremental append plus threshold-triggered async commit", while `compact()` is the explicit "wait for archive and compaction to finish" boundary.## Tools and Expandability@@ -159,7 +159,7 @@ They serve different roles:- automatic recall covers the default case where the model does not know what to search yet- `memory_recall` gives the model an explicit follow-up search path- `memory_store` is for immediately persisting clearly important information-- `ov_archive_expand` is the “go back to archive detail” escape hatch when summaries are not enough+- `ov_archive_expand` is the "go back to archive detail" escape hatch when summaries are not enough- `ov_import` lets the agent complete explicit import requests without asking the user to remember slash commands- `ov_search` closes the loop after import by letting the user or agent confirm and consume resources and skills@@ -185,34 +185,17 @@ Resource import supports remote URLs, Git URLs, local files, local directories,For HTTP safety, the plugin never sends a direct local filesystem path to the OpenViking server. Local files and directories are first uploaded through `/api/v1/resources/temp_upload`; directories are zipped locally with a pure JavaScript zip implementation before upload.-## Local / Remote Runtime Modes+## Runtime Mode-The current implementation supports two runtime modes. The upper-layer session, memory, and archive model stays the same in both.+The plugin operates exclusively in remote mode as a pure HTTP client:-### Local mode--In `local` mode, the plugin manages the OpenViking subprocess itself:--- resolve Python from `OPENVIKING_PYTHON`, env files, or system defaults-- prepare the port before startup-- kill stale OpenViking processes on the target port-- move to the next free port if another process owns the configured one-- wait for `/health` before marking the service ready-- cache the local client so multiple plugin registrations do not spawn duplicates--That is why this plugin is not only “memory logic”. It is also a local runtime manager.--### Remote mode--In `remote` mode, the plugin behaves as a pure HTTP client:--- no local subprocess is started- `baseUrl` and optional `apiKey` come from plugin config+- no local subprocess is started or managed- session context, memory find/read, commit, and archive expansion behavior stays the same-The main difference between `local` and `remote` is who is responsible for bringing up the OpenViking service, not the higher-level context model.+The OpenViking service must be deployed and running independently before the plugin can connect to it.## Relationship to the Older Design Draft@@ -269,7 +252,7 @@ ov tui| Symptom | More likely cause | First check || --- | --- | --- || `plugins.slots.contextEngine` is not `openviking` | The plugin slot was never set, or another plugin replaced it | `openclaw config get plugins.slots.contextEngine` |-| `local` mode fails to start | Python path, env file, or `ov.conf` is wrong | `source ~/.openclaw/openviking.env && openclaw gateway restart` |+| Cannot connect to OpenViking service | `baseUrl` is wrong or the service is down | Check `baseUrl` in config and test connectivity manually || recall behaves inconsistently across sessions | Routing identity is not what you expected | Enable `logFindRequests`, then inspect `openclaw logs --follow` || long chats stop extracting memory | `pending_tokens` never crosses the threshold, or Phase 2 fails server-side | Check plugin config and `~/.openviking/data/log/openviking.log` || summaries are too coarse for detailed questions | You need archive-level detail, not just summary | Use an ID from `[Archive Index]` with `ov_archive_expand` |diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex 35dd702ed..8184233f2 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -2,7 +2,7 @@使用 [OpenViking](https://github.com/volcengine/OpenViking) 作为 [OpenClaw](https://github.com/openclaw/openclaw) 的长期记忆后端。在 OpenClaw 中,此插件注册为 `openviking` 上下文引擎。-本文档不是安装教程,而是面向集成方和工程师的“当前实现设计说明”。它基于 `examples/openclaw-plugin` 里的现有代码,重点解释这套插件今天实际上如何工作,而不是未来可能的重构方向。+本文档不是安装教程,而是面向集成方和工程师的"当前实现设计说明"。它基于 `examples/openclaw-plugin` 里的现有代码,重点解释这套插件今天实际上如何工作,而不是未来可能的重构方向。## 文档入口@@ -14,14 +14,14 @@- OpenClaw 仍然负责 agent runtime、prompt 编排和工具执行。- OpenViking 负责长期记忆检索、session 归档、archive summary 和记忆抽取。-- `examples/openclaw-plugin` 不是一个单一职责的“记忆查询插件”,而是一组围绕 OpenClaw 生命周期工作的集成层。+- `examples/openclaw-plugin` 不是一个单一职责的"记忆查询插件",而是一组围绕 OpenClaw 生命周期工作的集成层。按当前代码职责看,插件同时扮演四个角色:- `context-engine`:实现 `assemble`、`afterTurn`、`compact`- Hook 层:接管 `before_prompt_build`、`session_start`、`session_end`、`agent_end`、`before_reset`- Tool 提供者:注册 memory/archive 工具,以及 OpenViking resource 和 skill 导入工具-- 运行时管理器:在 `local` 模式下拉起并监控 OpenViking 子进程+- 运行时管理器:连接并监控远程 OpenViking 服务## 总体架构@@ -46,7 +46,7 @@- `sessionKey` 存在时优先用它生成稳定的 `ovSessionId`。- 非安全路径字符会被规整或退化成稳定的 SHA-256。- `X-OpenViking-Agent` 按 session 解析,不按进程写死。-- 若 `plugins.entries.openviking.config.agentId` 不是 `default`,会形成 `<configAgentId>_<sessionAgent>` 的前缀形式。+- 若 `plugins.entries.openviking.config.agent_prefix` 不是 `default`,会形成 `<agent_prefix>_<sessionAgent>` 的前缀形式。- client 层统一补全 `X-OpenViking-Account`、`X-OpenViking-User`、`X-OpenViking-Agent` 这些 header。这样做是为了支持多 agent、多 session 并发时的记忆隔离,避免不同 OpenClaw 会话串用同一套长期上下文。@@ -55,7 +55,7 @@- `baseUrl`- `apiKey`-- `agentId`+- `agent_prefix`其中:@@ -101,7 +101,7 @@-Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装、增量写入、异步提交、阻塞压缩回读”四个动作。+Session 是这套设计的主轴。当前实现里,它覆盖了"历史组装、增量写入、异步提交、阻塞压缩回读"四个动作。### `assemble()` 负责什么@@ -114,7 +114,7 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装- tool output 会被拆成独立的 `toolResult`- 之后再做一轮 `toolCall/toolResult` 配对修复,降低 transcript 结构不稳定的风险-因此,OpenClaw 拿到的是“压缩后的历史摘要 + archive 索引 + 当前活跃消息”,而不是无限增长的原始 transcript。+因此,OpenClaw 拿到的是"压缩后的历史摘要 + archive 索引 + 当前活跃消息",而不是无限增长的原始 transcript。### `afterTurn()` 负责什么@@ -141,7 +141,7 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装- 返回新的 token 估算、latest archive id 和 summary- 如果摘要不够精确,模型可以再调用 `ov_archive_expand` 读取某个 archive 的原始消息-所以 `afterTurn()` 更像“增量写入 + 条件触发异步提交”,而 `compact()` 才是“明确等待压缩与归档完成”的正式边界。+所以 `afterTurn()` 更像"增量写入 + 条件触发异步提交",而 `compact()` 才是"明确等待压缩与归档完成"的正式边界。## 工具层与可展开能力@@ -156,7 +156,7 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装它们各自的作用不同:-- 自动 recall 解决“模型不知道该先查什么”的默认场景。+- 自动 recall 解决"模型不知道该先查什么"的默认场景。- `memory_recall` 给模型一个显式补查入口。- `memory_store` 适合把一段明确的重要信息立刻落入记忆管线。- `ov_archive_expand` 负责在 summary 不够细时回到 archive 级原文。@@ -185,44 +185,27 @@ Resource 导入支持远程 URL、Git URL、本地文件、本地目录和 zip出于 HTTP 安全边界,插件不会把本地文件系统路径直接发送给 OpenViking 服务端。本地文件和目录会先通过 `/api/v1/resources/temp_upload` 上传;目录会先在本地使用纯 JavaScript zip 实现打包后再上传。-## Local / Remote 运行模式+## 运行模式-当前实现支持两种运行方式,但 session、memory、archive 的上层逻辑是一致的。+插件仅以远程模式运行,作为纯 HTTP 客户端:-### Local 模式--`local` 模式下,插件自己管理 OpenViking 子进程:--- 解析 `OPENVIKING_PYTHON`、env 文件或系统默认 Python-- 启动前先做端口准备-- 若目标端口上残留旧 OpenViking,会尝试清理-- 若端口被其他进程占用,会自动寻找下一个空闲端口-- 只有 `/health` 成功后,才把服务视为可用-- 会缓存 local client,避免同一环境里重复拉起多个运行时--这也是为什么插件不仅是“查记忆的逻辑层”,还是一个本地运行时管理器。--### Remote 模式--`remote` 模式下,插件只作为 HTTP 客户端工作:--- 不会启动本地子进程- `baseUrl` 和可选 `apiKey` 由插件配置提供+- 不会启动或管理本地子进程- session context、memory find/read、commit、archive expand 这些行为保持不变-换句话说,`local` 和 `remote` 的差异主要在“谁负责把 OpenViking 服务启动起来”,不在上层的上下文模型本身。+OpenViking 服务需要独立部署并运行,插件才能连接到它。## 与旧设计稿的关系-仓库里还有一份更偏“未来演进方向”的设计稿:`docs/design/openclaw-context-engine-refactor.md`。阅读时需要区分两者的口径:+仓库里还有一份更偏"未来演进方向"的设计稿:`docs/design/openclaw-context-engine-refactor.md`。阅读时需要区分两者的口径:- 本文描述的是当前实现已经落地的行为。-- 旧设计稿讨论的是“进一步把更多主链路迁入 context-engine 生命周期”的目标态。+- 旧设计稿讨论的是"进一步把更多主链路迁入 context-engine 生命周期"的目标态。- 当前版本里,自动 recall 的主入口仍然在 `before_prompt_build`,并没有完全迁到 `assemble()`。- 当前版本里,`afterTurn()` 已经负责增量写入 OpenViking session,但它仍然依赖阈值触发异步 commit。-- 当前版本里,`compact()` 已经走 `commit(wait=true)`,但它的职责仍以“同步提交 + 结果回读”为主,而不是承载一切上层编排。+- 当前版本里,`compact()` 已经走 `commit(wait=true)`,但它的职责仍以"同步提交 + 结果回读"为主,而不是承载一切上层编排。这段区分很重要,否则很容易把未来设计误读成现状。@@ -269,7 +252,7 @@ ov tui| 现象 | 更可能的原因 | 优先检查 || --- | --- | --- || `plugins.slots.contextEngine` 不是 `openviking` | 插件槽位未设置或被其他插件覆盖 | `openclaw config get plugins.slots.contextEngine` |-| `local` 模式启动失败 | Python 路径、env 文件或 `ov.conf` 不对 | `source ~/.openclaw/openviking.env && openclaw gateway restart` |+| 无法连接 OpenViking 服务 | `baseUrl` 配置错误或服务未启动 | 检查 `baseUrl` 配置并手动测试连接 || recall 在不同 session 间不稳定 | 路由身份和预期不一致 | 打开 `logFindRequests`,再看 `openclaw logs --follow` || 长对话后没有持续抽取记忆 | `pending_tokens` 未过阈值,或服务端 Phase 2 失败 | 检查插件配置和 `~/.openviking/data/log/openviking.log` || summary 太粗,不够回答细节问题 | 你要的是 archive 级明细,不是摘要 | 用 `[Archive Index]` 里的 ID 调用 `ov_archive_expand` |diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex 8f966482d..2bfd65668 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -1,5 +1,4 @@import { randomUUID } from "node:crypto";-import type { spawn } from "node:child_process";import { once } from "node:events";import { createWriteStream } from "node:fs";import { mkdtemp, readdir, readFile, rm, stat } from "node:fs/promises";@@ -33,17 +32,6 @@ export type RuntimeIdentity = {userId: string;agentId: string;};-export type LocalClientCacheEntry = {- client: OpenVikingClient;- process: ReturnType<typeof spawn> | null;-};--export type PendingClientEntry = {- promise: Promise<OpenVikingClient>;- resolve: (c: OpenVikingClient) => void;- reject: (err: unknown) => void;-};-export type CommitSessionResult = {session_id: string;/** "accepted" (async), "completed", "failed", or "timeout" (wait mode). */@@ -165,13 +153,6 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}-export const localClientCache = new Map<string, LocalClientCacheEntry>();--// Module-level pending promise map: shared across all plugin registrations so-// that both [gateway] and [plugins] contexts await the same promise and-// don't create duplicate pending promises that never resolve.-export const localClientPendingPromises = new Map<string, PendingClientEntry>();-const MEMORY_URI_PATTERNS = [/^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,/^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.tsindex 06944bd4a..10416eeea 100644--- a/examples/openclaw-plugin/commands/setup.ts+++ b/examples/openclaw-plugin/commands/setup.ts@@ -2,13 +2,12 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";import * as readline from "node:readline";-import { launchProcess, sysEnv, getEnv, parseWindowsEnvBatPythonPath, parsePosixEnvPythonPath } from "../runtime-utils.js";+import { launchProcess, sysEnv, getEnv } from "../runtime-utils.js";const IS_WIN = os.platform() === "win32";+const HOME = os.homedir();const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");-const DEFAULT_CONFIG_PATH = path.join(HOME, ".openviking", "ov.conf");-const DEFAULT_PORT = 1933;const DEFAULT_REMOTE_URL = "http://127.0.0.1:1933";type CommandProgram = {@@ -70,185 +69,6 @@ async function resolveAbsoluteCommand(cmd: string): Promise<string> {return r.out.trim() || cmd;}-async function resolvePythonCmd(): Promise<string> {- const envPython = getEnv("OPENVIKING_PYTHON");- if (envPython) return resolveAbsoluteCommand(envPython);-- const defaultDir = path.join(HOME, ".openclaw");- const searchDirs = OPENCLAW_DIR !== defaultDir- ? [OPENCLAW_DIR, defaultDir]- : [defaultDir];- for (const dir of searchDirs) {- const envFile = IS_WIN- ? path.join(dir, "openviking.env.bat")- : path.join(dir, "openviking.env");- if (fs.existsSync(envFile)) {- try {- const content = fs.readFileSync(envFile, "utf-8");- const parsed = IS_WIN- ? parseWindowsEnvBatPythonPath(content)- : parsePosixEnvPythonPath(content);- if (parsed) return parsed;- } catch { /* ignore */ }- }- }-- const venvPy = IS_WIN- ? path.join(HOME, ".openviking", "venv", "Scripts", "python.exe")- : path.join(HOME, ".openviking", "venv", "bin", "python");- if (fs.existsSync(venvPy)) return venvPy;-- const raw = IS_WIN ? "python" : "python3";- return resolveAbsoluteCommand(raw);-}--async function checkOpenVikingInstalled(): Promise<{ ok: boolean; version: string; pythonPath: string }> {- const pythonCmd = await resolvePythonCmd();- const result = await capture(pythonCmd, ["-c", "import openviking; print(openviking.__version__)"]);- if (result.code === 0 && result.out) {- return { ok: true, version: result.out, pythonPath: pythonCmd };- }-- const venvPy = IS_WIN- ? path.join(HOME, ".openviking", "venv", "Scripts", "python.exe")- : path.join(HOME, ".openviking", "venv", "bin", "python");- const candidates = IS_WIN- ? ["python", "py"]- : [venvPy, "python3.13", "python3.12", "python3.11", "python3.10", "python3"];- const tried = new Set<string>([pythonCmd]);- for (const candidate of candidates) {- const resolved = candidate.startsWith("/") && fs.existsSync(candidate)- ? candidate- : await resolveAbsoluteCommand(candidate);- if (!resolved || tried.has(resolved)) continue;- tried.add(resolved);- const check = await capture(resolved, ["-c", "import openviking; print(openviking.__version__)"]);- if (check.code === 0 && check.out) {- return { ok: true, version: check.out, pythonPath: resolved };- }- }-- return { ok: false, version: "", pythonPath: "" };-}--function writeOpenvikingEnv(pythonPath: string): void {- if (!fs.existsSync(OPENCLAW_DIR)) fs.mkdirSync(OPENCLAW_DIR, { recursive: true });- if (IS_WIN) {- const batSafe = pythonPath.replace(/"/g, '""');- const ps1Safe = pythonPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, '`$');- fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env.bat"), `@echo off\r\nset "OPENVIKING_PYTHON=${batSafe}"\r\n`, "utf-8");- fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env.ps1"), `$env:OPENVIKING_PYTHON = "${ps1Safe}"\n`, "utf-8");- } else {- const shSafe = pythonPath.replace(/'/g, "'\"'\"'");- fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env"), `export OPENVIKING_PYTHON='${shSafe}'\n`, "utf-8");- }-}--type LocalConfigValidationResult = {- ok: boolean;- error: string;- usedPythonValidation: boolean;-};--function getErrorMessage(error: unknown): string {- return String(error instanceof Error ? error.message : error);-}--function summarizeValidationOutput(output: string): string {- const lines = output- .split(/\r?\n/)- .map((line) => line.trim())- .filter(Boolean);- if (!lines.length) return output.trim();- const preferred = lines.find((line) => /^((ValueError|FileNotFoundError|SystemExit|RuntimeError):|Invalid )/.test(line));- return preferred || lines[lines.length - 1];-}--async function validateLocalConfigPath(configPath: string, pythonCmd?: string): Promise<LocalConfigValidationResult> {- if (!fs.existsSync(configPath)) {- return {- ok: false,- error: `Config file not found: ${configPath}`,- usedPythonValidation: false,- };- }-- let raw = "";- try {- raw = fs.readFileSync(configPath, "utf-8");- } catch (error) {- return {- ok: false,- error: `Failed to read config file: ${getErrorMessage(error)}`,- usedPythonValidation: false,- };- }-- try {- const parsed = JSON.parse(raw) as unknown;- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {- return {- ok: false,- error: "Invalid ov.conf: top-level JSON value must be an object",- usedPythonValidation: false,- };- }- } catch (error) {- return {- ok: false,- error: `Invalid ov.conf JSON: ${getErrorMessage(error)}`,- usedPythonValidation: false,- };- }-- if (!pythonCmd) {- return { ok: true, error: "", usedPythonValidation: false };- }-- const validationCode = [- "import sys",- "from openviking.server.config import load_server_config, validate_server_config",- "validate_server_config(load_server_config(sys.argv[1]))",- "print('ok')",- ].join(";");- const result = await capture(pythonCmd, ["-c", validationCode, configPath]);- if (result.code === 0) {- return { ok: true, error: "", usedPythonValidation: true };- }-- const detail = summarizeValidationOutput(result.err || result.out || `exit code ${result.code}`);- return {- ok: false,- error: `ov.conf failed OpenViking validation: ${detail}`,- usedPythonValidation: true,- };-}--function printLocalConfigFixHint(zh: boolean, configPath: string, validationError: string): void {- console.log("");- console.log(` ⚠ ${tr(zh,- validationError,- validationError,- )}`);- console.log(` ${tr(zh,- "OpenViking requires a valid ov.conf before local mode can be saved.",- "OpenViking 本地模式需要有效的 ov.conf,配置向导不会保存无效配置。",- )}`);- console.log(` ${tr(zh,- " Option 1: Run 'openviking init' to generate a default config",- " 方式 1:运行 'openviking init' 生成默认配置",- )}`);- console.log(` ${tr(zh,- " Option 2: Copy from examples/ov.conf.example",- " 方式 2:从 examples/ov.conf.example 复制",- )}`);- console.log(` ${tr(zh,- ` Target path: ${configPath}`,- ` 目标路径: ${configPath}`,- )}`);- console.log("");-}-async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<{ ok: boolean; version: string; error: string }> {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 10_000);@@ -321,21 +141,10 @@ function detectLangZh(options: Record<string, unknown>): boolean {return /^zh/i.test(lang);}-type SetupLocalDeps = {- checkOpenVikingInstalled: typeof checkOpenVikingInstalled;- writeOpenvikingEnv: typeof writeOpenvikingEnv;- checkServiceHealth: typeof checkServiceHealth;- validateLocalConfigPath: typeof validateLocalConfigPath;- writeConfig: typeof writeConfig;-};--const defaultSetupLocalDeps: SetupLocalDeps = {- checkOpenVikingInstalled,- writeOpenvikingEnv,- checkServiceHealth,- validateLocalConfigPath,- writeConfig,-};+function isLegacyLocalMode(existing: Record<string, unknown>): boolean {+ const mode = existing.mode;+ return mode !== "remote";+}// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport function registerSetupCli(api: any): void {@@ -371,17 +180,26 @@ export function registerSetupCli(api: any): void {try {if (existing && !options.reconfigure) {- console.log(tr(zh, "Existing configuration found:", "已找到现有配置:"));- if (existing.mode === "remote") {- console.log(` mode: ${existing.mode}`);- console.log(` baseUrl: ${existing.baseUrl ?? DEFAULT_REMOTE_URL}`);- if (existing.apiKey) console.log(` apiKey: ${maskKey(String(existing.apiKey))}`);- if (existing.agentId) console.log(` agentId: ${existing.agentId}`);- } else {- console.log(` mode: ${existing.mode ?? "local"}`);- console.log(` configPath: ${existing.configPath ?? DEFAULT_CONFIG_PATH}`);- console.log(` port: ${existing.port ?? DEFAULT_PORT}`);+ if (isLegacyLocalMode(existing)) {+ console.log(tr(+ zh,+ "Existing configuration uses local mode, which is no longer supported.",+ "当前配置为本地模式,已不再支持。",+ ));+ console.log(tr(+ zh,+ "Run `openclaw openviking setup --reconfigure` to configure a remote OpenViking server.",+ "请运行 `openclaw openviking setup --reconfigure` 以配置远程 OpenViking 服务。",+ ));+ console.log("");+ return;}++ console.log(tr(zh, "Existing configuration found:", "已找到现有配置:"));+ console.log(` mode: ${existing.mode}`);+ console.log(` baseUrl: ${existing.baseUrl ?? DEFAULT_REMOTE_URL}`);+ if (existing.apiKey) console.log(` apiKey: ${maskKey(String(existing.apiKey))}`);+ if (existing.agent_prefix) console.log(` agent_prefix: ${existing.agent_prefix}`);console.log("");console.log(tr(zh,@@ -392,34 +210,27 @@ export function registerSetupCli(api: any): void {console.log(tr(zh, "✓ Using existing configuration", "✓ 使用现有配置"));console.log("");- // Environment checks for existing local config- let envOk = true;- if (!existing.mode || existing.mode === "local") {- envOk = await runLocalChecks(zh, existing, q);- } else {- await runRemoteCheck(zh, existing);- }+ await runRemoteCheck(zh, existing);- if (envOk) {- console.log(tr(zh,- "✓ Plugin is ready. Run `openclaw gateway --force` to activate.",- "✓ 插件已就绪。运行 `openclaw gateway --force` 以激活。",- ));- }+ console.log(tr(zh,+ "✓ Plugin is ready. Run `openclaw gateway --force` to activate.",+ "✓ 插件已就绪。运行 `openclaw gateway --force` 以激活。",+ ));console.log("");return;}if (existing && options.reconfigure) {console.log(tr(zh, "Existing configuration found:", "已找到现有配置:"));- if (existing.mode === "remote") {+ if (isLegacyLocalMode(existing)) {+ console.log(tr(zh,+ "(Previous local-mode settings will be replaced with remote settings.)",+ "(将用远程模式设置替换此前的本地模式配置。)",+ ));+ } else {console.log(` mode: ${existing.mode}`);console.log(` baseUrl: ${existing.baseUrl ?? DEFAULT_REMOTE_URL}`);if (existing.apiKey) console.log(` apiKey: ${maskKey(String(existing.apiKey))}`);- } else {- console.log(` mode: ${existing.mode ?? "local"}`);- console.log(` configPath: ${existing.configPath ?? DEFAULT_CONFIG_PATH}`);- console.log(` port: ${existing.port ?? DEFAULT_PORT}`);}console.log("");console.log(tr(zh, "Reconfiguring...", "重新配置中..."));@@ -432,26 +243,7 @@ export function registerSetupCli(api: any): void {console.log("");}- const modeDefault = String(existing?.mode ?? "remote");- const modeInput = await q(- tr(zh, "Plugin mode - local or remote", "插件模式 - local 或 remote"),- modeDefault,- );- const mode = modeInput.toLowerCase() === "remote" ? "remote" : "local";-- if (mode === "local") {- const setupOk = await setupLocal(zh, configPath, existing, q);- if (!setupOk) {- console.log(tr(- zh,- "Local setup aborted. Fix the ov.conf issue above, then rerun `openclaw openviking setup`.",- "本地模式配置已中止。请先修复上面的 ov.conf 问题,再重新运行 `openclaw openviking setup`。",- ));- console.log("");- }- } else {- await setupRemote(zh, configPath, existing, q);- }+ await setupRemote(zh, configPath, existing, q);} finally {rl.close();}@@ -461,48 +253,6 @@ export function registerSetupCli(api: any): void {);}-async function runLocalChecks(- zh: boolean,- existing: Record<string, unknown>,- _q: (prompt: string, def?: string) => Promise<string>,-): Promise<boolean> {- console.log(tr(zh, "Checking environment...", "正在检查环境..."));- const ov = await checkOpenVikingInstalled();- if (ov.ok) {- console.log(` OpenViking: ${ov.version} ✓`);- console.log(` Python: ${ov.pythonPath}`);- writeOpenvikingEnv(ov.pythonPath);- } else {- console.log(` ℹ ${tr(zh,- "OpenViking Python package not detected (service may still work if installed separately)",- "未检测到 OpenViking Python 包(如已单独安装服务,可忽略此提示)",- )}`);- }- console.log("");-- const configPath = String(existing.configPath ?? DEFAULT_CONFIG_PATH);- const configValidation = await validateLocalConfigPath(configPath, ov.ok ? ov.pythonPath : undefined);- if (!configValidation.ok) {- printLocalConfigFixHint(zh, configPath, configValidation.error);- return false;- }-- const port = Number(existing.port) || DEFAULT_PORT;- console.log(tr(zh, `Checking OpenViking service on port ${port}...`, `正在检查 OpenViking 服务 (端口 ${port})...`));- const health = await checkServiceHealth(`http://127.0.0.1:${port}`);- if (health.ok) {- const ver = health.version ? ` (version: ${health.version})` : "";- console.log(` ✓ ${tr(zh, `OpenViking service is running${ver}`, `OpenViking 服务正在运行${ver}`)}`);- } else {- console.log(` ℹ ${tr(zh,- `OpenViking service is not running on port ${port} (will auto-start with openclaw gateway)`,- `OpenViking 服务未在端口 ${port} 运行(将随 openclaw gateway 自动启动)`,- )}`);- }- console.log("");- return true;-}-async function runRemoteCheck(zh: boolean,existing: Record<string, unknown>,@@ -520,88 +270,6 @@ async function runRemoteCheck(console.log("");}-async function setupLocal(- zh: boolean,- configPath: string,- existing: Record<string, unknown> | null,- q: (prompt: string, def?: string) => Promise<string>,- deps: Partial<SetupLocalDeps> = {},-): Promise<boolean> {- const resolvedDeps = { ...defaultSetupLocalDeps, ...deps };- // Environment check (non-blocking)- console.log("");- console.log(tr(zh, "Checking environment...", "正在检查环境..."));- const ov = await resolvedDeps.checkOpenVikingInstalled();- if (ov.ok) {- console.log(` OpenViking: ${ov.version} ✓`);- console.log(` Python: ${ov.pythonPath}`);- resolvedDeps.writeOpenvikingEnv(ov.pythonPath);- } else {- console.log(` ⚠ ${tr(zh,- "OpenViking Python package not detected. Make sure it is installed:",- "未检测到 OpenViking Python 包,请确保已安装:",- )}`);- console.log(" pip install openviking");- }- console.log("");-- // Configuration- console.log(tr(zh, "── Local Mode Configuration ──", "── 本地模式配置 ──"));- console.log("");-- const defaultConfigPath = existing?.configPath ? String(existing.configPath) : DEFAULT_CONFIG_PATH;- const defaultPort = existing?.port ? String(existing.port) : String(DEFAULT_PORT);-- const cfgPath = await q(tr(zh, "Config path", "配置文件路径"), defaultConfigPath);- const configValidation = await resolvedDeps.validateLocalConfigPath(cfgPath, ov.ok ? ov.pythonPath : undefined);- if (!configValidation.ok) {- printLocalConfigFixHint(zh, cfgPath, configValidation.error);- return false;- }-- const portStr = await q(tr(zh, "Port", "端口"), defaultPort);- const port = Math.max(1, Math.min(65535, parseInt(portStr, 10) || DEFAULT_PORT));-- console.log("");-- // Service health check (non-blocking)- console.log(tr(zh, `Checking OpenViking service on port ${port}...`, `正在检查 OpenViking 服务 (端口 ${port})...`));- const health = await resolvedDeps.checkServiceHealth(`http://127.0.0.1:${port}`);- if (health.ok) {- const ver = health.version ? ` (version: ${health.version})` : "";- console.log(` ✓ ${tr(zh, `OpenViking service is running${ver}`, `OpenViking 服务正在运行${ver}`)}`);- } else {- console.log(` ℹ ${tr(zh,- `OpenViking service is not running on port ${port} (will auto-start with openclaw gateway)`,- `OpenViking 服务未在端口 ${port} 运行(将随 openclaw gateway 自动启动)`,- )}`);- }- console.log("");-- // Write config- const pluginCfg: Record<string, unknown> = {- ...(existing ?? {}),- mode: "local",- configPath: cfgPath,- port,- };- delete pluginCfg.baseUrl;-- resolvedDeps.writeConfig(configPath, pluginCfg);-- console.log("");- console.log(` ${tr(zh, "mode:", "模式:")} local`);- console.log(` ${tr(zh, "configPath:", "配置文件:")} ${cfgPath}`);- console.log(` ${tr(zh, "port:", "端口:")} ${port}`);- console.log("");- console.log(tr(zh,- "Run `openclaw gateway --force` to activate the plugin.",- "运行 `openclaw gateway --force` 以激活插件。",- ));- console.log("");- return true;-}-async function setupRemote(zh: boolean,configPath: string,@@ -612,13 +280,15 @@ async function setupRemote(console.log(tr(zh, "── Remote Mode Configuration ──", "── 远程模式配置 ──"));console.log("");- const defaultUrl = existing?.baseUrl ? String(existing.baseUrl) : DEFAULT_REMOTE_URL;+ const defaultUrl = existing?.baseUrl && String(existing.baseUrl).trim()+ ? String(existing.baseUrl)+ : DEFAULT_REMOTE_URL;const defaultApiKey = existing?.apiKey ? String(existing.apiKey) : "";- const defaultAgentId = existing?.agentId ? String(existing.agentId) : "";+ const defaultAgentPrefix = existing?.agent_prefix ? String(existing.agent_prefix) : "";const baseUrl = await q(tr(zh, "OpenViking server URL", "OpenViking 服务器地址"), defaultUrl);const apiKey = await q(tr(zh, "API Key (optional)", "API Key(可选)"), defaultApiKey);- const agentId = await q(tr(zh, "Agent ID (optional)", "Agent ID(可选)"), defaultAgentId);+ const agentPrefix = await q(tr(zh, "Agent Prefix (optional)", "Agent Prefix(可选)"), defaultAgentPrefix);console.log("");@@ -646,8 +316,8 @@ async function setupRemote(};if (apiKey) pluginCfg.apiKey = apiKey;else delete pluginCfg.apiKey;- if (agentId) pluginCfg.agentId = agentId;- else delete pluginCfg.agentId;+ if (agentPrefix) pluginCfg.agent_prefix = agentPrefix;+ else delete pluginCfg.agent_prefix;delete pluginCfg.configPath;delete pluginCfg.port;@@ -657,7 +327,7 @@ async function setupRemote(console.log(` ${tr(zh, "mode:", "模式:")} remote`);console.log(` baseUrl: ${baseUrl}`);if (apiKey) console.log(` apiKey: ${maskKey(apiKey)}`);- if (agentId) console.log(` agentId: ${agentId}`);+ if (agentPrefix) console.log(` agent_prefix: ${agentPrefix}`);console.log("");console.log(tr(zh,"Run `openclaw gateway --force` to activate the plugin.",@@ -667,8 +337,6 @@ async function setupRemote(}export const __test__ = {- parseWindowsEnvBatPythonPath,- parsePosixEnvPythonPath,- validateLocalConfigPath,- setupLocal,+ resolveAbsoluteCommand,+ isLegacyLocalMode,};diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex 584db0e1d..009bf66db 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -1,17 +1,9 @@-import { homedir } from "node:os";-import { join } from "node:path";-import { resolve as resolvePath } from "node:path";import { getEnv } from "./runtime-utils.js";export type MemoryOpenVikingConfig = {- /** "local" = plugin starts OpenViking server as child process (like Claude Code); "remote" = use existing HTTP server */- mode?: "local" | "remote";- /** Path to ov.conf; used when mode is "local". Default ~/.openviking/ov.conf */- configPath?: string;- /** Port for local server when mode is "local". Ignored when mode is "remote". */- port?: number;+ mode?: "remote";baseUrl?: string;- agentId?: string;+ agent_prefix?: string;serverAuthMode?: "api_key" | "trusted";apiKey?: string;/** Advanced option. Only needed when using root key or trusted auth mode. With a user key the server derives identity from the key. */@@ -58,7 +50,6 @@ export type MemoryOpenVikingConfig = {};const DEFAULT_BASE_URL = "http://127.0.0.1:1933";-const DEFAULT_PORT = 1933;const DEFAULT_TARGET_URI = "viking://user/memories";const DEFAULT_TIMEOUT_MS = 15000;const DEFAULT_CAPTURE_MODE = "semantic";@@ -71,16 +62,14 @@ const DEFAULT_RECALL_MAX_INJECTED_CHARS = 4000;const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;-const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");--const DEFAULT_AGENT_ID = "default";+const DEFAULT_AGENT_PREFIX = "default";const DEFAULT_SERVER_AUTH_MODE = "api_key";-function resolveAgentId(configured: unknown): string {+function resolveAgentPrefix(configured: unknown): string {if (typeof configured === "string" && configured.trim()) {return configured.trim();}- return DEFAULT_AGENT_ID;+ return DEFAULT_AGENT_PREFIX;}function resolveEnvVars(value: string): string {@@ -154,13 +143,18 @@ export const memoryOpenVikingConfigSchema = {value = {};}const cfg = value as Record<string, unknown>;+ if ("agentId" in cfg) {+ if (!("agent_prefix" in cfg)) {+ cfg.agent_prefix = cfg.agentId;+ }+ delete cfg.agentId;+ }assertAllowedKeys(cfg,["mode",- "configPath",- "port","baseUrl",+ "agent_prefix","agentId","serverAuthMode","apiKey",@@ -194,21 +188,8 @@ export const memoryOpenVikingConfigSchema = {"openviking config",);- const mode = (cfg.mode === "local" || cfg.mode === "remote" ? cfg.mode : "remote") as- | "local"- | "remote";- const port = Math.max(1, Math.min(65535, Math.floor(toNumber(cfg.port, DEFAULT_PORT))));- const rawConfigPath =- typeof cfg.configPath === "string" && cfg.configPath.trim()- ? cfg.configPath.trim()- : DEFAULT_LOCAL_CONFIG_PATH;- const configPath = resolvePath(- resolveEnvVars(rawConfigPath).replace(/^~/, homedir()),- );-- const localBaseUrl = `http://127.0.0.1:${port}`;- const rawBaseUrl =- mode === "local" ? localBaseUrl : (typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl());+ const mode = "remote" as const;+ const rawBaseUrl = typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl();const resolvedBaseUrl = resolveEnvVars(rawBaseUrl).replace(/\/+$/, "");const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : process.env.OPENVIKING_API_KEY;const rawServerAuthMode =@@ -279,10 +260,8 @@ export const memoryOpenVikingConfigSchema = {return {mode,- configPath,- port,baseUrl: resolvedBaseUrl,- agentId: resolveAgentId(cfg.agentId),+ agent_prefix: resolveAgentPrefix(cfg.agent_prefix),serverAuthMode,apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",accountId,@@ -334,30 +313,15 @@ export const memoryOpenVikingConfigSchema = {};},uiHints: {- mode: {- label: "Mode",- help: "local = plugin starts OpenViking server (like Claude Code); remote = use existing HTTP server",- },- configPath: {- label: "Config path (local)",- placeholder: DEFAULT_LOCAL_CONFIG_PATH,- help: "Path to ov.conf when mode is local",- },- port: {- label: "Port (local)",- placeholder: String(DEFAULT_PORT),- help: "Port for local OpenViking server",- advanced: true,- },baseUrl: {- label: "OpenViking Base URL (remote)",+ label: "OpenViking Base URL",placeholder: DEFAULT_BASE_URL,help: "HTTP URL when mode is remote (or use ${OPENVIKING_BASE_URL})",},- agentId: {- label: "Agent ID",+ agent_prefix: {+ label: "Agent Prefix",placeholder: "auto-generated",- help: 'OpenViking X-OpenViking-Agent. "default" follows OpenClaw ctx.agentId. Non-default values are prepended as "<config>_<ctx.agentId>" (sanitized to [a-zA-Z0-9_-]).',+ help: 'OpenViking X-OpenViking-Agent prefix. "default" follows OpenClaw ctx.agentId. Non-default values are prepended as "<prefix>_<ctx.agentId>" (sanitized to [a-zA-Z0-9_-]).',},serverAuthMode: {label: "Server Auth Mode",@@ -489,15 +453,8 @@ export const memoryOpenVikingConfigSchema = {label: "Log find requests",help:"Log tenant routing: POST /api/v1/search/find (query, target_uri) and session POST .../messages + .../commit (sessionId, X-OpenViking-*). Never logs apiKey. " +- "Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1 (no JSON edit). When on, local-mode OpenViking subprocess stderr is also logged at info.",+ "Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1 (no JSON edit).",advanced: true,},},};--export const DEFAULT_MEMORY_OPENVIKING_DATA_DIR = join(- homedir(),- ".openclaw",- "memory",- "openviking",-);diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex 67a8af078..e8963a0a5 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -702,7 +702,6 @@ export function createMemoryOpenVikingContextEngine(params: {cfg: Required<MemoryOpenVikingConfig>;logger: Logger;getClient: () => Promise<OpenVikingClient>;- quickPrecheck?: () => Promise<{ ok: true } | { ok: false; reason: string }>;/** Extra args help match hook-populated routing when OpenClaw provides sessionKey / OV session id. */resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;rememberSessionAgentId?: (ctx: {@@ -719,7 +718,6 @@ export function createMemoryOpenVikingContextEngine(params: {cfg,logger,getClient,- quickPrecheck,resolveAgentId,rememberSessionAgentId,} = params;@@ -797,29 +795,6 @@ export function createMemoryOpenVikingContextEngine(params: {return typeof agentId === "string" && agentId.trim() ? agentId.trim() : undefined;}- async function runLocalPrecheck(- stage: "assemble" | "afterTurn",- sessionId: string,- extra: Record<string, unknown> = {},- ): Promise<boolean> {- if (cfg.mode !== "local" || !quickPrecheck) {- return true;- }- const result = await quickPrecheck();- if (result.ok) {- return true;- }- logger.warn?.(- `openviking: ${stage} precheck failed for session=${sessionId}: ${result.reason}`,- );- diag(`${stage}_skip`, sessionId, {- reason: "precheck_failed",- precheckReason: result.reason,- ...extra,- });- return false;- }-function assemblePassthrough(ovSessionId: string,reason: string,@@ -935,9 +910,6 @@ export function createMemoryOpenVikingContextEngine(params: {}try {- if (!(await runLocalPrecheck("assemble", OVSessionId, { tokenBudget }))) {- return { messages, estimatedTokens: roughEstimate(messages) };- }const client = await getClient();const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);@@ -1105,13 +1077,6 @@ export function createMemoryOpenVikingContextEngine(params: {messages: newMsgFull,});- if (!(await runLocalPrecheck("afterTurn", OVSessionId, {- totalMessages: messages.length,- newMessageCount: newCount,- prePromptMessageCount: start,- }))) {- return;- }const client = await getClient();const createdAt = pickLatestCreatedAt(turnMessages);const senderRoleId = toRoleId(sender.senderId);diff --git a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.pyindex ac8e83c24..c686af1b8 100644--- a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py+++ b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py@@ -1136,7 +1136,7 @@ def main() -> int:)or str(os.environ.get("OPENVIKING_API_KEY", "")).strip())- agent_id = args.agent_id or str(plugin_config.get("agentId", "")).strip() or DEFAULT_AGENT_ID+ agent_id = args.agent_id or str(plugin_config.get("agent_prefix", "")).strip() or DEFAULT_AGENT_IDuser_id = args.user_id or f"ov-healthcheck-{uuid.uuid4().hex[:8]}"probe = f"probe-{uuid.uuid4().hex[:8]}"run_facts = build_run_facts(probe)@@ -1183,7 +1183,7 @@ def main() -> int:recorder.add("WARN", "plugins.entries.openviking entry missing")if plugin_config:- mode = str(plugin_config.get("mode", "local"))+ mode = str(plugin_config.get("mode", "remote"))recorder.add("INFO", "Plugin mode", mode)if ov_config_path:recorder.add("INFO", "OpenViking config discovered", str(ov_config_path))diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 6ef00db58..cdff509b4 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -1,11 +1,8 @@-import { launchProcess, sysEnv, getEnv } from "./runtime-utils.js";-import { tmpdir } from "node:os";-import { Type } from "@sinclair/typebox";import { memoryOpenVikingConfigSchema } from "./config.js";import { registerSetupCli } from "./commands/setup.js";-import { OpenVikingClient, localClientCache, localClientPendingPromises, isMemoryUri } from "./client.js";+import { OpenVikingClient, isMemoryUri } from "./client.js";import type {AddResourceInput,AddResourceResult,@@ -13,7 +10,6 @@ import type {AddSkillResult,FindResult,FindResultItem,- PendingClientEntry,CommitSessionResult,OVMessage,} from "./client.js";@@ -33,16 +29,7 @@ import {summarizeInjectionMemories,pickMemoriesForInjection,} from "./memory-ranking.js";-import {- IS_WIN,- waitForHealthOrExit,- quickHealthCheck,- quickRecallPrecheck,- withTimeout,- resolvePythonCommand,- prepareLocalPort,- checkLocalRuntime,-} from "./process-manager.js";+import { quickRecallPrecheck, withTimeout } from "./process-manager.js";import {createMemoryOpenVikingContextEngine,openClawSessionToOvStorageId,@@ -168,8 +155,6 @@ type OpenClawPluginApi = {) => void;};-const MAX_OPENVIKING_STDERR_LINES = 200;-const MAX_OPENVIKING_STDERR_CHARS = 256_000;const AUTO_RECALL_TIMEOUT_MS = 5_000;const RECALL_QUERY_MAX_CHARS = 4_000;@@ -554,7 +539,7 @@ const contextEnginePlugin = {: {};const cfg = memoryOpenVikingConfigSchema.parse(api.pluginConfig);const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);- const rawAgentId = rawCfg.agentId;+ const rawAgentId = rawCfg.agent_prefix;if (cfg.logFindRequests) {api.logger.info("openviking: routing debug logging enabled (config logFindRequests, or env OPENVIKING_LOG_ROUTING=1 / OPENVIKING_DEBUG=1)",@@ -566,10 +551,10 @@ const contextEnginePlugin = {}};verboseRoutingInfo(- `openviking: loaded plugin config agentId="${cfg.agentId}" ` +- `(raw plugins.entries.openviking.config.agentId=${JSON.stringify(rawAgentId ?? "(missing)")}; ` ++ `openviking: loaded plugin config agent_prefix="${cfg.agent_prefix}" ` ++ `(raw plugins.entries.openviking.config.agent_prefix=${JSON.stringify(rawAgentId ?? "(missing)")}; ` +`${- cfg.agentId !== "default"+ cfg.agent_prefix !== "default"? "non-default → X-OpenViking-Agent is <configAgentId>_<ctx.agentId> (sanitized to [a-zA-Z0-9_-]) when hooks expose session agent; config-only if ctx.agentId unknown": 'default → X-OpenViking-Agent follows OpenClaw ctx.agentId per session (e.g. "main")'})`,@@ -590,68 +575,21 @@ const contextEnginePlugin = {: undefined;const tenantAccount = cfg.accountId;const tenantUser = cfg.userId;- const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}:${cfg.serverAuthMode}:${tenantAccount}:${tenantUser}:${cfg.agentId}:${cfg.isolateUserScopeByAgent ? "1" : "0"}:${cfg.isolateAgentScopeByUser ? "1" : "0"}:${cfg.logFindRequests ? "1" : "0"}`;-- let clientPromise: Promise<OpenVikingClient>;- let localProcess: ReturnType<typeof launchProcess> | null = null;- let resolveLocalClient: ((c: OpenVikingClient) => void) | null = null;- let rejectLocalClient: ((err: unknown) => void) | null = null;- let localUnavailableReason: string | null = null;- const markLocalUnavailable = (reason: string, err?: unknown) => {- if (!localUnavailableReason) {- localUnavailableReason = reason;- api.logger.warn(- `openviking: local mode marked unavailable (${reason})${err ? `: ${String(err)}` : ""}`,- );- }- if (rejectLocalClient) {- rejectLocalClient(- err instanceof Error ? err : new Error(`openviking unavailable: ${reason}`),- );- rejectLocalClient = null;- }- resolveLocalClient = null;- };- if (cfg.mode === "local") {- const cached = localClientCache.get(localCacheKey);- if (cached) {- localProcess = cached.process;- clientPromise = Promise.resolve(cached.client);- } else {- const existingPending = localClientPendingPromises.get(localCacheKey);- if (existingPending) {- clientPromise = existingPending.promise;- } else {- const entry = {} as PendingClientEntry;- entry.promise = new Promise<OpenVikingClient>((resolve, reject) => {- entry.resolve = resolve;- entry.reject = reject;- });- // Service startup can reject this shared promise before any hook/tool- // awaits it. Attach a sink now so expected local-startup failures do- // not surface as process-level unhandled rejections.- void entry.promise.catch(() => {});- clientPromise = entry.promise;- localClientPendingPromises.set(localCacheKey, entry);- }- }- } else {- clientPromise = Promise.resolve(- new OpenVikingClient(- cfg.baseUrl,- cfg.apiKey,- cfg.agentId,- cfg.timeoutMs,- cfg.serverAuthMode,- tenantAccount,- tenantUser,- routingDebugLog,- cfg.isolateUserScopeByAgent,- cfg.isolateAgentScopeByUser,- ),- );- }+ const clientPromise = Promise.resolve(+ new OpenVikingClient(+ cfg.baseUrl,+ cfg.apiKey,+ cfg.agent_prefix,+ cfg.timeoutMs,+ cfg.serverAuthMode,+ tenantAccount,+ tenantUser,+ routingDebugLog,+ cfg.isolateUserScopeByAgent,+ cfg.isolateAgentScopeByUser,+ ),+ );const getClient = (): Promise<OpenVikingClient> => clientPromise;@@ -1426,7 +1364,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {}));let contextEngineRef: ContextEngineWithCommit | null = null;- const sessionAgentResolver = createSessionAgentResolver(cfg.agentId);+ const sessionAgentResolver = createSessionAgentResolver(cfg.agent_prefix);const rememberSessionAgentId = (ctx: SessionAgentLookup) => {sessionAgentResolver.remember(ctx);};@@ -1445,7 +1383,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {sessionId: sid || "(empty)",sessionKey: sk || "(empty)",ovSessionId: ovSid || "(empty)",- parsedConfigAgentId: cfg.agentId,+ parsedConfigAgentPrefix: cfg.agent_prefix,mappedResolvedAgentId: result.mappedResolvedAgentId,resolvedBeforeSanitize: result.resolvedBeforeSanitize,resolved: result.resolved,@@ -1515,7 +1453,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {const prependContextParts: string[] = [];if (cfg.autoRecall && queryText.length >= 5) {- const precheck = await quickRecallPrecheck(cfg.mode, cfg.baseUrl, cfg.port, localProcess);+ const precheck = await quickRecallPrecheck(cfg.baseUrl);if (!precheck.ok) {verboseRoutingInfo(`openviking: skipping auto-recall because precheck failed (${precheck.reason})`,@@ -1646,10 +1584,6 @@ const mergeFindResults = (results: FindResult[]): FindResult => {cfg,logger: api.logger,getClient,- quickPrecheck:- cfg.mode === "local"- ? () => quickRecallPrecheck(cfg.mode, cfg.baseUrl, cfg.port, localProcess)- : undefined,resolveAgentId,rememberSessionAgentId,});@@ -1669,242 +1603,13 @@ const mergeFindResults = (results: FindResult[]): FindResult => {api.registerService({id: "openviking",start: async () => {- // Claim the pending entry — only the first start() call to claim it spawns the process.- // Subsequent start() calls (from other registrations sharing the same promise) fall through.- const pendingEntry = localClientPendingPromises.get(localCacheKey);- const isSpawner = cfg.mode === "local" && !!pendingEntry;- if (isSpawner) {- localClientPendingPromises.delete(localCacheKey);- resolveLocalClient = pendingEntry!.resolve;- rejectLocalClient = pendingEntry!.reject;- }- if (isSpawner) {- const timeoutMs = 60_000;- const intervalMs = 500;-- // Prepare port: kill stale OpenViking, or auto-find free port if occupied by others- const actualPort = await prepareLocalPort(cfg.port, api.logger);- const baseUrl = `http://127.0.0.1:${actualPort}`;-- const rawPythonCmd = resolvePythonCommand(api.logger);-- const runtimeCheck = checkLocalRuntime(rawPythonCmd, cfg.configPath, api.logger);- if (!runtimeCheck.installed) {- api.logger.warn(- "openviking: package not detected — please run `pip install openviking` first. " +- "Server spawn will proceed but may fail.",- );- }- if (!runtimeCheck.configExists) {- api.logger.warn(- `openviking: config file ${cfg.configPath} not found — ` +- "please run `ov-install` or create it manually. See https://github.com/volcengine/OpenViking",- );- }- const pythonCmd = runtimeCheck.pythonCmd;-- // Inherit system environment; optionally override Go/Python paths via env vars- const pathSep = IS_WIN ? ";" : ":";- const { ALL_PROXY, all_proxy, HTTP_PROXY, http_proxy, HTTPS_PROXY, https_proxy, ...filteredEnv } = sysEnv();- const env = {- ...filteredEnv,- PYTHONUNBUFFERED: "1",- PYTHONWARNINGS: "ignore::RuntimeWarning",- OPENVIKING_CONFIG_FILE: cfg.configPath,- OPENVIKING_START_CONFIG: cfg.configPath,- OPENVIKING_START_HOST: "127.0.0.1",- OPENVIKING_START_PORT: String(actualPort),- ...(getEnv("OPENVIKING_GO_PATH") && { PATH: `${getEnv("OPENVIKING_GO_PATH")}${pathSep}${getEnv("PATH") || ""}` }),- ...(getEnv("OPENVIKING_GOPATH") && { GOPATH: getEnv("OPENVIKING_GOPATH") }),- ...(getEnv("OPENVIKING_GOPROXY") && { GOPROXY: getEnv("OPENVIKING_GOPROXY") }),- };- // Run OpenViking server: use run_path on the module file to avoid RuntimeWarning from- // "parent package import loads submodule before execution" (exit 3). Fallback to run_module with warning suppressed.- const runpyCode = `import sys,os,warnings; warnings.filterwarnings('ignore', category=RuntimeWarning, message='.*sys.modules.*'); sys.argv=['openviking.server.bootstrap','--config',os.environ['OPENVIKING_START_CONFIG'],'--host',os.environ.get('OPENVIKING_START_HOST','127.0.0.1'),'--port',os.environ['OPENVIKING_START_PORT']]; import runpy, importlib.util; spec=importlib.util.find_spec('openviking.server.bootstrap'); (runpy.run_path(spec.origin, run_name='__main__') if spec and getattr(spec,'origin',None) else runpy.run_module('openviking.server.bootstrap', run_name='__main__', alter_sys=True))`;- const child = launchProcess(- pythonCmd,- ["-c", runpyCode],- { env, cwd: IS_WIN ? tmpdir() : "/tmp", stdio: ["ignore", "pipe", "pipe"] },- );- localProcess = child;- const stderrChunks: string[] = [];- let stderrCharCount = 0;- let stderrDroppedChunks = 0;- const pushStderrChunk = (chunk: string) => {- if (!chunk) return;- stderrChunks.push(chunk);- stderrCharCount += chunk.length;- while (- stderrChunks.length > MAX_OPENVIKING_STDERR_LINES ||- stderrCharCount > MAX_OPENVIKING_STDERR_CHARS- ) {- const dropped = stderrChunks.shift();- if (!dropped) break;- stderrCharCount -= dropped.length;- stderrDroppedChunks += 1;- }- };- const formatStderrOutput = () => {- if (!stderrChunks.length && !stderrDroppedChunks) return "";- const truncated =- stderrDroppedChunks > 0- ? `[truncated ${stderrDroppedChunks} earlier stderr chunk(s)]\n`- : "";- return `\n[openviking stderr]\n${truncated}${stderrChunks.join("\n")}`;- };- child.on("error", (err: Error) => api.logger.warn(`openviking: local server error: ${String(err)}`));- child.stderr?.on("data", (chunk: Buffer) => {- const s = String(chunk).trim();- pushStderrChunk(s);- if (cfg.logFindRequests) {- api.logger.info(`[openviking-local] ${s}`);- } else {- api.logger.debug?.(`[openviking] ${s}`);- }- });- child.on("exit", (code: number | null, signal: string | null) => {- if (localProcess === child) {- localProcess = null;- localClientCache.delete(localCacheKey);- }- const out = formatStderrOutput();- api.logger.warn(`openviking: subprocess exited (code=${code}, signal=${signal})${out}`);- });- try {- await waitForHealthOrExit(baseUrl, timeoutMs, intervalMs, child);- const client = new OpenVikingClient(- baseUrl,- cfg.apiKey,- cfg.agentId,- cfg.timeoutMs,- cfg.serverAuthMode,- tenantAccount,- tenantUser,- routingDebugLog,- cfg.isolateUserScopeByAgent,- cfg.isolateAgentScopeByUser,- );- localClientCache.set(localCacheKey, { client, process: child });- resolveLocalClient!(client);- rejectLocalClient = null;- api.logger.info(- `openviking: local server started (${baseUrl}, config: ${cfg.configPath})`,- );- } catch (err) {- localProcess = null;- child.kill("SIGTERM");- markLocalUnavailable("startup failed", err);- if (stderrChunks.length) {- api.logger.warn(- `openviking: startup failed (health check timeout or error).${formatStderrOutput()}`,- );- }- throw err;- }- } else if (cfg.mode === "local") {- // Defensive re-spawn: if we're not the designated spawner but there's- // no valid local process, trigger a fresh spawn to recover from- // scenarios like Gateway force-restart where the child process was- // orphaned or exited silently.- const cached = localClientCache.get(localCacheKey);- const processAlive = cached?.process && cached.process.exitCode === null && !cached.process.killed;- if (!processAlive) {- const healthOk = await quickHealthCheck(`http://127.0.0.1:${cfg.port}`, 2000);- if (!healthOk) {- api.logger.warn(- `openviking: no valid local process detected (isSpawner=false), triggering defensive re-spawn`,- );- const timeoutMs = 60_000;- const intervalMs = 500;- const actualPort = await prepareLocalPort(cfg.port, api.logger);- const baseUrl = `http://127.0.0.1:${actualPort}`;- const pythonCmd = resolvePythonCommand(api.logger);- const pathSep = IS_WIN ? ";" : ":";- const env = {- ...sysEnv(),- PYTHONUNBUFFERED: "1",- PYTHONWARNINGS: "ignore::RuntimeWarning",- OPENVIKING_CONFIG_FILE: cfg.configPath,- OPENVIKING_START_CONFIG: cfg.configPath,- OPENVIKING_START_HOST: "127.0.0.1",- OPENVIKING_START_PORT: String(actualPort),- ...(getEnv("OPENVIKING_GO_PATH") && { PATH: `${getEnv("OPENVIKING_GO_PATH")}${pathSep}${getEnv("PATH") || ""}` }),- ...(getEnv("OPENVIKING_GOPATH") && { GOPATH: getEnv("OPENVIKING_GOPATH") }),- ...(getEnv("OPENVIKING_GOPROXY") && { GOPROXY: getEnv("OPENVIKING_GOPROXY") }),- };- const runpyCode = `import sys,os,warnings; warnings.filterwarnings('ignore', category=RuntimeWarning, message='.*sys.modules.*'); sys.argv=['openviking.server.bootstrap','--config',os.environ['OPENVIKING_START_CONFIG'],'--host',os.environ.get('OPENVIKING_START_HOST','127.0.0.1'),'--port',os.environ['OPENVIKING_START_PORT']]; import runpy, importlib.util; spec=importlib.util.find_spec('openviking.server.bootstrap'); (runpy.run_path(spec.origin, run_name='__main__') if spec and getattr(spec,'origin',None) else runpy.run_module('openviking.server.bootstrap', run_name='__main__', alter_sys=True))`;- const child = launchProcess(- pythonCmd,- ["-c", runpyCode],- { env, cwd: IS_WIN ? tmpdir() : "/tmp", stdio: ["ignore", "pipe", "pipe"] },- );- localProcess = child;- child.on("error", (err: Error) => api.logger.warn(`openviking: local server error (re-spawn): ${String(err)}`));- child.stderr?.on("data", (chunk: Buffer) => {- api.logger.debug?.(`[openviking-respawn] ${String(chunk).trim()}`);- });- child.on("exit", (code: number | null, signal: string | null) => {- if (localProcess === child) {- localProcess = null;- localClientCache.delete(localCacheKey);- }- api.logger.warn(`openviking: re-spawned subprocess exited (code=${code}, signal=${signal})`);- });- try {- await waitForHealthOrExit(baseUrl, timeoutMs, intervalMs, child);- const client = new OpenVikingClient(- baseUrl,- cfg.apiKey,- cfg.agentId,- cfg.timeoutMs,- cfg.serverAuthMode,- tenantAccount,- tenantUser,- undefined,- cfg.isolateUserScopeByAgent,- cfg.isolateAgentScopeByUser,- );- localClientCache.set(localCacheKey, { client, process: child });- if (resolveLocalClient) {- resolveLocalClient(client);- rejectLocalClient = null;- }- api.logger.info(- `openviking: local server re-spawned successfully (${baseUrl}, config: ${cfg.configPath})`,- );- } catch (err) {- localProcess = null;- child.kill("SIGTERM");- markLocalUnavailable("re-spawn failed", err);- api.logger.warn(`openviking: defensive re-spawn failed: ${String(err)}`);- throw err;- }- } else {- api.logger.info(`openviking: local process healthy on port ${cfg.port} (isSpawner=false)`);- }- } else {- await (await getClient()).healthCheck().catch(() => {});- api.logger.info(- `openviking: initialized via cache (url: ${cfg.baseUrl}, targetUri: ${cfg.targetUri})`,- );- }- } else {- await (await getClient()).healthCheck().catch(() => {});- api.logger.info(- `openviking: initialized (url: ${cfg.baseUrl}, targetUri: ${cfg.targetUri}, search: hybrid endpoint)`,- );- }+ await (await getClient()).healthCheck().catch(() => {});+ api.logger.info(+ `openviking: initialized (url: ${cfg.baseUrl}, targetUri: ${cfg.targetUri}, search: hybrid endpoint)`,+ );},stop: () => {- if (localProcess) {- localProcess.kill("SIGTERM");- localClientCache.delete(localCacheKey);- localClientPendingPromises.delete(localCacheKey);- localProcess = null;- api.logger.info("openviking: local server stopped");- } else {- api.logger.info("openviking: stopped");- }+ api.logger.info("openviking: stopped");},});},diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.jsonindex f50c847a6..bf6e895a1 100644--- a/examples/openclaw-plugin/install-manifest.json+++ b/examples/openclaw-plugin/install-manifest.json@@ -10,7 +10,8 @@"required": ["index.ts","config.ts",- "package.json"+ "package.json",+ "openclaw.plugin.json"],"optional": ["context-engine.ts",@@ -22,7 +23,6 @@"session-transcript-repair.ts","runtime-utils.ts","commands/setup.ts",- "openclaw.plugin.json","tsconfig.json","package-lock.json",".gitignore"diff --git a/examples/openclaw-plugin/install.sh b/examples/openclaw-plugin/install.shdeleted file mode 100755index 7056400ea..000000000--- a/examples/openclaw-plugin/install.sh+++ /dev/null@@ -1,2240 +0,0 @@-#!/bin/bash-#-# 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)-# --version <ver> - Shorthand for --plugin-version v<ver> + --openviking-version <ver>-# --plugin-version <tag> - Plugin version (Git tag, e.g. v0.2.9, default: latest tag)-# --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 (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-# NPM_REGISTRY=url - npm registry (default: https://registry.npmmirror.com)-# 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-# 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 is legacy, prefer PLUGIN_VERSION. If omitted, resolve the latest tag from GitHub.-PLUGIN_VERSION_EXPLICIT="0"-if [[ -n "${PLUGIN_VERSION:-}" || -n "${BRANCH:-}" ]]; then- PLUGIN_VERSION_EXPLICIT="1"-fi-PLUGIN_VERSION="${PLUGIN_VERSION:-${BRANCH:-}}"-OPENVIKING_VERSION="${OPENVIKING_VERSION:-}"-VERSION_ALIAS=""-VERSION_ALIAS_EXPLICIT="0"-PLUGIN_VERSION_ARG_EXPLICIT="0"-OPENVIKING_VERSION_ARG_EXPLICIT="0"-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://mirrors.volces.com/pypi/simple/}"-HOME_DIR="${HOME:-$USERPROFILE}"-DEFAULT_OPENCLAW_DIR="${HOME_DIR}/.openclaw"-OPENCLAW_DIR="${DEFAULT_OPENCLAW_DIR}"-OPENVIKING_DIR="${HOME_DIR}/.openviking"-PLUGIN_DEST="" # Will be set after resolving plugin config-DEFAULT_SERVER_PORT=1933-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="remote"-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_version_alias=""-_expect_repo=""-for arg in "$@"; do- if [[ -n "$_expect_workdir" ]]; then- OPENCLAW_DIR="$arg"- _expect_workdir=""- continue- fi- if [[ -n "$_expect_plugin_version" ]]; then- PLUGIN_VERSION="$arg"- PLUGIN_VERSION_EXPLICIT="1"- PLUGIN_VERSION_ARG_EXPLICIT="1"- _expect_plugin_version=""- continue- fi- if [[ -n "$_expect_ov_version" ]]; then- OPENVIKING_VERSION="$arg"- OPENVIKING_VERSION_ARG_EXPLICIT="1"- _expect_ov_version=""- continue- fi- if [[ -n "$_expect_version_alias" ]]; then- VERSION_ALIAS="$arg"- VERSION_ALIAS_EXPLICIT="1"- _expect_version_alias=""- 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" == "--version" ]] && { _expect_version_alias="1"; continue; }- [[ "$arg" == --plugin-version=* ]] && { PLUGIN_VERSION="${arg#--plugin-version=}"; PLUGIN_VERSION_EXPLICIT="1"; PLUGIN_VERSION_ARG_EXPLICIT="1"; continue; }- [[ "$arg" == --openviking-version=* ]] && { OPENVIKING_VERSION="${arg#--openviking-version=}"; OPENVIKING_VERSION_ARG_EXPLICIT="1"; continue; }- [[ "$arg" == --version=* ]] && { VERSION_ALIAS="${arg#--version=}"; VERSION_ALIAS_EXPLICIT="1"; continue; }- [[ "$arg" == "--repo" ]] && { _expect_repo="1"; continue; }- [[ "$arg" == "-h" || "$arg" == "--help" ]] && {- echo "Usage: curl -fsSL <INSTALL_URL> | bash [-s -- OPTIONS]"- echo ""- echo "Options:"- echo " --repo <owner/repo> GitHub repository (default: volcengine/OpenViking)"- echo " --version <v> Shorthand for --plugin-version v<v> and --openviking-version <v>"- echo " --plugin-version <tag> Plugin version (Git tag, e.g. v0.2.9, default: latest tag)"- 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 a specific release version"- echo " curl -fsSL <URL> | bash -s -- --version 0.2.9"- echo ""- echo " # Install from a fork repository"- echo " curl -fsSL <URL> | bash -s -- --repo yourname/OpenViking --plugin-version dev-branch"- echo ""- echo " # Install specific plugin version"- echo " curl -fsSL <URL> | bash -s -- --plugin-version v0.2.8"- echo ""- echo " # Upgrade only the plugin files from main branch"- 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--normalize_combined_version() {- local value="${1:-}"- local normalized="${value#v}"- if [[ ! "$normalized" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then- err "--version requires a semantic version like 0.2.9 or v0.2.9"- exit 1- fi- COMBINED_PLUGIN_VERSION="v${normalized}"- COMBINED_OPENVIKING_VERSION="${normalized}"-}--if [[ "$VERSION_ALIAS_EXPLICIT" == "1" ]]; then- if [[ "$PLUGIN_VERSION_ARG_EXPLICIT" == "1" || "$OPENVIKING_VERSION_ARG_EXPLICIT" == "1" ]]; then- err "--version cannot be used together with --plugin-version or --openviking-version"- exit 1- fi- normalize_combined_version "$VERSION_ALIAS"- PLUGIN_VERSION="${COMBINED_PLUGIN_VERSION}"- OPENVIKING_VERSION="${COMBINED_OPENVIKING_VERSION}"- PLUGIN_VERSION_EXPLICIT="1"-fi--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"- if [[ "$LANG_UI" == "zh" ]]; then- echo "$zh"- else- echo "$en"- 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 or --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] No interactive TTY detected. Falling back to defaults (-y)."- else- 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'-BOLD='\033[1m'-NC='\033[0m'--info() { echo -e "${GREEN}[INFO]${NC} $1"; }-warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }-err() { echo -e "${RED}[ERROR]${NC} $1"; }-bold() { echo -e "${BOLD}$1${NC}"; }--# Detect OS-detect_os() {- case "$(uname -s)" in- Linux*) OS="linux";;- Darwin*) OS="macos";;- CYGWIN*|MINGW*|MSYS*) OS="windows";;- *) OS="unknown";;- esac- if [[ "$OS" == "windows" ]]; then- err "Windows is not supported by this installer yet. Please follow the docs for manual setup."- exit 1- fi-}--# Detect Linux distro-detect_distro() {- DISTRO="unknown"- if [[ -f /etc/os-release ]]; then- . /etc/os-release 2>/dev/null || true- case "${ID:-}" in- ubuntu|debian|linuxmint) DISTRO="debian";;- fedora|rhel|centos|rocky|almalinux|openeuler) DISTRO="rhel";;- esac- fi- if command -v apt &>/dev/null; then- DISTRO="debian"- elif command -v dnf &>/dev/null || command -v yum &>/dev/null; then- DISTRO="rhel"- fi-}--# ---- Workdir detection & mode selection ------detect_openclaw_instances() {- local instances=()- for dir in "${HOME_DIR}"/.openclaw*; do- [[ -d "$dir" ]] || continue- # skip workspace/data subdirectories- [[ "$(basename "$dir")" == .openclaw-* ]] || [[ "$(basename "$dir")" == ".openclaw" ]] || continue- instances+=("$dir")- done- echo "${instances[@]}"-}--select_workdir() {- # Already set via --workdir- [[ -n "$OPENCLAW_DIR" && "$OPENCLAW_DIR" != "${HOME_DIR}/.openclaw" ]] && return 0-- local instances=($(detect_openclaw_instances))-- # Only default instance or none 鈥?keep default- if [[ ${#instances[@]} -le 1 ]]; then- return 0- fi-- # Multiple instances found 鈥?let user pick- if [[ "$INSTALL_YES" != "1" ]]; then- echo ""- bold "Found multiple OpenClaw instances:"- local i=1- for inst in "${instances[@]}"; do- echo " ${i}) ${inst}"- i=$((i + 1))- done- echo ""- 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 "Invalid selection, using default"- OPENCLAW_DIR="${instances[0]}"- fi- else- OPENCLAW_DIR="${instances[0]}"- fi- PLUGIN_DEST="${OPENCLAW_DIR}/extensions/openviking"- fi-}--select_mode() {- if [[ "$INSTALL_YES" == "1" ]]; then- SELECTED_MODE="remote"- return 0- fi- echo ""- read -r -p "$(tr "Plugin mode - local or remote [remote]: " "插件模式 - local 或 remote [remote]: ")" _mode < /dev/tty || true- _mode="${_mode:-remote}"- if [[ "$_mode" == "remote" ]]; then- SELECTED_MODE="remote"- else- SELECTED_MODE="local"- fi-}--collect_remote_config() {- remote_base_url="http://127.0.0.1:1933"- 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 "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}"- remote_api_key="${_api_key:-}"- remote_agent_id="${_agent_id:-}"- fi-}--# ---- 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。")"- 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。")"- return 1- fi- echo "ok|$out|$py"- return 0-}--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。")"- 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。")"- return 1- fi- echo "ok|$out|node"- return 0-}--# Print guidance for missing dependencies-print_install_hints() {- local missing=("$@")- bold "\n============================================================"- bold " $(tr "Environment check failed. Install missing dependencies first:" "环境校验未通过,请先安装以下缺失项:")"- bold "============================================================\n"-- for item in "${missing[@]}"; do- local name="${item%%|*}"- local rest="${item#*|}"- err "$(tr "Missing: $name" "缺失: $name")"- [[ -n "$rest" ]] && echo " $rest"- echo ""- done-- detect_distro- echo "Based on your system (${DISTRO}), you can run:"- echo ""-- if printf '%s\n' "${missing[@]}" | grep -q "Python"; then- 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 # verify >= 3.10"- echo ""- fi-- if printf '%s\n' "${missing[@]}" | grep -q "Node"; then- 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 # verify >= v22"- echo ""- fi-- 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 "Checking OpenViking runtime environment..."- echo ""-- local missing=()- local r-- r=$(check_python) || missing+=("Python 3.10+ | $(echo "$r" | cut -d'|' -f3)")- if [[ "${r%%|*}" == "ok" ]]; then- 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) OK"- fi-- if [[ ${#missing[@]} -gt 0 ]]; then- echo ""- print_install_hints "${missing[@]}"- fi-- echo ""- info "$(tr "Environment check passed." "环境校验通过。")"- echo ""-}--# ---- 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}$ ]]-}--pick_latest_plugin_tag() {- local latest_semver=""- local first_tag=""- local tag=""- while IFS= read -r tag; do- [[ -z "$tag" ]] && continue- [[ -z "$first_tag" ]] && first_tag="$tag"- if is_semver_like "$tag"; then- if [[ -z "$latest_semver" ]] || version_gte "$tag" "$latest_semver"; then- latest_semver="$tag"- fi- fi- done-- if [[ -n "$latest_semver" ]]; then- printf '%s\n' "$latest_semver"- return 0- fi-- if [[ -n "$first_tag" ]]; then- printf '%s\n' "$first_tag"- fi-}--resolve_default_plugin_version() {- [[ -n "$PLUGIN_VERSION" ]] && return 0-- info "$(tr "No plugin version specified; resolving latest tag from ${REPO}..." "未指定插件版本,正在解析 ${REPO} 的最新 tag...")"-- local latest_tag=""- local api_tags=""- api_tags="$(- curl -fsSL --connect-timeout 10 \- -H "Accept: application/vnd.github+json" \- -H "User-Agent: openviking-installer" \- "https://api.github.com/repos/${REPO}/tags?per_page=100" 2>/dev/null \- | tr -d '\r' \- | grep -oE '"name":"[^"]+"' \- | sed -E 's/^"name":"(.*)"$/\1/' \- || true- )"- if [[ -n "$api_tags" ]]; then- latest_tag="$(printf '%s\n' "$api_tags" | pick_latest_plugin_tag)"- fi-- if [[ -z "$latest_tag" ]] && command -v git >/dev/null 2>&1; then- local git_tags=""- git_tags="$(- git ls-remote --tags --refs "https://github.com/${REPO}.git" 2>/dev/null \- | sed -E 's#^.*refs/tags/##' \- || true- )"- if [[ -n "$git_tags" ]]; then- latest_tag="$(printf '%s\n' "$git_tags" | pick_latest_plugin_tag)"- fi- fi-- if [[ -z "$latest_tag" ]]; then- err "$(tr "Could not resolve the latest tag for ${REPO}." "无法解析 ${REPO} 的最新 tag。")"- echo "$(tr "Please rerun with --plugin-version <tag>, or use --plugin-version main to track the branch head explicitly." "请使用 --plugin-version <tag> 重新执行;如果需要显式跟踪分支头,请使用 --plugin-version main。")"- exit 1- fi-- PLUGIN_VERSION="$latest_tag"- info "$(tr "Resolved default plugin version to latest tag: ${PLUGIN_VERSION}" "已将默认插件版本解析为最新 tag: ${PLUGIN_VERSION}")"-}--# 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 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)")"- return 0- fi- info "$(tr "Checking OpenClaw..." "正在检查 OpenClaw...")"- if command -v openclaw >/dev/null 2>&1; then- info "$(tr "OpenClaw detected." "已检测到 OpenClaw。")"- return 0- fi-- err "OpenClaw not found. Install it manually, then rerun this script."- echo ""- echo "Recommended command:"- echo " npm install -g openclaw --registry ${NPM_REGISTRY}"- echo ""- 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}"-- # Determine package spec- local pkg_spec="openviking"- if [[ -n "$OPENVIKING_VERSION" ]]; then- pkg_spec="openviking==${OPENVIKING_VERSION}"- info "$(tr "Installing or upgrading OpenViking ${OPENVIKING_VERSION} from PyPI..." "正在安装或升级 OpenViking ${OPENVIKING_VERSION} (PyPI)...")"- else- info "$(tr "Installing or upgrading 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=""- 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 --upgrade --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 安装完成。")"- 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 "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 "Installing OpenViking with --break-system-packages (OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1)"- if "$py" -m pip install --upgrade --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 "OpenViking installed (system)"- return 0- fi- fi- 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"- local venv_py="${venv_dir}/bin/python"-- # 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 "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 "OpenViking installed (venv)"- return 0- fi-- local venv_ok=0- # Try 1: stdlib venv with ensurepip (needs python3-venv); errors suppressed to avoid confusing "ensurepip not available" message- if "$py" -m venv "${venv_dir}" 2>/dev/null; then- venv_ok=1- fi-- # Try 2: venv --without-pip then bootstrap pip via get-pip.py (no ensurepip needed; works when Try 1 fails)- if [[ "$venv_ok" -eq 0 ]]; then- rm -rf "${venv_dir}" 2>/dev/null || true- info "$(tr "Creating venv without system pip, then installing pip..." "正在创建无系统 pip 的虚拟环境并安装 pip...")"- if "$py" -m venv --without-pip "${venv_dir}" 2>/dev/null; then- info "$(tr "Venv created without pip; bootstrapping pip (using index: ${PIP_INDEX_URL})..." "已创建无 pip 的虚拟环境,正在安装 pip(使用镜像: ${PIP_INDEX_URL})...")"- local get_pip get_pip_url- get_pip=$(mktemp -t get-pip.XXXXXX.py 2>/dev/null || echo "/tmp/get-pip.py")- # 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 "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"- fi- if ! curl -fsSL --connect-timeout 15 --max-time 120 "${get_pip_url}" -o "${get_pip}" 2>/dev/null; then- if [[ "${get_pip_url}" != "https://bootstrap.pypa.io/get-pip.py" ]]; then- curl -fsSL --connect-timeout 15 --max-time 120 "https://bootstrap.pypa.io/get-pip.py" -o "${get_pip}" 2>/dev/null || true- fi- fi- if [[ -s "${get_pip}" ]] && PIP_INDEX_URL="${PIP_INDEX_URL}" "$venv_py" "${get_pip}" -q 2>/dev/null; then- venv_ok=1- fi- rm -f "${get_pip}" 2>/dev/null || true- fi- fi-- # Try 3: virtualenv (if already installed or installable with --user)- if [[ "$venv_ok" -eq 0 ]]; then- rm -rf "${venv_dir}" 2>/dev/null || true- if "$py" -m virtualenv "${venv_dir}" 2>/dev/null; then- venv_ok=1- elif "$py" -m pip install --user virtualenv -i "${PIP_INDEX_URL}" -q 2>/dev/null && "$py" -m virtualenv "${venv_dir}" 2>/dev/null; then- venv_ok=1- fi- fi-- if [[ "$venv_ok" -eq 0 ]]; then- 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 "Could not create venv. Install venv then re-run:"- echo " sudo apt install python${py_ver}-venv # or python3-full"- echo ""- 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}" >/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 "OpenViking installed (venv)"- return 0- fi-- 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}"-- local workspace="${OPENVIKING_DIR}/data"- local server_port="${DEFAULT_SERVER_PORT}"- local vlm_model="${DEFAULT_VLM_MODEL}"- local embedding_model="${DEFAULT_EMBED_MODEL}"- 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"-- if [[ "$INSTALL_YES" == "1" && -f "${conf_path}" ]]; then- SELECTED_SERVER_PORT="$(readPortFromOvConf "${conf_path}" || true)"- [[ -z "${SELECTED_SERVER_PORT}" ]] && SELECTED_SERVER_PORT="${DEFAULT_SERVER_PORT}"- SELECTED_CONFIG_PATH="${conf_path}"- info "$(tr "Preserved existing config: ${conf_path}" "已保留现有配置: ${conf_path}")"- return 0- fi-- if [[ "$INSTALL_YES" != "1" ]]; then- echo ""- read -r -p "$(tr "OpenViking workspace path [${workspace}]: " "OpenViking 数据目录 [${workspace}]: ")" _workspace < /dev/tty || true- read -r -p "OpenViking HTTP port [${server_port}]: " _server_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}"- vlm_model="${_vlm_model:-$vlm_model}"- embedding_model="${_embedding_model:-$embedding_model}"- vlm_api_key="${_vlm_api_key:-$vlm_api_key}"- embedding_api_key="${_embedding_api_key:-$embedding_api_key}"- fi-- server_port="$(normalize_port "${server_port}" "${DEFAULT_SERVER_PORT}" "OpenViking HTTP port")"- mkdir -p "${workspace}"- 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}" \- 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": {- "backend": "local",- "timeout": 10,- },- },- "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,- },-}--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}/${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 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 url="${gh_raw}/examples/${plugin_dir}/${name}"- local ok=0- echo -n " [${i}/${total}] ${name} "- local attempt=1- while [[ "$attempt" -le "${max_retries}" ]]; do- if curl -fsSL --connect-timeout 15 --max-time 120 -# -o "${PLUGIN_DEST}/${name}" "${url}" 2>/dev/null; then- ok=1- break- fi- [[ "$attempt" -lt "${max_retries}" ]] && sleep 2- attempt=$((attempt + 1))- done- if [[ "$ok" -eq 1 ]]; then- echo " OK"- else- echo ""- err "$(tr "Download failed after ${max_retries} retries: ${url}" "下载失败(已重试 ${max_retries} 次): ${url}")"- exit 1- fi- done-- # 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 "$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 plugin config for the selected mode- if [[ "$SELECTED_MODE" == "local" ]]; then- 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.${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.${plugin_id}.config.apiKey" "${remote_api_key}"- fi- if [[ -n "${remote_agent_id}" ]]; then- "${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 插件配置完成")"-}--_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}'-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 "OpenClaw + OpenViking Installer"- echo ""-- detect_os- ensure_plugin_only_operation_args- select_workdir- if [[ "$ROLLBACK_LAST_UPGRADE" == "1" ]]; then- info "Target: ${OPENCLAW_DIR}"- info "Repository: ${REPO}"- info "Mode: rollback last plugin upgrade"- if [[ "$PLUGIN_VERSION_EXPLICIT" == "1" ]]; then- warn "--plugin-version is ignored in --rollback mode."- fi- rollback_last_upgrade_operation- return 0- fi- resolve_default_plugin_version- validate_requested_plugin_version- info "Target: ${OPENCLAW_DIR}"- info "Repository: ${REPO}"- info "Plugin version: ${PLUGIN_VERSION}"- [[ -n "$OPENVIKING_VERSION" ]] && info "OpenViking version: ${OPENVIKING_VERSION}"-- 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 [[ "$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-- 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-- 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 " 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 "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 "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 "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 "Remote server: ${remote_base_url}"- fi- echo ""-}--main "$@"diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex c1dc1a09f..541ca76ed 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -4,30 +4,15 @@"kind": "context-engine","description": "OpenClaw context-engine plugin for memory management — powered by OpenViking","uiHints": {- "mode": {- "label": "Mode",- "help": "local = plugin starts OpenViking (like Claude Code); remote = use existing HTTP server"- },- "configPath": {- "label": "Config path (local)",- "placeholder": "~/.openviking/ov.conf",- "help": "Path to ov.conf when mode is local"- },- "port": {- "label": "Port (local)",- "placeholder": "1933",- "help": "Port for local OpenViking server",- "advanced": true- },"baseUrl": {- "label": "OpenViking Base URL (remote)",+ "label": "OpenViking Base URL","placeholder": "http://127.0.0.1:1933","help": "HTTP URL when mode is remote (or ${OPENVIKING_BASE_URL})"},- "agentId": {- "label": "Agent ID",- "placeholder": "random unique ID",- "help": "OpenViking agent identity. default: follow OpenClaw ctx.agentId. Non-default: use `<this>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-), so the configured value acts as a prefix."+ "agent_prefix": {+ "label": "Agent Prefix",+ "placeholder": "auto-generated",+ "help": "OpenViking agent prefix. default: follow OpenClaw ctx.agentId. Non-default: use `<prefix>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-), so the configured value acts as a prefix."},"serverAuthMode": {"label": "Server Auth Mode",@@ -157,7 +142,7 @@},"logFindRequests": {"label": "Log find requests",- "help": "Log tenant routing: /search/find + session messages/commit (X-OpenViking-*; not apiKey). Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1. Local mode: subprocess stderr at info when enabled.",+ "help": "Log tenant routing: /search/find + session messages/commit (X-OpenViking-*; not apiKey). Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1.","advanced": true}},@@ -165,20 +150,15 @@"type": "object","additionalProperties": false,"properties": {- "mode": {- "type": "string"- },- "configPath": {+ "baseUrl": {"type": "string"},- "port": {- "type": "number"- },- "baseUrl": {+ "agent_prefix": {"type": "string"},"agentId": {- "type": "string"+ "type": "string",+ "description": "Deprecated: use agent_prefix instead"},"serverAuthMode": {"type": "string"diff --git a/examples/openclaw-plugin/process-manager.ts b/examples/openclaw-plugin/process-manager.tsindex 69690912b..ec09dac76 100644--- a/examples/openclaw-plugin/process-manager.ts+++ b/examples/openclaw-plugin/process-manager.ts@@ -1,9 +1,5 @@-import { readFileSync, existsSync } from "node:fs";import { Socket } from "node:net";-import { platform } from "node:os";-import { launchProcess, runSync, sysEnv, getEnv, parseWindowsEnvBatPythonPath, parsePosixEnvPythonPath } from "./runtime-utils.js";--export const IS_WIN = platform() === "win32";+import { launchProcess } from "./runtime-utils.js";export function waitForHealth(baseUrl: string, timeoutMs: number, intervalMs: number): Promise<void> {const deadline = Date.now() + timeoutMs;@@ -151,45 +147,12 @@ export async function quickHealthCheck(baseUrl: string, timeoutMs: number): Prom}export async function quickRecallPrecheck(- mode: "local" | "remote",baseUrl: string,- defaultPort: number,- localProcess: ReturnType<typeof launchProcess> | null,): Promise<{ ok: true } | { ok: false; reason: string }> {const healthOk = await quickHealthCheck(baseUrl, 500);if (healthOk) {return { ok: true };}-- let host = "127.0.0.1";- let port = defaultPort;- try {- const parsed = new URL(baseUrl);- if (parsed.hostname) {- host = parsed.hostname;- }- if (parsed.port) {- const parsedPort = Number(parsed.port);- if (Number.isFinite(parsedPort) && parsedPort > 0) {- port = parsedPort;- }- }- } catch {- // Keep defaults when baseUrl is malformed.- }-- if (mode === "local") {- const portOk = await quickTcpProbe(host, port, 200);- if (!portOk) {- return { ok: false, reason: `local port unavailable (${host}:${port})` };- }- if (localProcess && (localProcess.killed || localProcess.exitCode !== null || localProcess.signalCode !== null)) {- return { ok: false, reason: "local process is not running" };- }- if (localProcess === null) {- return { ok: true };- }- }return { ok: false, reason: "health check failed" };}@@ -197,232 +160,3 @@ export interface ProcessLogger {info?: (msg: string) => void;warn?: (msg: string) => void;}--/**- * Prepare a port for local OpenViking startup.- *- * 1. If the port hosts an OpenViking instance (health check passes) → kill it, return same port.- * 2. If the port is occupied by something else → auto-find the next free port.- * 3. If the port is free → return it as-is.- */-export async function prepareLocalPort(- port: number,- logger: ProcessLogger,- maxRetries: number = 10,-): Promise<number> {- const isOpenViking = await quickHealthCheck(`http://127.0.0.1:${port}`, 2000);- if (isOpenViking) {- logger.info?.(`openviking: killing stale OpenViking on port ${port}`);- await killProcessOnPort(port, logger);- return port;- }-- const occupied = await quickTcpProbe("127.0.0.1", port, 500);- if (!occupied) {- return port;- }-- // Port occupied by non-OpenViking process — find next free port- logger.warn?.(`openviking: port ${port} is occupied by another process, searching for a free port...`);- for (let candidate = port + 1; candidate <= port + maxRetries; candidate++) {- if (candidate > 65535) break;- const taken = await quickTcpProbe("127.0.0.1", candidate, 300);- if (!taken) {- logger.info?.(`openviking: using free port ${candidate} instead of ${port}`);- return candidate;- }- }- throw new Error(- `openviking: port ${port} is occupied and no free port found in range ${port + 1}-${port + maxRetries}`,- );-}--function killProcessOnPort(port: number, logger: ProcessLogger): Promise<void> {- return IS_WIN ? killProcessOnPortWin(port, logger) : killProcessOnPortUnix(port, logger);-}--async function killProcessOnPortWin(port: number, logger: ProcessLogger): Promise<void> {- try {- const netstatOut = runSync(- `netstat -ano | findstr "LISTENING" | findstr ":${port}"`,- { encoding: "utf-8", shell: "cmd.exe" },- ).trim();- if (!netstatOut) return;- const pids = new Set<number>();- for (const line of netstatOut.split(/\r?\n/)) {- const m = line.trim().match(/\s(\d+)\s*$/);- if (m) pids.add(Number(m[1]));- }- for (const pid of pids) {- if (pid > 0) {- logger.info?.(`openviking: killing pid ${pid} on port ${port}`);- try { runSync(`taskkill /PID ${pid} /F`, { encoding: "utf-8", shell: "cmd.exe" }); } catch { /* already gone */ }- }- }- if (pids.size) await new Promise((r) => setTimeout(r, 500));- } catch { /* netstat not available or no stale process */ }-}--async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promise<void> {- try {- let pids: number[] = [];- try {- const lsofOut = runSync(`lsof -ti tcp:${port} -s tcp:listen 2>/dev/null || true`, {- encoding: "utf-8",- shell: "/bin/sh",- }).trim();- if (lsofOut) pids = lsofOut.split(/\s+/).map((s) => Number(s)).filter((n) => n > 0);- } catch { /* lsof not available */ }- if (pids.length === 0) {- try {- const ssOut = runSync(- `ss -tlnp 2>/dev/null | awk -v p=":${port}" '$4 ~ p {gsub(/.*pid=/,""); gsub(/,.*/,""); print; exit}'`,- { encoding: "utf-8", shell: "/bin/sh" },- ).trim();- if (ssOut) {- const n = Number(ssOut);- if (n > 0) pids = [n];- }- } catch { /* ss not available */ }- }- for (const pid of pids) {- logger.info?.(`openviking: killing pid ${pid} on port ${port}`);- try { globalThis["process"].kill(pid, "SIGKILL"); } catch { /* already gone */ }- }- if (pids.length) await new Promise((r) => setTimeout(r, 500));- } catch { /* port check failed */ }-}--export function resolvePythonCommand(logger: ProcessLogger): string {- const defaultPy = IS_WIN ? "python" : "python3";- let pythonCmd = getEnv("OPENVIKING_PYTHON");-- if (!pythonCmd) {- const { join } = require("node:path") as typeof import("node:path");- const { homedir } = require("node:os") as typeof import("node:os");- const defaultDir = join(homedir(), ".openclaw");- const profileDir = getEnv("OPENCLAW_STATE_DIR");- const searchDirs = profileDir && profileDir !== defaultDir- ? [profileDir, defaultDir]- : [defaultDir];- for (const dir of searchDirs) {- if (pythonCmd) break;- if (IS_WIN) {- const envBat = join(dir, "openviking.env.bat");- if (existsSync(envBat)) {- try {- const content = readFileSync(envBat, "utf-8");- const parsed = parseWindowsEnvBatPythonPath(content);- if (parsed) pythonCmd = parsed;- } catch { /* ignore */ }- }- } else {- const envFile = join(dir, "openviking.env");- if (existsSync(envFile)) {- try {- const content = readFileSync(envFile, "utf-8");- const parsed = parsePosixEnvPythonPath(content);- if (parsed) pythonCmd = parsed;- } catch { /* ignore */ }- }- }- }- }-- if (!pythonCmd) {- if (IS_WIN) {- try {- pythonCmd = runSync("where python", { encoding: "utf-8", shell: "cmd.exe" }).split(/\r?\n/)[0].trim();- } catch {- pythonCmd = "python";- }- } else {- try {- pythonCmd = runSync("command -v python3 || which python3", {- encoding: "utf-8",- env: sysEnv(),- shell: "/bin/sh",- }).trim();- } catch {- pythonCmd = "python3";- }- }- }-- if (pythonCmd === defaultPy) {- logger.info?.(- `openviking: 未解析到 ${defaultPy} 路径,将用 "${defaultPy}"。若 openviking 在自定义 Python 下,请设置 OPENVIKING_PYTHON` +- (IS_WIN ? ' 或 call "%USERPROFILE%\\.openclaw\\openviking.env.bat"' : " 或 source ~/.openclaw/openviking.env"),- );- }-- return pythonCmd;-}--export const __test__ = {- parseWindowsEnvBatPythonPath,-};--// ----------------------------------------------------------------------------// Local runtime pre-flight check (detect only, never auto-install)-// -----------------------------------------------------------------------------function checkPythonVersion(pythonCmd: string): { ok: boolean; version?: string; error?: string } {- try {- const out = runSync(- `"${pythonCmd}" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"`,- { encoding: "utf-8", shell: IS_WIN ? "cmd.exe" : "/bin/sh" },- ).trim();- const [major, minor] = out.split(".").map(Number);- if (major < 3 || (major === 3 && minor < 10)) {- return { ok: false, error: `Python ${out} too old, need >= 3.10` };- }- return { ok: true, version: out };- } catch {- return { ok: false, error: "Python not found or failed to execute" };- }-}--function isOpenVikingImportable(pythonCmd: string): boolean {- try {- runSync(`"${pythonCmd}" -c "import openviking"`, {- encoding: "utf-8",- shell: IS_WIN ? "cmd.exe" : "/bin/sh",- });- return true;- } catch {- return false;- }-}--export interface CheckRuntimeResult {- pythonCmd: string;- installed: boolean;- configExists: boolean;-}--/**- * Pre-startup check for local mode: verify Python >= 3.10 and that the- * openviking package is importable. Does NOT auto-install anything — if- * the package is missing, the caller should warn the user to install it- * manually (e.g. `pip install openviking`).- */-export function checkLocalRuntime(- pythonCmd: string,- configPath: string,- logger: ProcessLogger,-): CheckRuntimeResult {- const pyCheck = checkPythonVersion(pythonCmd);- if (!pyCheck.ok) {- logger.warn?.(`openviking: runtime check — ${pyCheck.error}`);- return { pythonCmd, installed: false, configExists: existsSync(configPath) };- }- logger.info?.(`openviking: Python ${pyCheck.version} ✓`);-- const installed = isOpenVikingImportable(pythonCmd);- if (installed) {- logger.info?.("openviking: package detected ✓");- }-- return { pythonCmd, installed, configExists: existsSync(configPath) };-}diff --git a/examples/openclaw-plugin/runtime-utils.ts b/examples/openclaw-plugin/runtime-utils.tsindex e08370a00..87fe2f3e3 100644--- a/examples/openclaw-plugin/runtime-utils.ts+++ b/examples/openclaw-plugin/runtime-utils.ts@@ -28,13 +28,3 @@ export function sysEnv(): NodeJS.ProcessEnv {export function getEnv(key: string): string | undefined {return _env.env[key];}--export function parseWindowsEnvBatPythonPath(content: string): string | null {- const match = content.match(/set\s+"?OPENVIKING_PYTHON=([^"\r\n]+)"?/i);- return match?.[1]?.trim() || null;-}--export function parsePosixEnvPythonPath(content: string): string | null {- const match = content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);- return match?.[1]?.trim() || null;-}diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.jsindex 53fa80ae0..0a6152774 100755--- a/examples/openclaw-plugin/setup-helper/install.js+++ b/examples/openclaw-plugin/setup-helper/install.js@@ -1,6 +1,6 @@#!/usr/bin/env node/**- * OpenClaw + OpenViking cross-platform installer+ * OpenClaw OpenViking plugin installer (remote OpenViking server — does not install Python/OpenViking server).** One-liner (after npm publish; use package name + bin name):* npx -p openclaw-openviking-setup-helper ov-install [ -y ] [ --zh ] [ --workdir PATH ]@@ -11,21 +11,17 @@** Direct run:* node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --upgrade-plugin ]- * [ --plugin-version=TAG ] [ --openviking-version=V ] [ --version=V ] [ --repo=PATH ]+ * [ --plugin-version=TAG ]** Environment variables:- * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING- * OPENVIKING_VERSION Pip install openviking==VERSION (omit to follow release plugin version when possible)- * OPENVIKING_REPO Repo path: source install (pip -e) + local plugin (default: off)- * NPM_REGISTRY, PIP_INDEX_URL- * OPENVIKING_VLM_API_KEY, OPENVIKING_EMBEDDING_API_KEY, OPENVIKING_ARK_API_KEY- * OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES (Linux)+ * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_INSTALL_YES, SKIP_OPENCLAW+ * NPM_REGISTRY*/import { spawn } from "node:child_process";import { cp, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";import { existsSync, readdirSync } from "node:fs";-import { basename, dirname, join, relative } from "node:path";+import { basename, dirname, join } from "node:path";import { createInterface } from "node:readline";import { fileURLToPath } from "node:url";@@ -37,9 +33,6 @@ const pluginVersionEnv = (process.env.PLUGIN_VERSION || process.env.BRANCH || ""let PLUGIN_VERSION = pluginVersionEnv;let pluginVersionExplicit = Boolean(pluginVersionEnv);const NPM_REGISTRY = process.env.NPM_REGISTRY || "https://registry.npmmirror.com";-const DEFAULT_PIP_INDEX_URL = "https://mirrors.volces.com/pypi/simple/";-const OFFICIAL_PIP_INDEX_URL = "https://pypi.org/simple/";-const PIP_INDEX_URL = process.env.PIP_INDEX_URL || DEFAULT_PIP_INDEX_URL;const IS_WIN = process.platform === "win32";const HOME = process.env.HOME || process.env.USERPROFILE || "";@@ -48,13 +41,6 @@ const DEFAULT_OPENCLAW_DIR = join(HOME, ".openclaw");let OPENCLAW_DIR = DEFAULT_OPENCLAW_DIR;let PLUGIN_DEST = ""; // Will be set after resolving plugin config-const OPENVIKING_DIR = join(HOME, ".openviking");--const DEFAULT_SERVER_PORT = 1933;-const DEFAULT_AGFS_PORT = 1833;-const DEFAULT_VLM_MODEL = "doubao-seed-2-0-pro-260215";-const DEFAULT_EMBED_MODEL = "doubao-embedding-vision-251215";-// Fallback configs for old versions without manifestconst FALLBACK_LEGACY = {dir: "openclaw-memory-plugin",@@ -71,7 +57,7 @@ const FALLBACK_CURRENT = {id: "openviking",kind: "context-engine",slot: "contextEngine",- required: ["index.ts", "config.ts", "package.json"],+ required: ["index.ts", "config.ts", "package.json", "openclaw.plugin.json"],optional: ["context-engine.ts","client.ts",@@ -80,7 +66,6 @@ const FALLBACK_CURRENT = {"text-utils.ts","tool-call-id.ts","session-transcript-repair.ts",- "openclaw.plugin.json","tsconfig.json","package-lock.json",".gitignore",@@ -106,23 +91,15 @@ 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 combinedVersion = "";-let combinedVersionExplicit = false;-let pluginVersionArgExplicit = false;-let openvikingVersionArgExplicit = false;let showCurrentVersion = false;-let selectedMode = "remote";-let selectedServerPort = DEFAULT_SERVER_PORT;+const selectedMode = "remote";let remoteBaseUrl = "http://127.0.0.1:1933";let remoteApiKey = "";-let remoteAgentId = "";-let openvikingPythonPath = "";+let remoteAgentPrefix = "";let upgradeRuntimeConfig = null;let installedUpgradeState = null;let upgradeAudit = null;@@ -169,7 +146,6 @@ for (let i = 0; i < argv.length; i++) {}PLUGIN_VERSION = version;pluginVersionExplicit = true;- pluginVersionArgExplicit = true;continue;}if (arg === "--plugin-version") {@@ -180,51 +156,9 @@ for (let i = 0; i < argv.length; i++) {}PLUGIN_VERSION = version;pluginVersionExplicit = true;- pluginVersionArgExplicit = true;- i += 1;- continue;- }- if (arg.startsWith("--openviking-version=")) {- openvikingVersion = arg.slice("--openviking-version=".length).trim();- openvikingVersionArgExplicit = true;- 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;- openvikingVersionArgExplicit = true;- i += 1;- continue;- }- if (arg.startsWith("--version=")) {- const version = arg.slice("--version=".length).trim();- if (!version) {- console.error("--version requires a value");- process.exit(1);- }- combinedVersion = version;- combinedVersionExplicit = true;- continue;- }- if (arg === "--version") {- const version = argv[i + 1]?.trim();- if (!version) {- console.error("--version requires a value");- process.exit(1);- }- combinedVersion = version;- combinedVersionExplicit = true;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;@@ -245,74 +179,20 @@ for (let i = 0; i < argv.length; i++) {}}-if (combinedVersionExplicit) {- if (pluginVersionArgExplicit || openvikingVersionArgExplicit) {- console.error("--version cannot be used together with --plugin-version or --openviking-version");- process.exit(1);- }- const normalizedVersion = normalizeCombinedVersion(combinedVersion);- PLUGIN_VERSION = normalizedVersion.pluginVersion;- openvikingVersion = normalizedVersion.openvikingVersion;- pluginVersionExplicit = true;-}-function setOpenClawDir(dir) {OPENCLAW_DIR = dir;}-function normalizeCombinedVersion(version) {- const value = (version || "").trim();- if (!/^(v)?\d+(\.\d+){1,2}$/.test(value)) {- console.error("--version requires a semantic version like 0.2.9 or v0.2.9");- process.exit(1);- }- const openvikingVersionValue = value.startsWith("v") ? value.slice(1) : value;- return {- pluginVersion: `v${openvikingVersionValue}`,- openvikingVersion: openvikingVersionValue,- };-}--function deriveOpenvikingVersionFromPluginVersion(version) {- const value = (version || "").trim();- if (!isSemverLike(value)) {- return "";- }- return value.startsWith("v") ? value.slice(1) : value;-}--function syncOpenvikingVersionWithPluginVersion(reason = "") {- if (openvikingVersion) {- return;- }-- const derivedVersion = deriveOpenvikingVersionFromPluginVersion(PLUGIN_VERSION);- if (!derivedVersion) {- return;- }-- openvikingVersion = derivedVersion;- info(tr(- `No OpenViking version specified; syncing runtime version to plugin version ${PLUGIN_VERSION}${reason ? ` (${reason})` : ""}.`,- `未指定 OpenViking 版本;已将运行时版本同步为插件版本 ${PLUGIN_VERSION}${reason ? `(${reason})` : ""}。`,- ));-}--syncOpenvikingVersionWithPluginVersion("requested plugin version");-function printHelp() {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(" --version=V Shorthand for --plugin-version=vV and --openviking-version=V");console.log(" --plugin-version=TAG Plugin version (Git tag, e.g. v0.2.9, default: latest tag)");- console.log(" --openviking-version=V OpenViking PyPI version (e.g. 0.2.9, default: match plugin release version)");console.log(" --workdir PATH OpenClaw config directory (default: ~/.openclaw)");- console.log(" --current-version Print installed plugin/OpenViking versions and exit");- console.log(" --repo=PATH Use local OpenViking repo at PATH (pip -e + local plugin)");+ console.log(" --current-version Print installed plugin version and exit");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(" Upgrade only the plugin to the requested --plugin-version; keeps existing plugin runtime config");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)");@@ -327,7 +207,7 @@ function printHelp() {console.log(" node install.js --current-version");console.log("");console.log(" # Install a specific release version");- console.log(" node install.js --version=0.2.9");+ console.log(" node install.js --plugin-version=v0.2.9");console.log("");console.log(" # Install from a fork repository");console.log(" node install.js --github-repo=yourname/OpenViking --plugin-version=dev-branch");@@ -341,7 +221,7 @@ function printHelp() {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");+ console.log("Env: REPO, PLUGIN_VERSION, SKIP_OPENCLAW, NPM_REGISTRY");}function formatCliArg(value) {@@ -435,62 +315,6 @@ function runCapture(cmd, args, opts = {}) {});}-function runLiveCapture(cmd, args, opts = {}) {- return new Promise((resolve) => {- const child = spawn(cmd, args, {- stdio: ["ignore", "pipe", "pipe"],- shell: opts.shell ?? false,- ...opts,- });- let out = "";- let errOut = "";- child.stdout?.on("data", (chunk) => {- const text = String(chunk);- out += text;- process.stdout.write(text);- });- child.stderr?.on("data", (chunk) => {- const text = String(chunk);- errOut += text;- process.stderr.write(text);- });- child.on("error", (error) => {- resolve({ code: -1, out: "", err: String(error) });- });- child.on("close", (code) => {- resolve({ code, out: out.trim(), err: errOut.trim() });- });- });-}--function shouldFallbackToOfficialPypi(output) {- if (process.env.PIP_INDEX_URL?.trim()) return false;- if (PIP_INDEX_URL !== DEFAULT_PIP_INDEX_URL) return false;-- return /Could not find a version that satisfies the requirement|No matching distribution found|HTTP error 404|too many 502 error responses|Temporary failure in name resolution|Failed to establish a new connection|Connection (?:timed out|reset by peer)|Read timed out|ProxyError|SSLError|TLSV1_ALERT|Remote end closed connection/i.test(output);-}--async function runPipInstallWithFallback(py, pipArgs, opts = {}) {- const shell = opts.shell ?? false;- const primaryResult = await runLiveCapture(py, [...pipArgs, "-i", PIP_INDEX_URL], { shell });- if (primaryResult.code === 0) {- return { result: primaryResult, usedFallback: false };- }-- const primaryOutput = `${primaryResult.out}\n${primaryResult.err}`;- if (!shouldFallbackToOfficialPypi(primaryOutput)) {- return { result: primaryResult, usedFallback: false };- }-- warn(tr(- `Install from mirror failed. Retrying with official PyPI: ${OFFICIAL_PIP_INDEX_URL}`,- `镜像源安装失败,正在回退到官方 PyPI: ${OFFICIAL_PIP_INDEX_URL}`,- ));-- const fallbackResult = await runLiveCapture(py, [...pipArgs, "-i", OFFICIAL_PIP_INDEX_URL], { shell });- return { result: fallbackResult, usedFallback: true, primaryResult, fallbackResult };-}-function question(prompt, defaultValue = "") {const rl = createInterface({ input: process.stdin, output: process.stdout });const suffix = defaultValue ? ` [${defaultValue}]` : "";@@ -502,50 +326,6 @@ 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 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 {- ok: false,- detail: tr("Python not found or failed. Install Python >= 3.10.", "Python 未找到或执行失败,请安装 Python >= 3.10"),- cmd: py,- };- }- const [major, minor] = result.out.split(".").map(Number);- if (major < 3 || (major === 3 && minor < 10)) {- return {- ok: false,- detail: tr(`Python ${result.out} is too old. Need >= 3.10.`, `Python ${result.out} 版本过低,需要 >= 3.10`),- cmd: py,- };- }- return { ok: true, detail: result.out, cmd: py };-}--async function checkNode() {- const result = await runCapture("node", ["-v"], { shell: IS_WIN });- if (result.code !== 0 || !result.out) {- return { ok: false, detail: tr("Node.js not found. Install Node.js >= 22.", "Node.js 未找到,请安装 Node.js >= 22") };- }- const major = Number.parseInt(result.out.replace(/^v/, "").split(".")[0], 10);- if (!Number.isFinite(major) || major < 22) {- return { ok: false, detail: tr(`Node.js ${result.out} is too old. Need >= 22.`, `Node.js ${result.out} 版本过低,需要 >= 22`) };- }- return { ok: true, detail: result.out };-}-function detectOpenClawInstances() {const instances = [];try {@@ -588,64 +368,11 @@ async function selectWorkdir() {}}-async function selectMode() {- if (installYes) {- selectedMode = "remote";- return;- }- const mode = (await question(tr("Plugin mode - local or remote", "插件模式 - local 或 remote"), "remote")).toLowerCase();- selectedMode = mode === "remote" ? "remote" : "local";-}-async function collectRemoteConfig() {if (installYes) return;remoteBaseUrl = await question(tr("OpenViking server URL", "OpenViking 服务器地址"), remoteBaseUrl);remoteApiKey = await question(tr("API Key (optional)", "API Key(可选)"), remoteApiKey);- remoteAgentId = await question(tr("Agent ID (optional)", "Agent ID(可选)"), remoteAgentId);-}--async function validateEnvironment() {- info(tr("Checking OpenViking runtime environment...", "正在校验 OpenViking 运行环境..."));- console.log("");-- const missing = [];-- const python = await checkPython();- if (python.ok) {- info(` Python: ${python.detail} ✓`);- } else {- missing.push(`Python 3.10+ | ${python.detail}`);- }-- const node = await checkNode();- if (node.ok) {- info(` Node.js: ${node.detail} ✓`);- } else {- missing.push(`Node.js 22+ | ${node.detail}`);- }-- if (missing.length > 0) {- console.log("");- err(tr("Environment check failed. Install missing dependencies first.", "环境校验未通过,请先安装以下缺失组件。"));- console.log("");- if (missing.some((item) => item.startsWith("Python"))) {- console.log(tr("Python (example):", "Python(示例):"));- if (IS_WIN) console.log(" winget install --id Python.Python.3.11 -e");- else console.log(" pyenv install 3.11.12 && pyenv global 3.11.12");- console.log("");- }- if (missing.some((item) => item.startsWith("Node"))) {- console.log(tr("Node.js (example):", "Node.js(示例):"));- if (IS_WIN) console.log(" nvm install 22.22.0 && nvm use 22.22.0");- else console.log(" nvm install 22 && nvm use 22");- console.log("");- }- process.exit(1);- }-- console.log("");- info(tr("Environment check passed ✓", "环境校验通过 ✓"));- console.log("");+ remoteAgentPrefix = await question(tr("Agent Prefix (optional)", "Agent Prefix(可选)"), remoteAgentPrefix);}async function checkOpenClaw() {@@ -704,18 +431,6 @@ if (upgradePluginOnly && rollbackLastUpgrade) {process.exit(1);}-function ensurePluginOnlyOperationArgs() {- if ((upgradePluginOnly || rollbackLastUpgrade) && openvikingVersion) {- err(- tr(- "Plugin-only upgrade/rollback does not support --openviking-version or --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 或 --version。请使用 --plugin-version 指定插件版本;如果需要调整 OpenViking 服务版本,请执行完整安装流程。",- ),- );- process.exit(1);- }-}-// Detect OpenClaw versionasync function detectOpenClawVersion() {try {@@ -819,7 +534,6 @@ async function resolveDefaultPluginVersion() {const latestTag = pickLatestPluginTag(payload.map((item) => item?.name || ""));if (latestTag) {PLUGIN_VERSION = latestTag;- syncOpenvikingVersionWithPluginVersion("latest plugin tag");info(tr(`Resolved default plugin version to latest tag: ${PLUGIN_VERSION}`,`已将默认插件版本解析为最新 tag: ${PLUGIN_VERSION}`,@@ -844,7 +558,6 @@ async function resolveDefaultPluginVersion() {const latestTag = pickLatestPluginTag(parseGitLsRemoteTags(gitResult.out));if (latestTag) {PLUGIN_VERSION = latestTag;- syncOpenvikingVersionWithPluginVersion("latest plugin tag");info(tr(`Resolved default plugin version via git tags: ${PLUGIN_VERSION}`,`已通过 git tag 解析默认插件版本: ${PLUGIN_VERSION}`,@@ -1016,243 +729,6 @@ async function checkOpenClawCompatibility() {}}-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)"));- return;- }-- const python = await checkPython();- if (!python.cmd) {- 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;-- if (openvikingRepo && existsSync(join(openvikingRepo, "pyproject.toml"))) {- info(tr(`Installing OpenViking from source (editable): ${openvikingRepo}`, `正在从源码安装 OpenViking(可编辑): ${openvikingRepo}`));- await run(py, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { silent: true });- await run(py, ["-m", "pip", "install", "-e", openvikingRepo]);- openvikingPythonPath = py;- info(tr("OpenViking installed ✓ (source)", "OpenViking 安装完成 ✓(源码)"));- return;- }-- // Determine package spec- const pkgSpec = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";- if (openvikingVersion) {- info(tr(`Installing or upgrading OpenViking ${openvikingVersion} from PyPI...`, `正在安装或升级 OpenViking ${openvikingVersion} (PyPI)...`));- } else {- info(tr("Installing or upgrading OpenViking (latest) from PyPI...", "正在安装或升级 OpenViking (最新版) (PyPI)..."));- }- info(tr(`Using pip index: ${PIP_INDEX_URL}`, `使用 pip 镜像源: ${PIP_INDEX_URL}`));-- info(`Package: ${pkgSpec}`);- await runCapture(py, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });- const { result: installResult } = await runPipInstallWithFallback(- py,- ["-m", "pip", "install", "--upgrade", "--progress-bar", "on", pkgSpec],- { shell: false },- );- if (installResult.code === 0) {- openvikingPythonPath = py;- info(tr("OpenViking installed ✓", "OpenViking 安装完成 ✓"));- return;- }-- const installOutput = `${installResult.out}\n${installResult.err}`;- const shouldTryVenv = !IS_WIN && /externally-managed-environment|externally managed|No module named pip/i.test(installOutput);- if (shouldTryVenv) {- const venvDir = join(OPENVIKING_DIR, "venv");- const venvPy = IS_WIN ? join(venvDir, "Scripts", "python.exe") : join(venvDir, "bin", "python");-- if (existsSync(venvPy)) {- const reuseCheck = await runCapture(venvPy, ["-c", "import openviking"], { shell: false });- if (reuseCheck.code === 0) {- const { result: venvReuseInstall } = await runPipInstallWithFallback(- venvPy,- ["-m", "pip", "install", "--progress-bar", "on", "-U", pkgSpec],- { shell: false },- );- if (venvReuseInstall.code !== 0) {- err(tr("OpenViking install failed in venv.", "在虚拟环境中安装 OpenViking 失败。"));- console.log(venvReuseInstall.err || venvReuseInstall.out);- process.exit(1);- }- openvikingPythonPath = venvPy;- info(tr("OpenViking installed ✓ (venv)", "OpenViking 安装完成 ✓(虚拟环境)"));- return;- }- }-- await mkdir(OPENVIKING_DIR, { recursive: true });- const venvCreate = await runCapture(py, ["-m", "venv", venvDir], { shell: false });- if (venvCreate.code !== 0) {- console.log("");- err(tr("Cannot create Python virtual environment.", "无法创建 Python 虚拟环境。"));- console.log(tr(- " python3-venv is not installed. Fix with:",- " python3-venv 未安装,请执行以下命令修复:"- ));- console.log(`- apt update- apt install -y software-properties-common- add-apt-repository universe- apt update- apt install -y python3-venv-`);- console.log(tr(- " Or force install into system Python (not recommended):",- " 或强制安装到系统 Python(不推荐):"- ));- console.log(` OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1 ov-install\n`);- process.exit(1);- }-- await runCapture(venvPy, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });- const { result: venvInstall } = await runPipInstallWithFallback(- venvPy,- ["-m", "pip", "install", "--upgrade", "--progress-bar", "on", pkgSpec],- { shell: false },- );- if (venvInstall.code === 0) {- openvikingPythonPath = venvPy;- info(tr("OpenViking installed ✓ (venv)", "OpenViking 安装完成 ✓(虚拟环境)"));- return;- }-- err(tr("OpenViking install failed in venv.", "在虚拟环境中安装 OpenViking 失败。"));- console.log(venvInstall.err || venvInstall.out);- process.exit(1);- }-- if (process.env.OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES === "1") {- const { result: systemInstall } = await runPipInstallWithFallback(- py,- ["-m", "pip", "install", "--upgrade", "--progress-bar", "on", "--break-system-packages", pkgSpec],- { shell: false },- );- if (systemInstall.code === 0) {- openvikingPythonPath = py;- info(tr("OpenViking installed ✓ (system)", "OpenViking 安装完成 ✓(系统)"));- return;- }- }-- err(tr("OpenViking install failed. Check Python >= 3.10 and pip.", "OpenViking 安装失败,请检查 Python >= 3.10 及 pip"));- console.log(installResult.err || installResult.out);- process.exit(1);-}--async function configureOvConf() {- await mkdir(OPENVIKING_DIR, { recursive: true });-- const configPath = join(OPENVIKING_DIR, "ov.conf");- if (installYes && existsSync(configPath)) {- selectedServerPort = await readPortFromOvConf(configPath) || DEFAULT_SERVER_PORT;- info(- tr(- `Preserved existing config: ${configPath}`,- `已保留现有配置: ${configPath}`,- ),- );- return;- }-- let workspace = join(OPENVIKING_DIR, "data");- let serverPort = String(DEFAULT_SERVER_PORT);- let agfsPort = String(DEFAULT_AGFS_PORT);- let vlmModel = DEFAULT_VLM_MODEL;- let embeddingModel = DEFAULT_EMBED_MODEL;- let vlmApiKey = process.env.OPENVIKING_VLM_API_KEY || process.env.OPENVIKING_ARK_API_KEY || "";- let embeddingApiKey = process.env.OPENVIKING_EMBEDDING_API_KEY || process.env.OPENVIKING_ARK_API_KEY || "";-- if (!installYes) {- console.log("");- workspace = await question(tr("OpenViking workspace path", "OpenViking 数据目录"), workspace);- serverPort = await question(tr("OpenViking HTTP port", "OpenViking HTTP 端口"), serverPort);- agfsPort = await question(tr("AGFS port", "AGFS 端口"), agfsPort);- vlmModel = await question(tr("VLM model", "VLM 模型"), vlmModel);- embeddingModel = await question(tr("Embedding model", "Embedding 模型"), embeddingModel);- console.log(tr("VLM and Embedding API keys can differ. Leave empty to edit ov.conf later.", "说明:VLM 与 Embedding 的 API Key 可分别填写,留空可稍后在 ov.conf 修改。"));- const vlmInput = await question(tr("VLM API key (optional)", "VLM API Key(可留空)"), "");- const embInput = await question(tr("Embedding API key (optional)", "Embedding API Key(可留空)"), "");- if (vlmInput) vlmApiKey = vlmInput;- if (embInput) embeddingApiKey = embInput;- }-- selectedServerPort = Number.parseInt(serverPort, 10) || DEFAULT_SERVER_PORT;- const agfsPortNum = Number.parseInt(agfsPort, 10) || DEFAULT_AGFS_PORT;-- await mkdir(workspace, { recursive: true });-- const config = {- server: {- host: "127.0.0.1",- port: selectedServerPort,- root_api_key: null,- cors_origins: ["*"],- },- storage: {- workspace,- vectordb: { name: "context", backend: "local", project: "default" },- agfs: { port: agfsPortNum, log_level: "warn", backend: "local", timeout: 10, retry_times: 3 },- },- log: {- level: "WARNING",- format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s",- output: "file",- rotation: true,- rotation_days: 3,- rotation_interval: "midnight",- },- embedding: {- dense: {- provider: "volcengine",- api_key: embeddingApiKey || null,- model: embeddingModel,- api_base: "https://ark.cn-beijing.volces.com/api/v3",- dimension: 1024,- input: "multimodal",- },- },- vlm: {- provider: "volcengine",- api_key: vlmApiKey || null,- model: vlmModel,- api_base: "https://ark.cn-beijing.volces.com/api/v3",- temperature: 0.1,- max_retries: 3,- },- };-- await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");- info(tr(`Config generated: ${configPath}`, `已生成配置: ${configPath}`));-}-function getOpenClawConfigPath() {return join(OPENCLAW_DIR, "openclaw.json");}@@ -1274,51 +750,11 @@ function getInstallStatePathForPlugin(pluginId) {return join(OPENCLAW_DIR, "extensions", pluginId, ".ov-install-state.json");}-async function detectInstalledOpenVikingVersion() {- const pythonCandidates = [];- const configuredPython = process.env.OPENVIKING_PYTHON?.trim();- if (configuredPython) {- pythonCandidates.push(configuredPython);- }-- const envCandidates = IS_WIN- ? [join(OPENCLAW_DIR, "openviking.env.ps1"), join(OPENCLAW_DIR, "openviking.env.bat")]- : [join(OPENCLAW_DIR, "openviking.env")];-- for (const envPath of envCandidates) {- if (!existsSync(envPath)) continue;- const raw = await readFile(envPath, "utf8").catch(() => "");- if (!raw) continue;- const match = raw.match(/OPENVIKING_PYTHON(?:\s*=\s*|=)['"]?([^'"\r\n]+)['"]?/);- const pythonPath = match?.[1]?.trim();- if (pythonPath) {- pythonCandidates.push(pythonPath);- }- }-- for (const candidate of IS_WIN ? ["py", "python", "python3"] : ["python3", "python"]) {- pythonCandidates.push(candidate);- }-- const seen = new Set();- for (const candidate of pythonCandidates) {- if (!candidate || seen.has(candidate)) continue;- seen.add(candidate);- const result = await runCapture(candidate, ["-c", "import openviking; print(openviking.__version__)"], { shell: IS_WIN });- if (result.code === 0) {- return result.out.trim();- }- }-- return "";-}-async function printCurrentVersionInfo() {const state = await readJsonFileIfExists(getInstallStatePathForPlugin("openviking"));const pluginRequestedRef = state?.requestedRef || "";const pluginReleaseId = state?.releaseId || "";const pluginInstalledAt = state?.installedAt || "";- const openvikingInstalledVersion = await detectInstalledOpenVikingVersion();console.log("");bold(tr("Installed versions", "当前已安装版本"));@@ -1328,7 +764,7 @@ async function printCurrentVersionInfo() {if (pluginRequestedRef && pluginReleaseId && pluginRequestedRef !== pluginReleaseId) {console.log(`Plugin requested ref: ${pluginRequestedRef}`);}- console.log(`OpenViking: ${openvikingInstalledVersion || "unknown"}`);+ console.log(tr("OpenViking server: not installed by this tool (use a remote URL in plugin config)", "OpenViking 服务端:本工具不安装;请在插件配置中填写远程服务地址"));if (pluginInstalledAt) {console.log(`Installed at: ${pluginInstalledAt}`);}@@ -1346,10 +782,6 @@ 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;}@@ -1435,46 +867,19 @@ function formatTargetVersionLabel() {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;+ const runtime = {};+ if (typeof entryConfig.baseUrl === "string" && entryConfig.baseUrl.trim()) {+ runtime.baseUrl = entryConfig.baseUrl.trim();}-- if (typeof entryConfig.configPath === "string" && entryConfig.configPath.trim()) {- runtime.configPath = entryConfig.configPath.trim();+ if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) {+ runtime.apiKey = entryConfig.apiKey;}- 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;- }+ if (typeof entryConfig.agent_prefix === "string" && entryConfig.agent_prefix.trim()) {+ runtime.agent_prefix = entryConfig.agent_prefix.trim();}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();@@ -1607,7 +1012,7 @@ async function rollbackLastUpgradeOperation() {info(tr("Run `openclaw gateway` and `openclaw status` to verify the restored plugin state.", "请运行 `openclaw gateway` 和 `openclaw status` 验证恢复后的插件状态。"));}-async function prepareUpgradeRuntimeConfig(installedState) {+function prepareUpgradeRuntimeConfig(installedState) {const plugins = installedState.config?.plugins ?? {};const candidateOrder = installedState.detections.map((item) => item.variant)@@ -1623,16 +1028,11 @@ async function prepareUpgradeRuntimeConfig(installedState) {}if (!runtime) {- runtime = { mode: "local" };- }-- if (runtime.mode === "remote") {- runtime.baseUrl = runtime.baseUrl || remoteBaseUrl;- return runtime;+ runtime = {};}- runtime.configPath = runtime.configPath || join(OPENVIKING_DIR, "ov.conf");- runtime.port = runtime.port || await readPortFromOvConf(runtime.configPath) || DEFAULT_SERVER_PORT;+ delete runtime.mode;+ runtime.baseUrl = runtime.baseUrl || remoteBaseUrl;return runtime;}@@ -1759,24 +1159,19 @@ async function prepareStrongPluginUpgrade() {}installedUpgradeState = installedState;- upgradeRuntimeConfig = await prepareUpgradeRuntimeConfig(installedState);+ upgradeRuntimeConfig = 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}`));+ remoteBaseUrl = upgradeRuntimeConfig.baseUrl || remoteBaseUrl;+ remoteApiKey = upgradeRuntimeConfig.apiKey || "";+ remoteAgentPrefix = upgradeRuntimeConfig.agent_prefix || "";+ info(tr(`Upgrade runtime mode: ${selectedMode} (remote OpenViking server)`, `升级运行模式: ${selectedMode}(远程 OpenViking 服务)`));info(tr(`Upgrade path: ${fromVersion} -> ${toVersion}`, `升级路径: ${fromVersion} -> ${toVersion}`));@@ -1804,8 +1199,8 @@ async function prepareStrongPluginUpgrade() {info(tr(- "Upgrade will keep the existing OpenViking runtime file and re-apply only the minimum plugin runtime settings.",- "升级将保留现有 OpenViking 运行时文件,并只回填最小插件运行配置。",+ "Upgrade will preserve existing plugin server connection settings where possible and re-apply minimal remote plugin config.",+ "升级将尽可能保留已有的插件服务端连接信息,并只回填最少的远程插件配置。",),);info(tr(`Upgrade audit file: ${getUpgradeAuditPath()}`, `升级审计文件: ${getUpgradeAuditPath()}`));@@ -1909,36 +1304,20 @@ async function downloadPlugin(destDir) {info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));}-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";- },- });-}--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 });+ const stagingPrefix = `.${pluginId}.staging-`;+ try {+ const entries = readdirSync(extensionsDir, { withFileTypes: true });+ for (const entry of entries) {+ if (entry.isDirectory() && entry.name.startsWith(stagingPrefix)) {+ await rm(join(extensionsDir, entry.name), { recursive: true, force: true });+ }+ }+ } catch {}+ const stagingDir = join(extensionsDir, `${stagingPrefix}${process.pid}-${Date.now()}`);await mkdir(stagingDir, { recursive: true });return stagingDir;}@@ -2027,22 +1406,9 @@ async function scrubStaleOpenClawPluginRegistration() {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 插件..."));@@ -2088,27 +1454,18 @@ async function configureOpenClawPlugin({return;}- const effectiveRuntimeConfig = runtimeConfig || (- selectedMode === "remote"- ? { mode: "remote", baseUrl: remoteBaseUrl, apiKey: remoteApiKey, agentId: remoteAgentId }- : { mode: "local", configPath: join(OPENVIKING_DIR, "ov.conf"), port: selectedServerPort }- );+ const effectiveRuntimeConfig = runtimeConfig || {+ baseUrl: remoteBaseUrl,+ apiKey: remoteApiKey,+ agent_prefix: remoteAgentPrefix,+ };- // Set plugin config for the selected mode- 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.${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 (effectiveRuntimeConfig.agentId) {- await oc(["config", "set", `plugins.entries.${pluginId}.config.agentId`, effectiveRuntimeConfig.agentId]);- }+ 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 (effectiveRuntimeConfig.agent_prefix) {+ await oc(["config", "set", `plugins.entries.${pluginId}.config.agent_prefix`, effectiveRuntimeConfig.agent_prefix]);}// Legacy (memory) plugins need explicit targetUri/autoRecall/autoCapture (new version has defaults in config.ts)@@ -2121,75 +1478,9 @@ async function configureOpenClawPlugin({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();- return python.cmd || "";-}--async function writeOpenvikingEnv({ includePython }) {+async function writeOpenvikingEnv() {const needStateDir = OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR;- 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;+ if (!needStateDir) return null;await mkdir(OPENCLAW_DIR, { recursive: true });@@ -2197,14 +1488,8 @@ async function writeOpenvikingEnv({ includePython }) {const batLines = ["@echo off"];const psLines = [];- if (needStateDir) {- batLines.push(`set "OPENCLAW_STATE_DIR=${OPENCLAW_DIR.replace(/"/g, '""')}"`);- psLines.push(`$env:OPENCLAW_STATE_DIR = "${OPENCLAW_DIR.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);- }- if (pythonPath) {- batLines.push(`set "OPENVIKING_PYTHON=${pythonPath.replace(/"/g, '""')}"`);- psLines.push(`$env:OPENVIKING_PYTHON = "${pythonPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);- }+ batLines.push(`set "OPENCLAW_STATE_DIR=${OPENCLAW_DIR.replace(/"/g, '""')}"`);+ psLines.push(`$env:OPENCLAW_STATE_DIR = "${OPENCLAW_DIR.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);const batPath = join(OPENCLAW_DIR, "openviking.env.bat");const ps1Path = join(OPENCLAW_DIR, "openviking.env.ps1");@@ -2215,16 +1500,12 @@ async function writeOpenvikingEnv({ includePython }) {return { shellPath: batPath, powershellPath: ps1Path };}- const lines = [];- if (needStateDir) {- lines.push(`export OPENCLAW_STATE_DIR='${OPENCLAW_DIR.replace(/'/g, "'\"'\"'")}'`);- }- if (pythonPath) {- lines.push(`export OPENVIKING_PYTHON='${pythonPath.replace(/'/g, "'\"'\"'")}'`);- }-const envPath = join(OPENCLAW_DIR, "openviking.env");- await writeFile(envPath, `${lines.join("\n")}\n`, "utf8");+ await writeFile(+ envPath,+ `export OPENCLAW_STATE_DIR='${OPENCLAW_DIR.replace(/'/g, "'\"'\"'")}'\n`,+ "utf8",+ );info(tr(`Environment file generated: ${envPath}`, `已生成环境文件: ${envPath}`));return { shellPath: envPath };}@@ -2252,24 +1533,11 @@ function getExistingEnvFiles() {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 一键安装"));+ bold(tr("🦣 OpenClaw OpenViking plugin installer", "🦣 OpenClaw OpenViking 插件安装"));console.log("");- ensurePluginOnlyOperationArgs();await selectWorkdir();if (showCurrentVersion) {await printCurrentVersionInfo();@@ -2288,15 +1556,9 @@ async function main() {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}`));- }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: plugin upgrade only", "模式: 仅升级插件"));}info(tr(`Mode: ${selectedMode}`, `模式: ${selectedMode}`));@@ -2305,15 +1567,6 @@ async function main() {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();@@ -2321,25 +1574,12 @@ async function main() {await collectRemoteConfig();}- let pluginPath;- 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}`));- await deployPluginFromLocal(pluginPath);- info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));- pluginPath = PLUGIN_DEST;- } else {- await deployPluginFromRemote();- pluginPath = PLUGIN_DEST;- }+ await deployPluginFromRemote();await configureOpenClawPlugin(upgradePluginOnly? {runtimeConfig: upgradeRuntimeConfig,- skipGatewayMode: true,claimSlot: installedUpgradeState ? shouldClaimTargetSlot(installedUpgradeState) : true,}: { preserveExistingConfig: false },@@ -2356,11 +1596,9 @@ async function main() {}let envFiles = getExistingEnvFiles();if (!upgradePluginOnly) {- envFiles = await writeOpenvikingEnv({- includePython: selectedMode === "local",- });+ envFiles = await writeOpenvikingEnv();} else if (!envFiles && OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {- envFiles = await writeOpenvikingEnv({ includePython: false });+ envFiles = await writeOpenvikingEnv();}console.log("");@@ -2379,30 +1617,14 @@ async function main() {console.log("");}- if (selectedMode === "local") {- info(tr("Run these commands to start OpenClaw + OpenViking:", "请按以下命令启动 OpenClaw + OpenViking:"));- } else {- info(tr("Run these commands to start OpenClaw:", "请按以下命令启动 OpenClaw:"));- }+ info(tr("Run these commands to start OpenClaw:", "请按以下命令启动 OpenClaw:"));console.log(` 1) ${wrapCommand("openclaw --version", envFiles)}`);console.log(` 2) ${wrapCommand("openclaw onboard", envFiles)}`);console.log(` 3) ${wrapCommand("openclaw gateway", envFiles)}`);console.log(` 4) ${wrapCommand("openclaw status", envFiles)}`);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}`));- }+ info(tr(`OpenViking server URL (plugin): ${remoteBaseUrl}`, `OpenViking 服务地址(插件): ${remoteBaseUrl}`));console.log("");}diff --git a/examples/openclaw-plugin/setup-helper/package.json b/examples/openclaw-plugin/setup-helper/package.jsonindex 419d25033..81e040fcc 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.15",+ "version": "0.2.16-dev.4","description": "Setup helper for installing OpenViking memory plugin into OpenClaw","type": "module","bin": {diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.mdindex c8b167131..782928b36 100644--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md@@ -57,12 +57,9 @@ Example: User says "Forget my phone number"| Field | Default | Description ||-------|---------|-------------|-| `mode` | `remote` | `local` (start local server) or `remote` (connect to remote) |-| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL (remote mode) |+| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL || `apiKey` | — | OpenViking API Key (optional) |-| `agentId` | `default` | Identifies this agent to OpenViking |-| `configPath` | `~/.openviking/ov.conf` | Config file path (local mode) |-| `port` | `1933` | Local server port (local mode) |+| `agent_prefix` | `default` | Agent prefix identifying this instance to OpenViking || `targetUri` | `viking://user/memories` | Default search scope || `autoCapture` | `true` | Automatically capture memories || `captureMode` | `semantic` | Capture mode: `semantic` / `keyword` |@@ -74,10 +71,7 @@ Example: User says "Forget my phone number"## Daily Operations```bash-# Start (local mode: source env first)-source ~/.openclaw/openviking.env && openclaw gateway--# Start (remote mode: no env needed)+# Startopenclaw gateway# Check status@@ -98,9 +92,6 @@ Restart the gateway after changing the slot.If you have multiple OpenClaw instances, use `--workdir` to target a specific one:```bash-# Install script-curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second-# Setup helpernpx ./examples/openclaw-plugin/setup-helper --workdir ~/.openclaw-openclaw-second@@ -112,7 +103,7 @@ OPENCLAW_STATE_DIR=~/.openclaw-openclaw-second openclaw config set ...| Symptom | Cause | Fix ||---------|-------|-----|-| `extracted 0 memories` | Wrong API Key or model name | Check `api_key` and `model` in `ov.conf` |-| `port occupied` | Port used by another process | Change port: `openclaw config set plugins.entries.openviking.config.port 1934` |-| Plugin not loaded | Env file not sourced or slot not configured | Check `openclaw status` output |+| `extracted 0 memories` | Wrong API Key or model name | Check server-side VLM and embedding configuration |+| Cannot connect to OpenViking | `baseUrl` is wrong or service is down | Verify `baseUrl` and test connectivity |+| Plugin not loaded | Slot not configured | Check `openclaw status` output || Inaccurate recall | recallScoreThreshold too low | Increase threshold or adjust recallLimit |diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.tsindex da44b7dfe..f7978ec9a 100644--- a/examples/openclaw-plugin/tests/ut/config.test.ts+++ b/examples/openclaw-plugin/tests/ut/config.test.ts@@ -1,6 +1,4 @@import { describe, expect, it, vi, afterEach } from "vitest";-import { homedir } from "node:os";-import { join, resolve as resolvePath } from "node:path";import { memoryOpenVikingConfigSchema } from "../../config.js";@@ -13,8 +11,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {it("empty object uses all defaults", () => {const cfg = memoryOpenVikingConfigSchema.parse({});- expect(cfg.mode).toBe("local");- expect(cfg.port).toBe(1933);+ expect(cfg.mode).toBe("remote");expect(cfg.recallLimit).toBe(6);expect(cfg.recallScoreThreshold).toBe(0.15);expect(cfg.autoCapture).toBe(true);@@ -26,7 +23,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.captureMode).toBe("semantic");expect(cfg.captureMaxLength).toBe(24000);expect(cfg.recallMaxContentChars).toBe(5000);- expect(cfg.agentId).toBe("default");+ expect(cfg.agent_prefix).toBe("default");expect(cfg.serverAuthMode).toBe("api_key");expect(cfg.isolateUserScopeByAgent).toBe(false);expect(cfg.isolateAgentScopeByUser).toBe(false);@@ -79,16 +76,6 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {).toThrow("unknown keys");});- it("clamps port below 1 to 1", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ port: 0 });- expect(cfg.port).toBe(1);- });-- it("clamps port above 65535 to 65535", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ port: 99999 });- expect(cfg.port).toBe(65535);- });-it("resolves environment variables in apiKey", () => {process.env.TEST_OV_API_KEY = "sk-test-key-123";const cfg = memoryOpenVikingConfigSchema.parse({@@ -121,28 +108,12 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.recallScoreThreshold).toBe(1);});- it("expands tilde in configPath", () => {- const cfg = memoryOpenVikingConfigSchema.parse({- configPath: "~/custom/ov.conf",- });- const expected = resolvePath(join(homedir(), "custom", "ov.conf"));- expect(cfg.configPath).toBe(expected);- });-it("throws on invalid captureMode", () => {expect(() =>memoryOpenVikingConfigSchema.parse({ captureMode: "fast" }),).toThrow('captureMode must be "semantic" or "keyword"');});- it("local mode auto-generates baseUrl from port", () => {- const cfg = memoryOpenVikingConfigSchema.parse({- mode: "local",- port: 9999,- });- expect(cfg.baseUrl).toBe("http://127.0.0.1:9999");- });-it("trims trailing slashes from baseUrl", () => {const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",@@ -164,8 +135,8 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {it("treats undefined/null as empty config", () => {const cfg1 = memoryOpenVikingConfigSchema.parse(undefined);const cfg2 = memoryOpenVikingConfigSchema.parse(null);- expect(cfg1.mode).toBe("local");- expect(cfg2.mode).toBe("local");+ expect(cfg1.mode).toBe("remote");+ expect(cfg2.mode).toBe("remote");});it("accepts valid captureMode values", () => {@@ -189,14 +160,24 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfgHigh.recallMaxContentChars).toBe(10000);});- it("resolves agentId from configured value", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentId: " my-agent " });- expect(cfg.agentId).toBe("my-agent");+ it("resolves agent_prefix from configured value", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ agent_prefix: " my-agent " });+ expect(cfg.agent_prefix).toBe("my-agent");+ });++ it("falls back to 'default' for empty agent_prefix", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ agent_prefix: " " });+ expect(cfg.agent_prefix).toBe("default");+ });++ it("migrates legacy agentId to agent_prefix", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ agentId: "legacy-agent" });+ expect(cfg.agent_prefix).toBe("legacy-agent");});- it("falls back to 'default' for empty agentId", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentId: " " });- expect(cfg.agentId).toBe("default");+ it("agent_prefix takes precedence over legacy agentId", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ agentId: "old", agent_prefix: "new" });+ expect(cfg.agent_prefix).toBe("new");});it("parses accountId and trims whitespace", () => {@@ -228,7 +209,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {const cfg = memoryOpenVikingConfigSchema.parse({baseUrl: "http://127.0.0.1:1933",apiKey: "sk-user",- agentId: "coding-agent",+ agent_prefix: "coding-agent",});expect(cfg.accountId).toBe("");expect(cfg.userId).toBe("");diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.tsindex 130e8d117..af9602501 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts@@ -18,7 +18,6 @@ function makeEngine(opts?: {getSession?: Record<string, unknown>;addSessionMessageError?: Error;cfgOverrides?: Record<string, unknown>;- quickPrecheck?: () => Promise<{ ok: true } | { ok: false; reason: string }>;}) {const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",@@ -65,7 +64,6 @@ function makeEngine(opts?: {cfg,logger,getClient,- quickPrecheck: opts?.quickPrecheck,resolveAgentId,});@@ -133,34 +131,6 @@ describe("context-engine afterTurn()", () => {);});- it("skips immediately when local precheck reports OpenViking unavailable", async () => {- const quickPrecheck = vi.fn().mockResolvedValue({- ok: false as const,- reason: "local process is not running",- });- const { engine, client, getClient, logger } = makeEngine({- cfgOverrides: {- mode: "local",- port: 1933,- },- quickPrecheck,- });-- await engine.afterTurn!({- sessionId: "s1",- sessionFile: "",- messages: [{ role: "user", content: "hello" }],- prePromptMessageCount: 0,- });-- expect(quickPrecheck).toHaveBeenCalledTimes(1);- expect(getClient).not.toHaveBeenCalled();- expect(client.addSessionMessage).not.toHaveBeenCalled();- expect(logger.warn).toHaveBeenCalledWith(- expect.stringContaining("afterTurn precheck failed"),- );- });-it("skips when no new user/assistant messages after prePromptMessageCount", async () => {const { engine, client, logger } = makeEngine();diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex 81615f5e7..d71a05cf0 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -42,7 +42,6 @@ function makeEngine(contextResult: unknown,opts?: {cfgOverrides?: Record<string, unknown>;- quickPrecheck?: () => Promise<{ ok: true } | { ok: false; reason: string }>;},) {const logger = makeLogger();@@ -65,7 +64,6 @@ function makeEngine(cfg: localCfg,logger,getClient,- quickPrecheck: opts?.quickPrecheck,resolveAgentId,});@@ -192,47 +190,6 @@ describe("context-engine assemble()", () => {});});- it("falls back immediately when local precheck reports OpenViking unavailable", async () => {- const quickPrecheck = vi.fn().mockResolvedValue({- ok: false as const,- reason: "local process is not running",- });- const { engine, client, getClient, logger } = makeEngine(- {- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 123,- stats: makeStats(),- },- {- cfgOverrides: {- mode: "local",- port: 1933,- },- quickPrecheck,- },- );-- const liveMessages = [{ role: "user", content: "fallback live message" }];- const result = await engine.assemble({- sessionId: "session-local",- messages: liveMessages,- tokenBudget: 4096,- });-- expect(quickPrecheck).toHaveBeenCalledTimes(1);- expect(getClient).not.toHaveBeenCalled();- expect(client.getSessionContext).not.toHaveBeenCalled();- expect(result).toEqual({- messages: liveMessages,- estimatedTokens: roughEstimate(liveMessages),- });- expect(logger.warn).toHaveBeenCalledWith(- expect.stringContaining("assemble precheck failed"),- );- });-it("emits a non-error toolResult for a running tool (not a synthetic error)", async () => {const { engine } = makeEngine({latest_archive_overview: "",diff --git a/examples/openclaw-plugin/tests/ut/local-startup-bad-config-real.test.ts b/examples/openclaw-plugin/tests/ut/local-startup-bad-config-real.test.tsdeleted file mode 100644index 7ddac2110..000000000--- a/examples/openclaw-plugin/tests/ut/local-startup-bad-config-real.test.ts+++ /dev/null@@ -1,103 +0,0 @@-import { mkdtemp, writeFile, rm } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { afterEach, beforeEach, describe, expect, it } from "vitest";--import { localClientCache, localClientPendingPromises } from "../../client.js";-import plugin from "../../index.js";--describe("local OpenViking startup with a bad config", () => {- beforeEach(() => {- localClientCache.clear();- localClientPendingPromises.clear();- });-- afterEach(() => {- localClientCache.clear();- localClientPendingPromises.clear();- });-- it("fails startup quickly and keeps before_prompt_build non-blocking", async () => {- const tempDir = await mkdtemp(join(tmpdir(), "ov-bad-conf-"));- const badConfigPath = join(tempDir, "ov.conf");- await writeFile(badConfigPath, "[broken\nthis is not valid\n", "utf8");-- try {- const handlers = new Map<string, (event: unknown, ctx?: unknown) => unknown>();- let service:- | {- start: () => Promise<void>;- stop?: () => Promise<void> | void;- }- | null = null;- const logs: Array<{ level: string; message: string }> = [];- const logger = {- debug: (message: string) => logs.push({ level: "debug", message }),- error: (message: string) => logs.push({ level: "error", message }),- info: (message: string) => logs.push({ level: "info", message }),- warn: (message: string) => logs.push({ level: "warn", message }),- };-- plugin.register({- logger,- on: (name, handler) => {- handlers.set(name, handler);- },- pluginConfig: {- autoCapture: true,- autoRecall: true,- configPath: badConfigPath,- logFindRequests: false,- mode: "local",- port: 19439,- },- registerContextEngine: () => {},- registerService: (entry) => {- service = entry;- },- registerTool: () => {},- });-- expect(service).toBeTruthy();- const hook = handlers.get("before_prompt_build");- expect(hook).toBeTruthy();-- const startAt = Date.now();- const startOutcome = await Promise.race([- service!.start().then(- () => ({ kind: "resolved" as const }),- (error) => ({ error: String(error), kind: "rejected" as const }),- ),- new Promise<{ kind: "timeout" }>((resolve) => {- setTimeout(() => resolve({ kind: "timeout" }), 5_000);- }),- ]);-- expect(startOutcome.kind).toBe("rejected");- expect(Date.now() - startAt).toBeLessThan(5_000);- expect(logs.some((entry) => entry.message.includes("local mode marked unavailable"))).toBe(true);-- const hookAt = Date.now();- const hookOutcome = await Promise.race([- Promise.resolve(- hook!(- { messages: [{ content: "hello memory", role: "user" }], prompt: "hello memory" },- { agentId: "main", sessionId: "test-session", sessionKey: "agent:main:test" },- ),- ).then(() => ({ kind: "returned" as const })),- new Promise<{ kind: "timeout" }>((resolve) => {- setTimeout(() => resolve({ kind: "timeout" }), 1_500);- }),- ]);-- expect(hookOutcome.kind).toBe("returned");- expect(Date.now() - hookAt).toBeLessThan(1_500);- expect(logs.some((entry) => entry.message.includes("failed to get client"))).toBe(true);-- await service?.stop?.();- } finally {- await rm(tempDir, { force: true, recursive: true });- }- }, 15_000);-});diff --git a/examples/openclaw-plugin/tests/ut/local-startup-failure.test.ts b/examples/openclaw-plugin/tests/ut/local-startup-failure.test.tsdeleted file mode 100644index 44e83c565..000000000--- a/examples/openclaw-plugin/tests/ut/local-startup-failure.test.ts+++ /dev/null@@ -1,145 +0,0 @@-import { EventEmitter } from "node:events";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--describe("local OpenViking startup failure", () => {- beforeEach(() => {- vi.resetModules();- vi.clearAllMocks();- });-- afterEach(() => {- vi.resetModules();- });-- it("fails fast when the child exits before health is ready", async () => {- class FakeChild extends EventEmitter {- stderr = new EventEmitter();- killed = false;- exitCode: number | null = null;- signalCode: string | null = null;-- kill = vi.fn((signal: string = "SIGTERM") => {- if (this.killed || this.exitCode !== null || this.signalCode !== null) {- return true;- }- this.killed = true;- this.signalCode = signal;- this.emit("exit", null, signal);- return true;- });- }-- const waitForHealth = vi.fn(() => new Promise<void>(() => {}));- const prepareLocalPort = vi.fn(async () => 19433);- const resolvePythonCommand = vi.fn(() => "python3");- const spawn = vi.fn(() => {- const child = new FakeChild();- setTimeout(() => {- if (!child.killed && child.exitCode === null && child.signalCode === null) {- child.exitCode = 1;- child.emit("exit", 1, null);- }- }, 20);- return child;- });-- vi.doMock("node:child_process", () => ({- execSync: vi.fn(() => ""),- spawn,- }));-- vi.doMock("../../process-manager.js", async () => {- const actual = await vi.importActual<typeof import("../../process-manager.js")>(- "../../process-manager.js",- );- return {- ...actual,- IS_WIN: false,- prepareLocalPort,- resolvePythonCommand,- waitForHealth,- };- });-- const { localClientCache, localClientPendingPromises } = await import("../../client.js");- localClientCache.clear();- localClientPendingPromises.clear();-- const { default: plugin } = await import("../../index.js");- const handlers = new Map<string, (event: unknown, ctx?: unknown) => unknown>();- let service:- | {- start: () => Promise<void>;- }- | null = null;- const logs: Array<{ level: string; message: string }> = [];- const unhandled: unknown[] = [];- const onUnhandledRejection = (reason: unknown) => {- unhandled.push(reason);- };- process.on("unhandledRejection", onUnhandledRejection);- try {- const logger = {- debug: (message: string) => logs.push({ level: "debug", message }),- error: (message: string) => logs.push({ level: "error", message }),- info: (message: string) => logs.push({ level: "info", message }),- warn: (message: string) => logs.push({ level: "warn", message }),- };-- plugin.register({- logger,- on: (name, handler) => {- handlers.set(name, handler);- },- pluginConfig: {- autoCapture: true,- autoRecall: true,- configPath: "/tmp/openclaw-ovbug/bad-ov.conf",- logFindRequests: false,- mode: "local",- port: 19433,- },- registerContextEngine: vi.fn(),- registerService: (entry) => {- service = entry;- },- registerTool: vi.fn(),- });-- expect(service).toBeTruthy();- const hook = handlers.get("before_prompt_build");- expect(hook).toBeTruthy();-- const startOutcome = await Promise.race([- service!.start().then(- () => ({ kind: "resolved" as const }),- (error) => ({ error: String(error), kind: "rejected" as const }),- ),- new Promise<{ kind: "timeout" }>((resolve) => {- setTimeout(() => resolve({ kind: "timeout" }), 500);- }),- ]);-- expect(startOutcome.kind).toBe("rejected");-- const hookOutcome = await Promise.race([- Promise.resolve(- hook!(- { messages: [{ content: "hello memory", role: "user" }], prompt: "hello memory" },- { agentId: "main", sessionId: "test-session", sessionKey: "agent:main:test" },- ),- ).then(() => ({ kind: "returned" as const })),- new Promise<{ kind: "timeout" }>((resolve) => {- setTimeout(() => resolve({ kind: "timeout" }), 500);- }),- ]);-- expect(hookOutcome.kind).toBe("returned");- expect(logs.some((entry) => entry.message.includes("failed to get client"))).toBe(true);- await new Promise((resolve) => setTimeout(resolve, 0));- expect(unhandled).toEqual([]);- } finally {- process.off("unhandledRejection", onUnhandledRejection);- }- });-});diff --git a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.tsindex c84c9b129..dbe28c08b 100644--- a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts+++ b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts@@ -3,7 +3,6 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:htimport { afterEach, beforeEach, describe, expect, it } from "vitest";-import { localClientCache, localClientPendingPromises } from "../../client.js";import plugin from "../../index.js";type RequestRecord = {@@ -44,8 +43,6 @@ describe("plugin normal flow with healthy backend", () => {beforeEach(async () => {requests = [];- localClientCache.clear();- localClientPendingPromises.clear();server = createServer(async (req, res) => {const method = req.method ?? "GET";@@ -170,8 +167,6 @@ describe("plugin normal flow with healthy backend", () => {});afterEach(async () => {- localClientCache.clear();- localClientPendingPromises.clear();server.close();await once(server, "close");});