Skip to content

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

refactor(setup-helper): replace cli.js with install.js, update repo defaults (#524)

LinQiang39103d6eefe118d
diff --git a/examples/openclaw-memory-plugin/INSTALL-ZH.md b/examples/openclaw-memory-plugin/INSTALL-ZH.md
index 58a53b937..16235b232 100644
--- a/examples/openclaw-memory-plugin/INSTALL-ZH.md
+++ b/examples/openclaw-memory-plugin/INSTALL-ZH.md
@@ -4,14 +4,37 @@
---
-## 一键安装(Linux / macOS)
+## 一键安装
+
+**前置条件:** Python >= 3.10,Node.js >= 22。安装助手会自动检查并提示安装缺少的组件。
+
+### 方式 A:npm 安装(推荐,全平台)
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash
+npm install -g openclaw-openviking-setup-helper
+ov-install
```
非交互模式(使用默认配置):
+```bash
+ov-install -y
+```
+
+安装到指定 OpenClaw 实例:
+
+```bash
+ov-install --workdir ~/.openclaw-second
+```
+
+### 方式 B:curl 一键安装(Linux / macOS)
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash
+```
+
+非交互模式:
+
```bash
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash -s -y
```
@@ -65,6 +88,15 @@ python3 -m pip install openviking --upgrade
### Step 2: 运行安装助手
+#### 方式 A:npm 全局安装(推荐)
+
+```bash
+npm install -g openclaw-openviking-setup-helper
+ov-install
+```
+
+#### 方式 B:从仓库运行
+
```bash
git clone https://github.com/volcengine/OpenViking.git
cd OpenViking
diff --git a/examples/openclaw-memory-plugin/INSTALL.md b/examples/openclaw-memory-plugin/INSTALL.md
index 0907e5dbc..59cb176e3 100644
--- a/examples/openclaw-memory-plugin/INSTALL.md
+++ b/examples/openclaw-memory-plugin/INSTALL.md
@@ -4,9 +4,30 @@ Give [OpenClaw](https://github.com/openclaw/openclaw) long-term memory powered b
---
-## One-Click Install (Linux / macOS)
+## One-Click Install
-**Prerequisites:** Python >= 3.10, Node.js >= 22. The script checks these and prompts you to install any missing components.
+**Prerequisites:** Python >= 3.10, Node.js >= 22. The installer checks these and prompts you to install any missing components.
+
+### Option A: npm (recommended, all platforms)
+
+```bash
+npm install -g openclaw-openviking-setup-helper
+ov-install
+```
+
+Non-interactive mode:
+
+```bash
+ov-install -y
+```
+
+Install to a specific OpenClaw instance:
+
+```bash
+ov-install --workdir ~/.openclaw-second
+```
+
+### Option B: curl (Linux / macOS)
```bash
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash
@@ -31,7 +52,7 @@ Remote mode (connect to an existing OpenViking server, no Python/OpenViking requ
curl -fsSL ... | bash
```
-The script will: 1) select target OpenClaw instance (auto-detects multiple instances), 2) select mode (local/remote), 3) validate environment and install (local mode), 4) configure and deploy the memory plugin.
+The installer will: 1) select target OpenClaw instance (auto-detects multiple instances), 2) select mode (local/remote), 3) validate environment and install (local mode), 4) configure and deploy the memory plugin.
---
@@ -329,6 +350,21 @@ python3 -c "import openviking; print('ok')"
### 4.3 Run the Setup Helper
+#### Option A: npm global install (recommended)
+
+```bash
+npm install -g openclaw-openviking-setup-helper
+ov-install
+```
+
+Non-interactive mode:
+
+```bash
+ov-install -y
+```
+
+#### Option B: Run from repo
+
From the OpenViking repo root:
```bash
@@ -593,7 +629,15 @@ npm install -g openclaw
- Linux/macOS: `source ~/.openclaw/openviking.env`
- Windows: `call "%USERPROFILE%\.openclaw\openviking.env.bat"`
- Run `openclaw status` to check plugin state
-- Re-run setup: `npx ./examples/openclaw-memory-plugin/setup-helper`
+- Re-run setup:
+
+```bash
+# npm install (recommended)
+ov-install
+
+# or from repo
+npx ./examples/openclaw-memory-plugin/setup-helper
+```
#### `health check timeout at http://127.0.0.1:1933`
diff --git a/examples/openclaw-memory-plugin/setup-helper/cli.js b/examples/openclaw-memory-plugin/setup-helper/cli.js
deleted file mode 100755
index 20582b967..000000000
--- a/examples/openclaw-memory-plugin/setup-helper/cli.js
+++ /dev/null
@@ -1,970 +0,0 @@
-#!/usr/bin/env node
-/**
- * OpenClaw + OpenViking setup helper
- * Usage: npx openclaw-openviking-setup-helper
- * Or: npx openclaw-openviking-setup-helper --help
- */
-
-import { spawn } from "node:child_process";
-import { mkdir, writeFile, access, readFile, rm } from "node:fs/promises";
-import { createInterface } from "node:readline";
-import { join, dirname } from "node:path";
-import { fileURLToPath } from "node:url";
-import { existsSync, readdirSync } from "node:fs";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const GITHUB_RAW =
- process.env.OPENVIKING_GITHUB_RAW ||
- "https://raw.githubusercontent.com/OpenViking/OpenViking/main";
-
-const IS_WIN = process.platform === "win32";
-const IS_LINUX = process.platform === "linux";
-const HOME = process.env.HOME || process.env.USERPROFILE || "";
-let OPENCLAW_DIR = join(HOME, ".openclaw");
-const OPENVIKING_DIR = join(HOME, ".openviking");
-let EXT_DIR = join(OPENCLAW_DIR, "extensions");
-let PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
-
-// ─── Utility helpers ───
-
-function log(msg, level = "info") {
- const icons = { info: "\u2139", ok: "\u2713", err: "\u2717", warn: "\u26A0" };
- console.log(`${icons[level] || ""} ${msg}`);
-}
-
-function run(cmd, args, opts = {}) {
- return new Promise((resolve, reject) => {
- const p = spawn(cmd, args, {
- stdio: opts.silent ? "pipe" : "inherit",
- shell: opts.shell ?? true,
- ...opts,
- });
- p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`exit ${code}`))));
- });
-}
-
-function runCapture(cmd, args, opts = {}) {
- return new Promise((resolve) => {
- const p = spawn(cmd, args, {
- stdio: ["ignore", "pipe", "pipe"],
- shell: opts.shell ?? false,
- ...opts,
- });
- let out = "";
- let err = "";
- p.stdout?.on("data", (d) => (out += d));
- p.stderr?.on("data", (d) => (err += d));
- p.on("error", (e) => {
- if (e.code === "ENOENT") resolve({ code: -1, out: "", err: `command not found: ${cmd}` });
- else resolve({ code: -1, out: "", err: String(e) });
- });
- p.on("close", (code) => resolve({ code, out: out.trim(), err: err.trim() }));
- });
-}
-
-function runCaptureWithTimeout(cmd, args, timeoutMs, opts = {}) {
- return new Promise((resolve) => {
- const p = spawn(cmd, args, {
- stdio: ["ignore", "pipe", "pipe"],
- shell: opts.shell ?? false,
- ...opts,
- });
- let out = "";
- let err = "";
- let settled = false;
- const done = (result) => { if (!settled) { settled = true; resolve(result); } };
- const timer = setTimeout(() => { p.kill(); done({ code: out ? 0 : -1, out: out.trim(), err: err.trim() }); }, timeoutMs);
- p.stdout?.on("data", (d) => (out += d));
- p.stderr?.on("data", (d) => (err += d));
- p.on("error", (e) => { clearTimeout(timer); done({ code: -1, out: "", err: String(e) }); });
- p.on("close", (code) => { clearTimeout(timer); done({ code, out: out.trim(), err: err.trim() }); });
- });
-}
-
-async function question(prompt, defaultValue = "") {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- const def = defaultValue ? ` [${defaultValue}]` : "";
- return new Promise((resolve) => {
- rl.question(`${prompt}${def}: `, (answer) => {
- rl.close();
- resolve((answer ?? defaultValue).trim() || defaultValue);
- });
- });
-}
-
-async function questionApiKey(prompt) {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- return new Promise((resolve) => {
- rl.question(prompt, (answer) => {
- rl.close();
- resolve((answer ?? "").trim());
- });
- });
-}
-
-// ─── Workdir detection & mode selection ───
-
-function detectOpenclawInstances() {
- const instances = [];
- try {
- const entries = readdirSync(HOME, { withFileTypes: true });
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === ".openclaw" || entry.name.startsWith(".openclaw-")) {
- instances.push(join(HOME, entry.name));
- }
- }
- } catch {}
- return instances.sort();
-}
-
-async function selectWorkdir(nonInteractive) {
- const instances = detectOpenclawInstances();
- if (instances.length <= 1) return; // keep default
-
- if (nonInteractive) return;
-
- console.log("\nFound multiple OpenClaw instances:");
- for (let i = 0; i < instances.length; i++) {
- console.log(` ${i + 1}) ${instances[i]}`);
- }
- const choice = await question("Select instance number", "1");
- const idx = parseInt(choice, 10) - 1;
- if (idx >= 0 && idx < instances.length) {
- OPENCLAW_DIR = instances[idx];
- } else {
- log("Invalid selection, using default", "warn");
- OPENCLAW_DIR = instances[0];
- }
- EXT_DIR = join(OPENCLAW_DIR, "extensions");
- PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
-}
-
-async function selectMode(nonInteractive) {
- if (nonInteractive) return "local";
- const choice = await question("Plugin mode (local/remote)", "local");
- return choice.toLowerCase() === "remote" ? "remote" : "local";
-}
-
-async function collectRemoteConfig(nonInteractive) {
- const opts = { baseUrl: "http://127.0.0.1:1933", apiKey: "", agentId: "" };
- if (nonInteractive) return opts;
-
- opts.baseUrl = await question("OpenViking server URL", opts.baseUrl);
- opts.apiKey = (await questionApiKey("API Key (optional, leave blank to skip): ")) || "";
- opts.agentId = (await questionApiKey("Agent ID (optional, leave blank to skip): ")) || "";
- return opts;
-}
-
-// ─── Distro detection ───
-
-async function detectDistro() {
- if (IS_WIN) return "windows";
- try {
- const { out } = await runCapture("sh", ["-c", "cat /etc/os-release 2>/dev/null"]);
- const lower = out.toLowerCase();
- if (lower.includes("ubuntu") || lower.includes("debian")) return "debian";
- if (lower.includes("centos") || lower.includes("rhel") || lower.includes("openeuler") || lower.includes("fedora") || lower.includes("rocky") || lower.includes("alma")) return "rhel";
- } catch {}
- const { code: aptCode } = await runCapture("sh", ["-c", "command -v apt"]);
- if (aptCode === 0) return "debian";
- const { code: dnfCode } = await runCapture("sh", ["-c", "command -v dnf || command -v yum"]);
- if (dnfCode === 0) return "rhel";
- return "unknown";
-}
-
-// ─── Environment checks ───
-
-const DEFAULT_PYTHON = IS_WIN ? "python" : "python3";
-
-async function checkOpenclaw() {
- if (IS_WIN) {
- const { code } = await runCaptureWithTimeout("openclaw", ["--version"], 10000, { shell: true });
- return code === 0 ? { ok: true } : { ok: false };
- }
- const { code } = await runCapture("openclaw", ["--version"]);
- return code === 0 ? { ok: true } : { ok: false };
-}
-
-async function checkPython() {
- const py = process.env.OPENVIKING_PYTHON || DEFAULT_PYTHON;
- const { code, out } = await runCapture(py, ["-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"]);
- if (code !== 0) return { ok: false, version: null, cmd: py, msg: `Python not found (tried: ${py})` };
- const [major, minor] = out.split(".").map(Number);
- if (major < 3 || (major === 3 && minor < 10))
- return { ok: false, version: out, cmd: py, msg: `Python ${out} too old, need >= 3.10` };
- return { ok: true, version: out, cmd: py, msg: `${out} (${py})` };
-}
-
-async function checkGo() {
- const goDir = process.env.OPENVIKING_GO_PATH?.replace(/^~/, HOME);
- const goCmd = goDir ? join(goDir, "go") : "go";
- const { code, out } = await runCapture(goCmd, ["version"]);
- if (code !== 0) return { ok: false, version: null, msg: "Go not found" };
- const m = out.match(/go([0-9]+)\.([0-9]+)/);
- if (!m) return { ok: false, version: null, msg: "Cannot parse Go version" };
- const [, major, minor] = m.map(Number);
- if (major < 1 || (major === 1 && minor < 19))
- return { ok: false, version: `${major}.${minor}`, msg: `Go ${major}.${minor} too old, need >= 1.19` };
- return { ok: true, version: `${major}.${minor}`, msg: `${major}.${minor}` };
-}
-
-async function checkCmake() {
- const { code } = await runCapture("cmake", ["--version"]);
- return { ok: code === 0 };
-}
-
-async function checkGpp() {
- const { code } = await runCapture("g++", ["--version"]);
- return { ok: code === 0 };
-}
-
-async function checkOpenvikingModule() {
- const py = process.env.OPENVIKING_PYTHON || DEFAULT_PYTHON;
- const { code } = await runCapture(py, ["-c", "import openviking"]);
- return code === 0 ? { ok: true } : { ok: false };
-}
-
-async function checkOvvConf() {
- const cfg = process.env.OPENVIKING_CONFIG_FILE || join(OPENVIKING_DIR, "ov.conf");
- try {
- await access(cfg);
- return { ok: true, path: cfg };
- } catch {
- return { ok: false, path: cfg };
- }
-}
-
-// ─── Config helpers ───
-
-const DEFAULT_SERVER_PORT = 1933;
-const DEFAULT_AGFS_PORT = 1833;
-const DEFAULT_VLM_MODEL = "doubao-seed-2-0-pro-260215";
-const DEFAULT_EMBEDDING_MODEL = "doubao-embedding-vision-251215";
-
-const DEFAULT_WORKSPACE = join(HOME, ".openviking", "data");
-
-function buildOvvConfJson(opts = {}) {
- const {
- apiKey = "",
- serverPort = DEFAULT_SERVER_PORT,
- agfsPort = DEFAULT_AGFS_PORT,
- vlmModel = DEFAULT_VLM_MODEL,
- embeddingModel = DEFAULT_EMBEDDING_MODEL,
- workspace = DEFAULT_WORKSPACE,
- } = opts;
- return JSON.stringify({
- server: {
- host: "127.0.0.1",
- port: serverPort,
- root_api_key: null,
- cors_origins: ["*"],
- },
- storage: {
- workspace,
- vectordb: { name: "context", backend: "local", project: "default" },
- agfs: { port: agfsPort, log_level: "warn", backend: "local", timeout: 10, retry_times: 3 },
- },
- embedding: {
- dense: {
- provider: "volcengine",
- api_key: apiKey || null,
- model: embeddingModel,
- api_base: "https://ark.cn-beijing.volces.com/api/v3",
- dimension: 1024,
- input: "multimodal",
- },
- },
- vlm: {
- provider: "volcengine",
- api_key: apiKey || null,
- model: vlmModel,
- api_base: "https://ark.cn-beijing.volces.com/api/v3",
- temperature: 0.1,
- max_retries: 3,
- },
- }, null, 2);
-}
-
-function parsePort(val, defaultVal) {
- const n = parseInt(val, 10);
- return Number.isFinite(n) && n >= 1 && n <= 65535 ? n : defaultVal;
-}
-
-async function ensureOvvConf(cfgPath, opts = {}) {
- await mkdir(dirname(cfgPath), { recursive: true });
- await writeFile(cfgPath, buildOvvConfJson(opts));
- log(`Created config: ${cfgPath}`, "ok");
- if (!opts.apiKey) {
- log("API Key not set; memory features may be unavailable. Edit ov.conf to add later.", "warn");
- }
-}
-
-async function getApiKeyFromOvvConf(cfgPath) {
- let raw;
- try {
- raw = await readFile(cfgPath, "utf-8");
- const cfg = JSON.parse(raw);
- return cfg?.embedding?.dense?.api_key || "";
- } catch {
- const m = raw?.match(/api_key\s*:\s*["']?([^"'\s#]+)["']?/);
- return m ? m[1].trim() : "";
- }
-}
-
-async function getOvvConfPorts(cfgPath) {
- try {
- const raw = await readFile(cfgPath, "utf-8");
- const cfg = JSON.parse(raw);
- return {
- serverPort: cfg?.server?.port ?? DEFAULT_SERVER_PORT,
- agfsPort: cfg?.storage?.agfs?.port ?? DEFAULT_AGFS_PORT,
- };
- } catch {
- return { serverPort: DEFAULT_SERVER_PORT, agfsPort: DEFAULT_AGFS_PORT };
- }
-}
-
-async function isOvvConfInvalid(cfgPath) {
- try {
- JSON.parse(await readFile(cfgPath, "utf-8"));
- return false;
- } catch {
- return true;
- }
-}
-
-async function updateOvvConf(cfgPath, opts = {}) {
- let cfg;
- try {
- cfg = JSON.parse(await readFile(cfgPath, "utf-8"));
- } catch {
- log("ov.conf is not valid JSON, will create new config", "warn");
- await ensureOvvConf(cfgPath, opts);
- return;
- }
- if (opts.apiKey !== undefined) {
- if (!cfg.embedding) cfg.embedding = {};
- if (!cfg.embedding.dense) cfg.embedding.dense = {};
- cfg.embedding.dense.api_key = opts.apiKey || null;
- if (!cfg.vlm) cfg.vlm = {};
- cfg.vlm.api_key = opts.apiKey || null;
- }
- if (opts.vlmModel !== undefined) {
- if (!cfg.vlm) cfg.vlm = {};
- cfg.vlm.model = opts.vlmModel;
- if (!cfg.vlm.api_base) cfg.vlm.api_base = "https://ark.cn-beijing.volces.com/api/v3";
- if (!cfg.vlm.provider) cfg.vlm.provider = "volcengine";
- }
- if (opts.embeddingModel !== undefined) {
- if (!cfg.embedding) cfg.embedding = {};
- if (!cfg.embedding.dense) cfg.embedding.dense = {};
- cfg.embedding.dense.model = opts.embeddingModel;
- }
- if (opts.serverPort !== undefined && cfg.server) cfg.server.port = opts.serverPort;
- if (opts.agfsPort !== undefined && cfg.storage?.agfs) cfg.storage.agfs.port = opts.agfsPort;
- await writeFile(cfgPath, JSON.stringify(cfg, null, 2));
-}
-
-// ─── Interactive config collection ───
-
-async function collectOvvConfInteractive(nonInteractive) {
- const opts = {
- apiKey: process.env.OPENVIKING_ARK_API_KEY || "",
- serverPort: DEFAULT_SERVER_PORT,
- agfsPort: DEFAULT_AGFS_PORT,
- vlmModel: DEFAULT_VLM_MODEL,
- embeddingModel: DEFAULT_EMBEDDING_MODEL,
- workspace: DEFAULT_WORKSPACE,
- };
- if (nonInteractive) return opts;
-
- console.log("\n╔══════════════════════════════════════════════════════════╗");
- console.log("║ OpenViking Configuration (ov.conf) ║");
- console.log("╚══════════════════════════════════════════════════════════╝");
-
- console.log("\n--- Data Storage ---");
- console.log("Workspace is where OpenViking stores all data (vector database, files, etc.).");
- opts.workspace = await question(`Workspace path`, DEFAULT_WORKSPACE);
-
- console.log("\nOpenViking requires a Volcengine Ark API Key for:");
- console.log(" - Embedding model: vectorizes text for semantic search");
- console.log(" - VLM model: analyzes conversations to extract memories");
- console.log("\nGet your API Key at: https://console.volcengine.com/ark\n");
-
- opts.apiKey = (await questionApiKey("Volcengine Ark API Key (leave blank to skip, configure later): ")) || opts.apiKey;
-
- console.log("\n--- Model Configuration ---");
- console.log("VLM model is used to extract and analyze memories from conversations.");
- opts.vlmModel = await question(`VLM model name`, DEFAULT_VLM_MODEL);
-
- console.log("\nEmbedding model is used to vectorize text for semantic search.");
- opts.embeddingModel = await question(`Embedding model name`, DEFAULT_EMBEDDING_MODEL);
-
- console.log("\n--- Server Ports ---");
- const serverPortStr = await question(`OpenViking HTTP port`, String(DEFAULT_SERVER_PORT));
- opts.serverPort = parsePort(serverPortStr, DEFAULT_SERVER_PORT);
- const agfsPortStr = await question(`AGFS port`, String(DEFAULT_AGFS_PORT));
- opts.agfsPort = parsePort(agfsPortStr, DEFAULT_AGFS_PORT);
-
- return opts;
-}
-
-// ─── Installation helpers ───
-
-async function installOpenviking(repoRoot) {
- const py = process.env.OPENVIKING_PYTHON || DEFAULT_PYTHON;
- log(`Installing openviking (using ${py})...`);
- if (repoRoot && existsSync(join(repoRoot, "pyproject.toml"))) {
- await run(py, ["-m", "pip", "install", "-e", repoRoot]);
- return;
- }
- await run(py, ["-m", "pip", "install", "openviking"]);
-}
-
-async function fetchPluginFromGitHub(dest) {
- log("Downloading memory-openviking plugin from GitHub...");
- const files = [
- "examples/openclaw-memory-plugin/index.ts",
- "examples/openclaw-memory-plugin/config.ts",
- "examples/openclaw-memory-plugin/client.ts",
- "examples/openclaw-memory-plugin/process-manager.ts",
- "examples/openclaw-memory-plugin/memory-ranking.ts",
- "examples/openclaw-memory-plugin/text-utils.ts",
- "examples/openclaw-memory-plugin/openclaw.plugin.json",
- "examples/openclaw-memory-plugin/package.json",
- "examples/openclaw-memory-plugin/package-lock.json",
- "examples/openclaw-memory-plugin/tsconfig.json",
- "examples/openclaw-memory-plugin/.gitignore",
- ];
- await mkdir(dest, { recursive: true });
- for (let i = 0; i < files.length; i++) {
- const rel = files[i];
- const name = rel.split("/").pop();
- process.stdout.write(` Downloading ${i + 1}/${files.length}: ${name} ... `);
- const url = `${GITHUB_RAW}/${rel}`;
- const res = await fetch(url);
- if (!res.ok) throw new Error(`Download failed: ${url}`);
- const buf = await res.arrayBuffer();
- await writeFile(join(dest, name), Buffer.from(buf));
- process.stdout.write("\u2713\n");
- }
- log(`Plugin downloaded to ${dest}`, "ok");
- process.stdout.write(" Installing plugin deps (npm install)... ");
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: dest, silent: true });
- process.stdout.write("\u2713\n");
- log("Plugin deps installed", "ok");
-}
-
-async function fixStalePluginPaths(pluginPath) {
- const cfgPath = join(OPENCLAW_DIR, "openclaw.json");
- if (!existsSync(cfgPath)) return;
- try {
- const cfg = JSON.parse(await readFile(cfgPath, "utf8"));
- let changed = false;
- const paths = cfg?.plugins?.load?.paths;
- if (Array.isArray(paths)) {
- const cleaned = paths.filter((p) => existsSync(p));
- if (!cleaned.includes(pluginPath)) cleaned.push(pluginPath);
- if (JSON.stringify(cleaned) !== JSON.stringify(paths)) {
- cfg.plugins.load.paths = cleaned;
- changed = true;
- }
- }
- const installs = cfg?.plugins?.installs;
- if (installs) {
- for (const [k, v] of Object.entries(installs)) {
- if (v?.installPath && !existsSync(v.installPath)) {
- delete installs[k];
- changed = true;
- }
- }
- }
- if (changed) {
- await writeFile(cfgPath, JSON.stringify(cfg, null, 2) + "\n");
- log("Cleaned stale plugin paths from openclaw.json", "ok");
- }
- } catch {}
-}
-
-async function configureOpenclawViaJson(pluginPath, serverPort, pluginMode = "local", remoteOpts = {}) {
- const cfgPath = join(OPENCLAW_DIR, "openclaw.json");
- let cfg = {};
- try { cfg = JSON.parse(await readFile(cfgPath, "utf8")); } catch { /* start fresh */ }
- if (!cfg.plugins) cfg.plugins = {};
- cfg.plugins.enabled = true;
- const allow = Array.isArray(cfg.plugins.allow) ? cfg.plugins.allow : [];
- if (!allow.includes("memory-openviking")) allow.push("memory-openviking");
- cfg.plugins.allow = allow;
- if (!cfg.plugins.slots) cfg.plugins.slots = {};
- cfg.plugins.slots.memory = "memory-openviking";
- if (!cfg.plugins.load) cfg.plugins.load = {};
- const paths = Array.isArray(cfg.plugins.load.paths) ? cfg.plugins.load.paths : [];
- if (!paths.includes(pluginPath)) paths.push(pluginPath);
- cfg.plugins.load.paths = paths;
- if (!cfg.plugins.entries) cfg.plugins.entries = {};
-
- const pluginConfig = {
- mode: pluginMode,
- targetUri: "viking://user/memories",
- autoRecall: true,
- autoCapture: true,
- };
- if (pluginMode === "local") {
- pluginConfig.configPath = join(OPENVIKING_DIR, "ov.conf");
- pluginConfig.port = serverPort;
- } else {
- pluginConfig.baseUrl = remoteOpts.baseUrl || "http://127.0.0.1:1933";
- if (remoteOpts.apiKey) pluginConfig.apiKey = remoteOpts.apiKey;
- if (remoteOpts.agentId) pluginConfig.agentId = remoteOpts.agentId;
- }
- cfg.plugins.entries["memory-openviking"] = { config: pluginConfig };
-
- if (!cfg.gateway) cfg.gateway = {};
- cfg.gateway.mode = "local";
- await mkdir(OPENCLAW_DIR, { recursive: true });
- await writeFile(cfgPath, JSON.stringify(cfg, null, 2) + "\n");
-}
-
-async function configureOpenclawViaCli(pluginPath, serverPort, installMode, pluginMode = "local", remoteOpts = {}) {
- const extraEnv = OPENCLAW_DIR !== join(HOME, ".openclaw")
- ? { env: { ...process.env, OPENCLAW_STATE_DIR: OPENCLAW_DIR } }
- : {};
- const runNoShell = (cmd, args, opts = {}) => run(cmd, args, { ...opts, ...extraEnv, shell: false });
-
- if (installMode === "link") {
- if (existsSync(PLUGIN_DEST)) {
- log(`Removing old plugin dir ${PLUGIN_DEST}...`, "info");
- await rm(PLUGIN_DEST, { recursive: true, force: true });
- }
- await run("openclaw", ["plugins", "install", "-l", pluginPath], extraEnv);
- } else {
- // Merge into existing load paths instead of overwriting
- let currentPaths = [];
- try {
- const rawPaths = await runCapture("openclaw", ["config", "get", "plugins.load.paths", "--json"], { ...extraEnv });
- currentPaths = JSON.parse(rawPaths.out || "[]");
- } catch {}
- if (!Array.isArray(currentPaths)) currentPaths = [];
- if (!currentPaths.includes(pluginPath)) currentPaths.push(pluginPath);
- await runNoShell("openclaw", ["config", "set", "plugins.load.paths", JSON.stringify(currentPaths), "--json"], { silent: true }).catch(() => {});
- }
- await runNoShell("openclaw", ["config", "set", "plugins.enabled", "true"]);
- // Merge into existing allow list instead of overwriting
- let currentAllow = [];
- try {
- const raw = await runCapture("openclaw", ["config", "get", "plugins.allow", "--json"], { ...extraEnv });
- currentAllow = JSON.parse(raw.out || "[]");
- } catch {}
- if (!Array.isArray(currentAllow)) currentAllow = [];
- if (!currentAllow.includes("memory-openviking")) currentAllow.push("memory-openviking");
- await runNoShell("openclaw", ["config", "set", "plugins.allow", JSON.stringify(currentAllow), "--json"]);
- await runNoShell("openclaw", ["config", "set", "gateway.mode", "local"]);
- await runNoShell("openclaw", ["config", "set", "plugins.slots.memory", "memory-openviking"]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.mode", pluginMode]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.targetUri", "viking://user/memories"]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.autoRecall", "true", "--json"]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.autoCapture", "true", "--json"]);
-
- if (pluginMode === "local") {
- const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.configPath", ovConfPath]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.port", String(serverPort)]);
- } else {
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.baseUrl", remoteOpts.baseUrl || "http://127.0.0.1:1933"]);
- if (remoteOpts.apiKey) {
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.apiKey", remoteOpts.apiKey]);
- }
- if (remoteOpts.agentId) {
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.agentId", remoteOpts.agentId]);
- }
- }
-}
-
-async function configureOpenclaw(pluginPath, serverPort = DEFAULT_SERVER_PORT, installMode = "link", pluginMode = "local", remoteOpts = {}) {
- await fixStalePluginPaths(pluginPath);
- if (IS_WIN) {
- await configureOpenclawViaJson(pluginPath, serverPort, pluginMode, remoteOpts);
- } else {
- await configureOpenclawViaCli(pluginPath, serverPort, installMode, pluginMode, remoteOpts);
- }
- log("OpenClaw plugin config done", "ok");
-}
-
-async function resolveCommand(cmd) {
- if (IS_WIN) {
- const { code, out } = await runCapture("where", [cmd], { shell: true });
- return code === 0 ? out.split(/\r?\n/)[0].trim() : "";
- }
- const { out } = await runCapture("sh", ["-c", `command -v ${cmd} 2>/dev/null || which ${cmd}`]);
- return out || "";
-}
-
-async function writeOpenvikingEnv() {
- const pyCmd = process.env.OPENVIKING_PYTHON || DEFAULT_PYTHON;
- const pyPath = await resolveCommand(pyCmd);
- const goOut = await resolveCommand("go");
- const goPath = goOut ? dirname(goOut) : "";
- await mkdir(OPENCLAW_DIR, { recursive: true });
-
- if (IS_WIN) {
- const lines = [];
- if (pyPath) lines.push(`set OPENVIKING_PYTHON=${pyPath}`);
- if (goPath) lines.push(`set OPENVIKING_GO_PATH=${goPath}`);
- if (process.env.GOPATH) lines.push(`set OPENVIKING_GOPATH=${process.env.GOPATH}`);
- if (process.env.GOPROXY) lines.push(`set OPENVIKING_GOPROXY=${process.env.GOPROXY}`);
- await writeFile(join(OPENCLAW_DIR, "openviking.env.bat"), lines.join("\r\n") + "\r\n");
- log(`Written ~/.openclaw/openviking.env.bat`, "ok");
- } else {
- const lines = [];
- if (pyPath) lines.push(`export OPENVIKING_PYTHON='${pyPath}'`);
- if (goPath) lines.push(`export OPENVIKING_GO_PATH='${goPath}'`);
- if (process.env.GOPATH) lines.push(`export OPENVIKING_GOPATH='${process.env.GOPATH}'`);
- if (process.env.GOPROXY) lines.push(`export OPENVIKING_GOPROXY='${process.env.GOPROXY}'`);
- await writeFile(join(OPENCLAW_DIR, "openviking.env"), lines.join("\n") + "\n");
- log(`Written ~/.openclaw/openviking.env`, "ok");
- }
-}
-
-// ─── Main flow ───
-
-async function main() {
- const args = process.argv.slice(2);
- const help = args.includes("--help") || args.includes("-h");
- const nonInteractive = args.includes("--yes") || args.includes("-y");
-
- // Parse --workdir
- for (let i = 0; i < args.length; i++) {
- if (args[i] === "--workdir" && i + 1 < args.length) {
- OPENCLAW_DIR = args[i + 1];
- EXT_DIR = join(OPENCLAW_DIR, "extensions");
- PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
- }
- }
-
- if (help) {
- console.log(`
-OpenClaw + OpenViking setup helper
-
-Usage: npx openclaw-openviking-setup-helper [options]
-
-Options:
- -y, --yes Non-interactive, use defaults
- --workdir <path> OpenClaw config directory (default: ~/.openclaw)
- -h, --help Show help
-
-Steps:
- 1. Check OpenClaw
- 2. Check build environment (Python, Go, cmake, g++)
- 3. Install openviking module if needed
- 4. Configure ov.conf (API Key, VLM, Embedding, ports)
- 5. Deploy memory-openviking plugin
- 6. Write ~/.openclaw/openviking.env
-
-Env vars:
- OPENVIKING_PYTHON Python path
- OPENVIKING_CONFIG_FILE ov.conf path
- OPENVIKING_REPO Local OpenViking repo path (use local plugin if set)
- OPENVIKING_ARK_API_KEY Volcengine Ark API Key (used in -y mode, skip prompt)
- OPENVIKING_GO_PATH Go bin dir (when Go not in PATH, e.g. ~/local/go/bin)
-`);
- process.exit(0);
- }
-
- console.log("\n\ud83e\udd9e OpenClaw + OpenViking setup helper\n");
-
- // Workdir & mode selection
- await selectWorkdir(nonInteractive);
- log(`Target: ${OPENCLAW_DIR}`, "info");
-
- const pluginMode = await selectMode(nonInteractive);
- log(`Mode: ${pluginMode}`, "info");
-
- let remoteOpts = {};
- if (pluginMode === "remote") {
- remoteOpts = await collectRemoteConfig(nonInteractive);
- }
-
- const distro = await detectDistro();
-
- if (pluginMode === "local") {
- // ════════════════════════════════════════════
- // Phase 1: Check build tools & runtime environment
- // cmake/g++ must be present before OpenClaw install (node-llama-cpp needs them)
- // ════════════════════════════════════════════
- console.log("── Step 1/5: Checking build environment ──\n");
-
- const missing = [];
-
- // cmake check (needed by OpenClaw's node-llama-cpp AND OpenViking C++ extension)
- const cmakeResult = await checkCmake();
- if (cmakeResult.ok) {
- log("cmake: installed", "ok");
- } else {
- log("cmake: not found", "err");
- missing.push({ name: "cmake", detail: "Required by OpenClaw (llama.cpp) and OpenViking (C++ extension)" });
- }
-
- // g++ check (needed by OpenClaw's node-llama-cpp AND OpenViking C++ extension)
- const gppResult = await checkGpp();
- if (gppResult.ok) {
- log("g++: installed", "ok");
- } else {
- log("g++: not found", "err");
- missing.push({ name: "g++ (gcc-c++)", detail: "Required by OpenClaw (llama.cpp) and OpenViking (C++ extension)" });
- }
-
- // Python check
- const pyResult = await checkPython();
- if (pyResult.ok) {
- log(`Python: ${pyResult.msg}`, "ok");
- } else {
- log(`Python: ${pyResult.msg}`, "err");
- missing.push({ name: "Python >= 3.10", detail: pyResult.version ? `Current: ${pyResult.version}` : "Not found" });
- }
-
- // Go check (required on Linux for source install)
- const goResult = await checkGo();
- if (goResult.ok) {
- log(`Go: ${goResult.msg}`, "ok");
- } else if (IS_LINUX) {
- log(`Go: ${goResult.msg}`, "err");
- missing.push({ name: "Go >= 1.19", detail: goResult.msg });
- } else {
- log(`Go: not found (not required on ${process.platform})`, "warn");
- }
-
- if (missing.length > 0) {
- console.log("\n\u2717 Missing dependencies:\n");
- for (const m of missing) {
- console.log(` - ${m.name}: ${m.detail}`);
- }
-
- console.log("\n Please install the missing dependencies:\n");
-
- if (distro === "rhel") {
- const needBuild = missing.some((m) => m.name === "cmake" || m.name === "g++ (gcc-c++)");
- const needPython = missing.some((m) => m.name.startsWith("Python"));
- const needGo = missing.some((m) => m.name.startsWith("Go"));
-
- if (needBuild) console.log(" sudo dnf install -y gcc gcc-c++ cmake make");
- if (needPython) {
- console.log(" # Install Python 3.11 (try package manager first):");
- console.log(" sudo dnf install -y python3.11 python3.11-devel python3.11-pip");
- console.log(" # If unavailable, build from source:");
- console.log(" # See INSTALL-ZH.md 'Linux Environment Setup' section");
- }
- if (needGo) {
- console.log(" # Install Go >= 1.19:");
- console.log(" wget https://go.dev/dl/go1.25.6.linux-amd64.tar.gz");
- console.log(" sudo rm -rf /usr/local/go");
- console.log(" sudo tar -C /usr/local -xzf go1.25.6.linux-amd64.tar.gz");
- console.log(" echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc");
- console.log(" source ~/.bashrc");
- console.log(" # Configure Go module proxy (recommended if downloads are slow):");
- console.log(" go env -w GOPROXY=https://goproxy.cn,direct");
- }
- } else if (distro === "debian") {
- const needBuild = missing.some((m) => m.name === "cmake" || m.name === "g++ (gcc-c++)");
- const needPython = missing.some((m) => m.name.startsWith("Python"));
- const needGo = missing.some((m) => m.name.startsWith("Go"));
-
- if (needBuild) console.log(" sudo apt update && sudo apt install -y build-essential cmake");
- if (needPython) {
- console.log(" # Install Python 3.11:");
- console.log(" sudo add-apt-repository ppa:deadsnakes/ppa");
- console.log(" sudo apt install -y python3.11 python3.11-dev python3.11-venv");
- }
- if (needGo) {
- console.log(" # Install Go >= 1.19:");
- console.log(" wget https://go.dev/dl/go1.25.6.linux-amd64.tar.gz");
- console.log(" sudo rm -rf /usr/local/go");
- console.log(" sudo tar -C /usr/local -xzf go1.25.6.linux-amd64.tar.gz");
- console.log(" echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc");
- console.log(" source ~/.bashrc");
- console.log(" # Configure Go module proxy (recommended if downloads are slow):");
- console.log(" go env -w GOPROXY=https://goproxy.cn,direct");
- }
- } else {
- console.log(" Please install: cmake, g++, Python >= 3.10, Go >= 1.19");
- console.log(" See INSTALL-ZH.md for detailed instructions.");
- }
-
- console.log("\n After installing, re-run this script:");
- console.log(" npx ./examples/openclaw-memory-plugin/setup-helper\n");
- process.exit(1);
- }
- } // end if pluginMode === "local" (Phase 1)
-
- // ════════════════════════════════════════════
- // Phase 2: Check OpenClaw
- // ════════════════════════════════════════════
- console.log("\n── Step 2/5: Checking OpenClaw ──\n");
-
- const hasOpenclaw = await checkOpenclaw();
- if (!hasOpenclaw.ok) {
- log("OpenClaw is not installed.", "err");
- console.log("\n Please install OpenClaw:\n");
- console.log(" npm install -g openclaw\n");
- console.log(" If downloads are slow, use npmmirror registry:");
- console.log(" npm install -g openclaw --registry=https://registry.npmmirror.com\n");
- console.log(" After installation, run onboarding to configure your LLM:");
- console.log(" openclaw onboard\n");
- console.log(" Then re-run this script:");
- console.log(" npx ./examples/openclaw-memory-plugin/setup-helper\n");
- process.exit(1);
- }
- log("OpenClaw: installed", "ok");
-
- let ovOpts = {
- apiKey: process.env.OPENVIKING_ARK_API_KEY || "",
- serverPort: DEFAULT_SERVER_PORT,
- agfsPort: DEFAULT_AGFS_PORT,
- vlmModel: DEFAULT_VLM_MODEL,
- embeddingModel: DEFAULT_EMBEDDING_MODEL,
- };
-
- if (pluginMode === "local") {
- // ════════════════════════════════════════════
- // Phase 3: Check & install openviking module
- // ════════════════════════════════════════════
- console.log("\n── Step 3/5: Checking openviking module ──\n");
-
- const ovMod = await checkOpenvikingModule();
- if (ovMod.ok) {
- log("openviking module: installed", "ok");
- } else {
- log("openviking module: not found", "warn");
- const inferredRepoRoot = join(__dirname, "..", "..", "..");
- const hasLocalRepo = existsSync(join(inferredRepoRoot, "pyproject.toml"));
- const repo = process.env.OPENVIKING_REPO || (hasLocalRepo ? inferredRepoRoot : "");
-
- if (nonInteractive) {
- await installOpenviking(repo);
- } else {
- const choice = await question(
- repo
- ? "Install openviking from local repo? (y=local repo / n=skip)"
- : "Install openviking from PyPI? (y/n)",
- "y"
- );
- if (choice.toLowerCase() === "y") {
- await installOpenviking(repo);
- } else {
- log("Please install openviking manually and re-run this script.", "err");
- if (repo) console.log(` cd ${repo} && python3 -m pip install -e .`);
- else console.log(" python3.11 -m pip install openviking --upgrade --force-reinstall");
- process.exit(1);
- }
- }
-
- const recheck = await checkOpenvikingModule();
- if (!recheck.ok) {
- log("openviking module installation failed. Check errors above.", "err");
- process.exit(1);
- }
- log("openviking module: installed", "ok");
- }
-
- // ════════════════════════════════════════════
- // Phase 4: Configure ov.conf (interactive)
- // ════════════════════════════════════════════
- console.log("\n── Step 4/5: Configuring OpenViking ──\n");
-
- const ovConf = await checkOvvConf();
- const ovConfPath = ovConf.path;
-
- if (!ovConf.ok) {
- log(`ov.conf not found: ${ovConfPath}`, "info");
- const create = nonInteractive || (await question("Create ov.conf now? (y/n)", "y")).toLowerCase() === "y";
- if (create) {
- ovOpts = await collectOvvConfInteractive(nonInteractive);
- await ensureOvvConf(ovConfPath, ovOpts);
- } else {
- log("Please create ~/.openviking/ov.conf manually", "err");
- process.exit(1);
- }
- } else {
- log(`ov.conf found: ${ovConfPath}`, "ok");
- const invalid = await isOvvConfInvalid(ovConfPath);
- const existingKey = await getApiKeyFromOvvConf(ovConfPath);
- const existingPorts = await getOvvConfPorts(ovConfPath);
-
- if (invalid) {
- log("ov.conf format is invalid, will recreate", "warn");
- ovOpts = await collectOvvConfInteractive(nonInteractive);
- await ensureOvvConf(ovConfPath, ovOpts);
- } else if (!existingKey && !nonInteractive) {
- log("API Key is not configured in ov.conf", "warn");
- console.log("\nOpenViking needs a Volcengine Ark API Key for memory features.");
- console.log("Get your API Key at: https://console.volcengine.com/ark\n");
- const apiKey = (await questionApiKey("Volcengine Ark API Key (leave blank to skip): ")) || process.env.OPENVIKING_ARK_API_KEY || "";
- if (apiKey) {
- await updateOvvConf(ovConfPath, { apiKey });
- log("Written API Key to ov.conf", "ok");
- } else {
- log("API Key not set; memory features may be unavailable. Edit ov.conf to add later.", "warn");
- }
- ovOpts = { ...existingPorts, apiKey };
- } else if (!existingKey && process.env.OPENVIKING_ARK_API_KEY) {
- await updateOvvConf(ovConfPath, { apiKey: process.env.OPENVIKING_ARK_API_KEY });
- log("Written API Key from env to ov.conf", "ok");
- ovOpts = { ...existingPorts, apiKey: process.env.OPENVIKING_ARK_API_KEY };
- } else {
- ovOpts = { ...existingPorts, apiKey: existingKey };
- }
- }
- } // end if pluginMode === "local" (Phase 3 & 4)
-
- // ════════════════════════════════════════════
- // Phase 5: Deploy plugin & finalize
- // ════════════════════════════════════════════
- console.log("\n── Step 5/5: Deploying plugin ──\n");
-
- const inferredRepoRoot = join(__dirname, "..", "..", "..");
- const repoRoot = process.env.OPENVIKING_REPO ||
- (existsSync(join(inferredRepoRoot, "examples", "openclaw-memory-plugin", "index.ts")) ? inferredRepoRoot : "");
- let pluginPath;
- if (repoRoot && existsSync(join(repoRoot, "examples", "openclaw-memory-plugin", "index.ts"))) {
- pluginPath = join(repoRoot, "examples", "openclaw-memory-plugin");
- log(`Using local plugin: ${pluginPath}`, "ok");
- if (!existsSync(join(pluginPath, "node_modules"))) {
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: pluginPath, silent: true });
- }
- } else {
- await fetchPluginFromGitHub(PLUGIN_DEST);
- pluginPath = PLUGIN_DEST;
- }
-
- const installMode = (repoRoot && existsSync(join(repoRoot, "examples", "openclaw-memory-plugin", "index.ts"))) ? "link" : "download";
- await configureOpenclaw(pluginPath, ovOpts?.serverPort, installMode, pluginMode, remoteOpts);
-
- if (pluginMode === "local") {
- await writeOpenvikingEnv();
- }
-
- // Done
- console.log("\n╔══════════════════════════════════════════════════════════╗");
- console.log("║ \u2705 Setup complete! ║");
- console.log("╚══════════════════════════════════════════════════════════╝");
- if (pluginMode === "local") {
- console.log("\nTo start OpenClaw with memory:");
- if (IS_WIN) {
- console.log(' call "%USERPROFILE%\\.openclaw\\openviking.env.bat" && openclaw gateway');
- } else {
- console.log(` source ${OPENCLAW_DIR}/openviking.env && openclaw gateway`);
- }
- } else {
- console.log("\nTo start OpenClaw with memory (remote mode):");
- console.log(" openclaw gateway");
- console.log(`\nRemote server: ${remoteOpts.baseUrl}`);
- }
- console.log("\nTo verify:");
- console.log(" openclaw status");
- console.log("");
-}
-
-main().catch((e) => {
- console.error(e);
- process.exit(1);
-});
diff --git a/examples/openclaw-memory-plugin/setup-helper/install.js b/examples/openclaw-memory-plugin/setup-helper/install.js
new file mode 100644
index 000000000..b2edf2b9b
--- /dev/null
+++ b/examples/openclaw-memory-plugin/setup-helper/install.js
@@ -0,0 +1,816 @@
+#!/usr/bin/env node
+/**
+ * OpenClaw + OpenViking cross-platform installer
+ *
+ * One-liner (after npm publish; use package name + bin name):
+ * npx -p openclaw-openviking-setup-helper ov-install [ -y ] [ --zh ] [ --workdir PATH ]
+ * Or install globally then run:
+ * npm i -g openclaw-openviking-setup-helper
+ * ov-install
+ * openclaw-openviking-install
+ *
+ * Direct run:
+ * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ]
+ * [ --openviking-version=V ] [ --repo=PATH ]
+ *
+ * Environment variables:
+ * REPO, BRANCH, OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING
+ * OPENVIKING_VERSION Pip install openviking==VERSION (omit for latest)
+ * OPENVIKING_REPO Repo path: source install (pip -e) + local plugin (default: off)
+ * NPM_REGISTRY, PIP_INDEX_URL
+ * OPENVIKING_VLM_API_KEY, OPENVIKING_EMBEDDING_API_KEY, OPENVIKING_ARK_API_KEY
+ * OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES (Linux)
+ */
+
+import { spawn } from "node:child_process";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { existsSync, readdirSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { createInterface } from "node:readline";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const REPO = process.env.REPO || "volcengine/OpenViking";
+const BRANCH = process.env.BRANCH || "main";
+const GH_RAW = `https://raw.githubusercontent.com/${REPO}/${BRANCH}`;
+const NPM_REGISTRY = process.env.NPM_REGISTRY || "https://registry.npmmirror.com";
+const PIP_INDEX_URL = process.env.PIP_INDEX_URL || "https://pypi.tuna.tsinghua.edu.cn/simple";
+
+const IS_WIN = process.platform === "win32";
+const HOME = process.env.HOME || process.env.USERPROFILE || "";
+
+const DEFAULT_OPENCLAW_DIR = join(HOME, ".openclaw");
+let OPENCLAW_DIR = DEFAULT_OPENCLAW_DIR;
+let PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "memory-openviking");
+
+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";
+
+const REQUIRED_PLUGIN_FILES = [
+ "examples/openclaw-memory-plugin/index.ts",
+ "examples/openclaw-memory-plugin/config.ts",
+ "examples/openclaw-memory-plugin/openclaw.plugin.json",
+ "examples/openclaw-memory-plugin/package.json",
+ "examples/openclaw-memory-plugin/package-lock.json",
+ "examples/openclaw-memory-plugin/.gitignore",
+];
+
+const OPTIONAL_PLUGIN_FILES = [
+ "examples/openclaw-memory-plugin/client.ts",
+ "examples/openclaw-memory-plugin/process-manager.ts",
+ "examples/openclaw-memory-plugin/memory-ranking.ts",
+ "examples/openclaw-memory-plugin/text-utils.ts",
+];
+
+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 selectedMode = "local";
+let selectedServerPort = DEFAULT_SERVER_PORT;
+let remoteBaseUrl = "http://127.0.0.1:1933";
+let remoteApiKey = "";
+let remoteAgentId = "";
+let openvikingPythonPath = "";
+
+const argv = process.argv.slice(2);
+for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === "-y" || arg === "--yes") {
+ installYes = true;
+ continue;
+ }
+ if (arg === "--zh") {
+ langZh = true;
+ continue;
+ }
+ if (arg === "--workdir") {
+ const workdir = argv[i + 1]?.trim();
+ if (!workdir) {
+ console.error("--workdir requires a path");
+ process.exit(1);
+ }
+ setOpenClawDir(workdir);
+ workdirExplicit = true;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--openviking-version=")) {
+ openvikingVersion = arg.slice("--openviking-version=".length).trim();
+ continue;
+ }
+ if (arg.startsWith("--repo=")) {
+ openvikingRepo = arg.slice("--repo=".length).trim();
+ continue;
+ }
+ if (arg === "-h" || arg === "--help") {
+ printHelp();
+ process.exit(0);
+ }
+}
+
+const OPENVIKING_PIP_SPEC = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";
+
+function setOpenClawDir(dir) {
+ OPENCLAW_DIR = dir;
+ PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "memory-openviking");
+}
+
+function printHelp() {
+ console.log("Usage: node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --openviking-version=V ] [ --repo=PATH ]");
+ console.log("");
+ console.log(" -y, --yes Non-interactive (use defaults)");
+ console.log(" --zh Chinese prompts");
+ console.log(" --workdir OpenClaw config directory (default: ~/.openclaw)");
+ console.log(" --openviking-version=VERSION Pip install openviking==VERSION (default: latest)");
+ console.log(" --repo=PATH Use OpenViking repo at PATH: pip install -e PATH, plugin from repo (default: off)");
+ console.log(" -h, --help This help");
+ console.log("");
+ console.log("Env: OPENVIKING_REPO, REPO, BRANCH, SKIP_OPENCLAW, SKIP_OPENVIKING, OPENVIKING_VERSION, NPM_REGISTRY, PIP_INDEX_URL");
+}
+
+function tr(en, zh) {
+ return langZh ? zh : en;
+}
+
+function info(msg) {
+ console.log(`[INFO] ${msg}`);
+}
+
+function warn(msg) {
+ console.log(`[WARN] ${msg}`);
+}
+
+function err(msg) {
+ console.log(`[ERROR] ${msg}`);
+}
+
+function bold(msg) {
+ console.log(msg);
+}
+
+function run(cmd, args, opts = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(cmd, args, {
+ stdio: opts.silent ? "pipe" : "inherit",
+ shell: opts.shell ?? true,
+ ...opts,
+ });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ if (code === 0) resolve();
+ else reject(new Error(`exit ${code}`));
+ });
+ });
+}
+
+function runCapture(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) => {
+ out += String(chunk);
+ });
+ child.stderr?.on("data", (chunk) => {
+ errOut += String(chunk);
+ });
+ child.on("error", (error) => {
+ resolve({ code: -1, out: "", err: String(error) });
+ });
+ child.on("close", (code) => {
+ resolve({ code, out: out.trim(), err: errOut.trim() });
+ });
+ });
+}
+
+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 question(prompt, defaultValue = "") {
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ const suffix = defaultValue ? ` [${defaultValue}]` : "";
+ return new Promise((resolve) => {
+ rl.question(`${prompt}${suffix}: `, (answer) => {
+ rl.close();
+ resolve((answer ?? defaultValue).trim() || defaultValue);
+ });
+ });
+}
+
+async function checkPython() {
+ const py = process.env.OPENVIKING_PYTHON || (IS_WIN ? "python" : "python3");
+ 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 {
+ const entries = readdirSync(HOME, { withFileTypes: true });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === ".openclaw" || entry.name.startsWith(".openclaw-")) {
+ instances.push(join(HOME, entry.name));
+ }
+ }
+ } catch {}
+ return instances.sort();
+}
+
+async function selectWorkdir() {
+ if (workdirExplicit) return;
+
+ const instances = detectOpenClawInstances();
+ if (instances.length <= 1) return;
+ if (installYes) return;
+
+ console.log("");
+ bold(tr("Found multiple OpenClaw instances:", "发现多个 OpenClaw 实例:"));
+ for (let i = 0; i < instances.length; i++) {
+ console.log(` ${i + 1}) ${instances[i]}`);
+ }
+ console.log("");
+
+ const answer = await question(tr("Select instance number", "选择实例编号"), "1");
+ const index = Number.parseInt(answer, 10) - 1;
+ if (index >= 0 && index < instances.length) {
+ setOpenClawDir(instances[index]);
+ } else {
+ warn(tr("Invalid selection, using default", "无效选择,使用默认"));
+ setOpenClawDir(instances[0]);
+ }
+}
+
+async function selectMode() {
+ if (installYes) {
+ selectedMode = "local";
+ return;
+ }
+ const mode = (await question(tr("Plugin mode - local or remote", "插件模式 - local 或 remote"), "local")).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("");
+}
+
+async function checkOpenClaw() {
+ if (process.env.SKIP_OPENCLAW === "1") {
+ info(tr("Skipping OpenClaw check (SKIP_OPENCLAW=1)", "跳过 OpenClaw 校验 (SKIP_OPENCLAW=1)"));
+ return;
+ }
+
+ info(tr("Checking OpenClaw...", "正在校验 OpenClaw..."));
+ const result = await runCapture("openclaw", ["--version"], { shell: IS_WIN });
+ if (result.code === 0) {
+ info(tr("OpenClaw detected ✓", "OpenClaw 已安装 ✓"));
+ return;
+ }
+
+ err(tr("OpenClaw not found. Install it manually, then rerun this script.", "未检测到 OpenClaw,请先手动安装后再执行本脚本"));
+ console.log("");
+ console.log(tr("Recommended command:", "推荐命令:"));
+ console.log(` npm install -g openclaw --registry ${NPM_REGISTRY}`);
+ console.log("");
+ console.log(" openclaw --version");
+ console.log(" openclaw onboard");
+ console.log("");
+ 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);
+ }
+
+ 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;
+ }
+
+ info(tr("Installing OpenViking from PyPI...", "正在安装 OpenViking (PyPI)..."));
+ info(tr(`Using pip index: ${PIP_INDEX_URL}`, `使用 pip 镜像源: ${PIP_INDEX_URL}`));
+
+ info(`Package: ${OPENVIKING_PIP_SPEC}`);
+ await runCapture(py, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });
+ const installResult = await runLiveCapture(
+ py,
+ ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ { 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) {
+ await runLiveCapture(
+ venvPy,
+ ["-m", "pip", "install", "--progress-bar", "on", "-U", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ { shell: false },
+ );
+ 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 venvInstall = await runLiveCapture(
+ venvPy,
+ ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ { 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 systemInstall = await runLiveCapture(
+ py,
+ ["-m", "pip", "install", "--progress-bar", "on", "--break-system-packages", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
+ { 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 });
+
+ 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 },
+ },
+ embedding: {
+ dense: {
+ backend: "volcengine",
+ api_key: embeddingApiKey || null,
+ model: embeddingModel,
+ api_base: "https://ark.cn-beijing.volces.com/api/v3",
+ dimension: 1024,
+ input: "multimodal",
+ },
+ },
+ vlm: {
+ backend: "volcengine",
+ api_key: vlmApiKey || null,
+ model: vlmModel,
+ api_base: "https://ark.cn-beijing.volces.com/api/v3",
+ temperature: 0.1,
+ max_retries: 3,
+ },
+ };
+
+ const configPath = join(OPENVIKING_DIR, "ov.conf");
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
+ info(tr(`Config generated: ${configPath}`, `已生成配置: ${configPath}`));
+}
+
+async function downloadPluginFile(relPath, required, index, total) {
+ const fileName = relPath.split("/").pop();
+ const url = `${GH_RAW}/${relPath}`;
+ const maxRetries = 3;
+
+ process.stdout.write(` [${index}/${total}] ${fileName} `);
+
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
+ try {
+ const response = await fetch(url);
+ if (response.ok) {
+ const buffer = Buffer.from(await response.arrayBuffer());
+ await writeFile(join(PLUGIN_DEST, fileName), buffer);
+ console.log("✓");
+ return;
+ }
+ if (!required && response.status === 404) {
+ console.log(tr("(not present in target branch, skipped)", "(目标分支不存在,已跳过)"));
+ return;
+ }
+ } catch {}
+
+ if (attempt < maxRetries) {
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ }
+ }
+
+ if (fileName === ".gitignore") {
+ console.log(tr("(retries failed, using minimal .gitignore)", "(重试失败,使用最小 .gitignore)"));
+ await writeFile(join(PLUGIN_DEST, fileName), "node_modules/\n", "utf8");
+ return;
+ }
+
+ console.log("");
+ err(tr(`Download failed: ${url}`, `下载失败: ${url}`));
+ process.exit(1);
+}
+
+async function downloadPlugin() {
+ await mkdir(PLUGIN_DEST, { recursive: true });
+ const files = [
+ ...REQUIRED_PLUGIN_FILES.map((relPath) => ({ relPath, required: true })),
+ ...OPTIONAL_PLUGIN_FILES.map((relPath) => ({ relPath, required: false })),
+ ];
+
+ info(tr(`Downloading memory-openviking plugin from ${REPO}@${BRANCH}...`, `正在从 ${REPO}@${BRANCH} 下载 memory-openviking 插件...`));
+ for (let i = 0; i < files.length; i++) {
+ const file = files[i];
+ await downloadPluginFile(file.relPath, file.required, i + 1, files.length);
+ }
+
+ info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
+ await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: PLUGIN_DEST, silent: false });
+ info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
+}
+
+async function configureOpenClawPlugin(pluginPath = PLUGIN_DEST) {
+ info(tr("Configuring OpenClaw plugin...", "正在配置 OpenClaw 插件..."));
+
+ const configPath = join(OPENCLAW_DIR, "openclaw.json");
+ let config = {};
+
+ if (existsSync(configPath)) {
+ try {
+ const raw = await readFile(configPath, "utf8");
+ if (raw.trim()) config = JSON.parse(raw);
+ } catch {
+ warn(tr("Existing openclaw.json invalid. Rebuilding required sections.", "已有 openclaw.json 非法,将重建相关配置节点。"));
+ }
+ }
+
+ if (!config.plugins) config.plugins = {};
+ if (!config.gateway) config.gateway = {};
+ if (!config.plugins.slots) config.plugins.slots = {};
+ if (!config.plugins.load) config.plugins.load = {};
+ if (!config.plugins.entries) config.plugins.entries = {};
+
+ const existingPaths = Array.isArray(config.plugins.load.paths) ? config.plugins.load.paths : [];
+ config.plugins.enabled = true;
+ config.plugins.allow = ["memory-openviking"];
+ config.plugins.slots.memory = "memory-openviking";
+ config.plugins.load.paths = [...new Set([...existingPaths, pluginPath])];
+
+ const pluginConfig = {
+ mode: selectedMode,
+ targetUri: "viking://user/memories",
+ autoRecall: true,
+ autoCapture: true,
+ };
+
+ if (selectedMode === "local") {
+ pluginConfig.configPath = join(OPENVIKING_DIR, "ov.conf");
+ pluginConfig.port = selectedServerPort;
+ } else {
+ pluginConfig.baseUrl = remoteBaseUrl;
+ if (remoteApiKey) pluginConfig.apiKey = remoteApiKey;
+ if (remoteAgentId) pluginConfig.agentId = remoteAgentId;
+ }
+
+ config.plugins.entries["memory-openviking"] = { config: pluginConfig };
+ config.gateway.mode = "local";
+
+ await mkdir(OPENCLAW_DIR, { recursive: true });
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
+ info(tr("OpenClaw plugin configured", "OpenClaw 插件配置完成"));
+}
+
+async function resolvePythonPath() {
+ if (openvikingPythonPath) return openvikingPythonPath;
+ const python = await checkPython();
+ const py = python.cmd;
+ if (!py) return "";
+
+ if (IS_WIN) {
+ const result = await runCapture("where", [py], { shell: true });
+ return result.out.split(/\r?\n/)[0]?.trim() || py;
+ }
+
+ const result = await runCapture("which", [py], { shell: false });
+ return result.out.trim() || py;
+}
+
+async function writeOpenvikingEnv({ includePython }) {
+ const needStateDir = OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR;
+ const pythonPath = includePython ? await resolvePythonPath() : "";
+ if (!needStateDir && !pythonPath) return null;
+
+ await mkdir(OPENCLAW_DIR, { recursive: true });
+
+ if (IS_WIN) {
+ 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, '\\"')}"`);
+ }
+
+ const batPath = join(OPENCLAW_DIR, "openviking.env.bat");
+ const ps1Path = join(OPENCLAW_DIR, "openviking.env.ps1");
+ await writeFile(batPath, `${batLines.join("\r\n")}\r\n`, "utf8");
+ await writeFile(ps1Path, `${psLines.join("\n")}\n`, "utf8");
+
+ info(tr(`Environment file generated: ${batPath}`, `已生成环境文件: ${batPath}`));
+ 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");
+ info(tr(`Environment file generated: ${envPath}`, `已生成环境文件: ${envPath}`));
+ return { shellPath: envPath };
+}
+
+function wrapCommand(command, envFiles) {
+ if (!envFiles) return command;
+ if (IS_WIN) return `call "${envFiles.shellPath}" && ${command}`;
+ return `source '${envFiles.shellPath.replace(/'/g, "'\"'\"'")}' && ${command}`;
+}
+
+async function main() {
+ console.log("");
+ bold(tr("🦣 OpenClaw + OpenViking Installer", "🦣 OpenClaw + OpenViking 一键安装"));
+ console.log("");
+
+ await selectWorkdir();
+ info(tr(`Target: ${OPENCLAW_DIR}`, `目标实例: ${OPENCLAW_DIR}`));
+
+ await selectMode();
+ info(tr(`Mode: ${selectedMode}`, `模式: ${selectedMode}`));
+
+ if (selectedMode === "local") {
+ await validateEnvironment();
+ await checkOpenClaw();
+ await installOpenViking();
+ await configureOvConf();
+ } else {
+ await checkOpenClaw();
+ await collectRemoteConfig();
+ }
+
+ let pluginPath;
+ const localPluginDir = openvikingRepo ? join(openvikingRepo, "examples", "openclaw-memory-plugin") : "";
+ if (openvikingRepo && existsSync(join(localPluginDir, "index.ts"))) {
+ pluginPath = localPluginDir;
+ info(tr(`Using local plugin from repo: ${pluginPath}`, `使用仓库内插件: ${pluginPath}`));
+ if (!existsSync(join(pluginPath, "node_modules"))) {
+ info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
+ await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: pluginPath, silent: false });
+ }
+ } else {
+ await downloadPlugin();
+ pluginPath = PLUGIN_DEST;
+ }
+
+ await configureOpenClawPlugin(pluginPath);
+ const envFiles = await writeOpenvikingEnv({
+ includePython: selectedMode === "local",
+ });
+
+ console.log("");
+ bold("═══════════════════════════════════════════════════════════");
+ bold(` ${tr("Installation complete!", "安装完成!")}`);
+ bold("═══════════════════════════════════════════════════════════");
+ 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:"));
+ }
+ 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") {
+ info(tr(`You can edit the config freely: ${OPENVIKING_DIR}/ov.conf`, `你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf`));
+ } else {
+ info(tr(`Remote server: ${remoteBaseUrl}`, `远程服务器: ${remoteBaseUrl}`));
+ }
+ console.log("");
+}
+
+main().catch((error) => {
+ console.error(error);
+ process.exit(1);
+});
diff --git a/examples/openclaw-memory-plugin/setup-helper/package.json b/examples/openclaw-memory-plugin/setup-helper/package.json
index d02501cea..ad5aa2502 100644
--- a/examples/openclaw-memory-plugin/setup-helper/package.json
+++ b/examples/openclaw-memory-plugin/setup-helper/package.json
@@ -1,20 +1,31 @@
{
"name": "openclaw-openviking-setup-helper",
- "version": "0.1.0",
+ "version": "0.2.8",
"description": "Setup helper for installing OpenViking memory plugin into OpenClaw",
"type": "module",
"bin": {
- "openclaw-openviking-setup-helper": "./cli.js"
+ "openclaw-openviking-setup-helper": "install.js",
+ "openclaw-openviking-install": "install.js",
+ "ov-install": "install.js"
},
- "keywords": ["openviking", "openclaw", "setup", "memory", "agent"],
+ "keywords": [
+ "openviking",
+ "openclaw",
+ "setup",
+ "memory",
+ "agent",
+ "installer"
+ ],
"author": "OpenViking",
"license": "Apache-2.0",
"repository": {
"type": "git",
- "url": "https://github.com/OpenViking/OpenViking.git",
+ "url": "git+https://github.com/volcengine/OpenViking.git",
"directory": "examples/openclaw-memory-plugin/setup-helper"
},
- "files": ["cli.js", "README.md"],
+ "files": [
+ "install.js"
+ ],
"engines": {
"node": ">=22.0.0"
}