Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat: add ClawHub publishing, setup wizard, and OPENCLAW_STATE_DIR support (#1587)
LinQiang39109bb76cf61f2
diff --git a/examples/openclaw-plugin/.clawhubignore b/examples/openclaw-plugin/.clawhubignorenew file mode 100644index 000000000..fda8472b4--- /dev/null+++ b/examples/openclaw-plugin/.clawhubignore@@ -0,0 +1,11 @@+setup-helper/+tests/+__tests__/+images/+health_check_tools/+upgrade_scripts/+skills/+INSTALL*.md+README*.md+install.sh+vitest.config.tsdiff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.mdindex 4ca32b88e..2dd59bc18 100644--- a/examples/openclaw-plugin/INSTALL-ZH.md+++ b/examples/openclaw-plugin/INSTALL-ZH.md@@ -32,9 +32,23 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examplesbash cleanup-memory-openviking.sh```-## 安装+## 通过 ClawHub 安装(推荐)-推荐使用 `npm` + `ov-install`。macOS、Linux、Windows 的流程相同。+```bash+openclaw plugins install clawhub:@openclaw/openviking+```++安装完成后运行交互式配置向导:++```bash+openclaw openviking setup+```++向导会检测 Python 环境、验证 OpenViking 包是否可用,并将配置写入 `$OPENCLAW_STATE_DIR/openclaw.json`(默认:`~/.openclaw/openclaw.json`)。++## 通过 ov-install 安装(替代方案)++`ov-install` 一键完成 Python/OpenViking 安装和插件部署。macOS、Linux、Windows 的流程相同。```bashnpm install -g openclaw-openviking-setup-helperdiff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.mdindex 785fb761b..ddc33552c 100644--- a/examples/openclaw-plugin/INSTALL.md+++ b/examples/openclaw-plugin/INSTALL.md@@ -32,9 +32,23 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examplesbash cleanup-memory-openviking.sh```-## Install+## Install via ClawHub (Recommended)-The recommended path is `npm` + `ov-install`.+```bash+openclaw plugins install clawhub:@openclaw/openviking+```++After installation, run the interactive setup wizard:++```bash+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`).++## Install via ov-install (Alternative)++The `ov-install` helper automates both the Python/OpenViking installation and plugin deployment:```bashnpm install -g openclaw-openviking-setup-helperdiff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.tsnew file mode 100644index 000000000..b4a6705af--- /dev/null+++ b/examples/openclaw-plugin/commands/setup.ts@@ -0,0 +1,522 @@+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 } 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 = {+ command: (name: string) => CommandBuilder;+};++type CommandBuilder = {+ description: (desc: string) => CommandBuilder;+ option: (flags: string, desc: string) => CommandBuilder;+ command: (name: string) => CommandBuilder;+ action: (fn: (...args: unknown[]) => void | Promise<void>) => CommandBuilder;+};++function tr(langZh: boolean, en: string, zh: string): string {+ return langZh ? zh : en;+}++function maskKey(key: string): string {+ if (key.length <= 8) return "****";+ return `${key.slice(0, 4)}...${key.slice(-4)}`;+}++function ask(rl: readline.Interface, prompt: string, defaultValue = ""): Promise<string> {+ const suffix = defaultValue ? ` [${defaultValue}]` : "";+ return new Promise((resolve) => {+ rl.question(`${prompt}${suffix}: `, (answer) => {+ resolve((answer ?? "").trim() || defaultValue);+ });+ });+}++function capture(+ cmd: string,+ args: string[],+ opts?: { env?: NodeJS.ProcessEnv; shell?: boolean },+): Promise<{ code: number; out: string; err: string }> {+ return new Promise((resolve) => {+ const child = launchProcess(cmd, args, {+ stdio: ["ignore", "pipe", "pipe"],+ env: opts?.env ?? sysEnv(),+ shell: opts?.shell ?? false,+ });+ let out = "";+ let errOut = "";+ child.stdout?.on("data", (chunk: Buffer) => { out += String(chunk); });+ child.stderr?.on("data", (chunk: Buffer) => { errOut += String(chunk); });+ child.on("error", (error: Error) => { resolve({ code: -1, out: "", err: String(error) }); });+ child.on("close", (code: number | null) => { resolve({ code: code ?? -1, out: out.trim(), err: errOut.trim() }); });+ });+}++async function resolveAbsoluteCommand(cmd: string): Promise<string> {+ if (cmd.startsWith("/") || (IS_WIN && /^[A-Za-z]:[/\\]/.test(cmd))) return cmd;+ if (IS_WIN) {+ const r = await capture("where", [cmd], { shell: true });+ return r.out.split(/\r?\n/)[0]?.trim() || cmd;+ }+ const r = await capture("which", [cmd]);+ 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 m = IS_WIN+ ? content.match(/set\s+OPENVIKING_PYTHON=(.+)/i)+ : content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);+ if (m?.[1]) return m[1].trim();+ } 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) {+ fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env.bat"), `@echo off\r\nset "OPENVIKING_PYTHON=${pythonPath}"\r\n`, "utf-8");+ fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env.ps1"), `$env:OPENVIKING_PYTHON = "${pythonPath.replace(/\\/g, "\\\\")}"\n`, "utf-8");+ } else {+ fs.writeFileSync(path.join(OPENCLAW_DIR, "openviking.env"), `export OPENVIKING_PYTHON='${pythonPath}'\n`, "utf-8");+ }+}++async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<{ ok: boolean; version: string; error: string }> {+ try {+ const headers: Record<string, string> = {};+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 10_000);+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/health`, {+ headers,+ signal: controller.signal,+ });+ clearTimeout(timeoutId);+ if (response.ok) {+ try {+ const data = await response.json() as Record<string, unknown>;+ return { ok: true, version: String(data.version ?? ""), error: "" };+ } catch {+ return { ok: true, version: "", error: "" };+ }+ }+ return { ok: false, version: "", error: `HTTP ${response.status}` };+ } catch (err) {+ return { ok: false, version: "", error: String(err instanceof Error ? err.message : err) };+ }+}++function readOpenClawConfig(configPath: string): Record<string, unknown> {+ if (!fs.existsSync(configPath)) return {};+ try {+ return JSON.parse(fs.readFileSync(configPath, "utf-8"));+ } catch {+ return {};+ }+}++function getExistingPluginConfig(config: Record<string, unknown>): Record<string, unknown> | null {+ const plugins = config.plugins as Record<string, unknown> | undefined;+ if (!plugins) return null;+ const entries = plugins.entries as Record<string, unknown> | undefined;+ if (!entries) return null;+ const entry = entries.openviking as Record<string, unknown> | undefined;+ if (!entry) return null;+ const cfg = entry.config as Record<string, unknown> | undefined;+ return cfg && cfg.mode ? cfg : null;+}++function writeConfig(+ configPath: string,+ pluginCfg: Record<string, unknown>,+): void {+ const configDir = path.dirname(configPath);+ if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });++ const config = readOpenClawConfig(configPath);++ if (!config.plugins) config.plugins = {};+ const plugins = config.plugins as Record<string, unknown>;+ if (!plugins.entries) plugins.entries = {};+ const entries = plugins.entries as Record<string, unknown>;++ const existingEntry = (entries.openviking as Record<string, unknown>) ?? {};+ entries.openviking = { ...existingEntry, config: pluginCfg };++ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");+}++function detectLangZh(options: Record<string, unknown>): boolean {+ if (options.zh) return true;+ const lang = getEnv("LANG") || getEnv("LC_ALL") || "";+ return /^zh/i.test(lang);+}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function registerSetupCli(api: any): void {+ if (!api.registerCli) {+ api.logger.info("openviking: registerCli not available, setup command skipped");+ return;+ }++ api.registerCli(+ ({ program: rawProgram }) => {+ const program = rawProgram as CommandProgram;+ const ovCmd = program.command("openviking").description("OpenViking plugin commands");++ ovCmd+ .command("setup")+ .description("Interactive setup wizard for OpenViking plugin configuration")+ .option("--reconfigure", "Force re-entry of all configuration values")+ .option("--zh", "Chinese prompts")+ .action(async (options: { reconfigure?: boolean; zh?: boolean }) => {+ const zh = detectLangZh(options as Record<string, unknown>);+ const configDir = OPENCLAW_DIR;+ const configPath = path.join(configDir, "openclaw.json");++ console.log("");+ console.log(`🦣 ${tr(zh, "OpenViking Plugin Setup", "OpenViking 插件配置向导")}`);+ console.log("");++ const config = readOpenClawConfig(configPath);+ const existing = getExistingPluginConfig(config);++ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });+ const q = (prompt: string, def = "") => ask(rl, prompt, def);++ 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}`);+ }+ console.log("");+ console.log(tr(+ zh,+ "Press Enter to keep existing values, or use --reconfigure to change.",+ "按 Enter 保留现有配置,或使用 --reconfigure 重新配置。",+ ));+ console.log("");+ 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);+ }++ if (envOk) {+ 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") {+ 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...", "重新配置中..."));+ console.log("");+ } else {+ console.log(tr(zh,+ "No existing configuration found. Starting setup wizard.",+ "未找到现有配置,开始配置向导。",+ ));+ console.log("");+ }++ const modeDefault = String(existing?.mode ?? "local");+ const modeInput = await q(+ tr(zh, "Plugin mode - local or remote", "插件模式 - local 或 remote"),+ modeDefault,+ );+ const mode = modeInput.toLowerCase() === "remote" ? "remote" : "local";++ if (mode === "local") {+ await setupLocal(zh, configPath, existing, q);+ } else {+ await setupRemote(zh, configPath, existing, q);+ }+ } finally {+ rl.close();+ }+ });+ },+ { commands: ["openviking"] },+ );+}++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);+ console.log(` ✓ ${tr(zh, "Saved OPENVIKING_PYTHON to ~/.openclaw/openviking.env", "已将 OPENVIKING_PYTHON 写入 ~/.openclaw/openviking.env")}`);+ } else {+ console.log(` ℹ ${tr(zh,+ "OpenViking Python package not detected (service may still work if installed separately)",+ "未检测到 OpenViking Python 包(如已单独安装服务,可忽略此提示)",+ )}`);+ }+ console.log("");++ 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>,+): Promise<void> {+ const baseUrl = String(existing.baseUrl ?? DEFAULT_REMOTE_URL);+ const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;+ console.log(tr(zh, `Testing connectivity to ${baseUrl}...`, `正在测试连接 ${baseUrl}...`));+ const health = await checkServiceHealth(baseUrl, apiKey);+ if (health.ok) {+ const ver = health.version ? ` (version: ${health.version})` : "";+ console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);+ } else {+ console.log(` ✗ ${tr(zh, `Connection failed: ${health.error}`, `连接失败: ${health.error}`)}`);+ }+ console.log("");+}++async function setupLocal(+ zh: boolean,+ configPath: string,+ existing: Record<string, unknown> | null,+ q: (prompt: string, def?: string) => Promise<string>,+): Promise<void> {+ // Environment check (non-blocking)+ console.log("");+ 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);+ console.log(` ✓ ${tr(zh, "Saved OPENVIKING_PYTHON to ~/.openclaw/openviking.env", "已将 OPENVIKING_PYTHON 写入 ~/.openclaw/openviking.env")}`);+ } 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 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 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;++ writeConfig(configPath, pluginCfg);++ console.log(tr(zh, "✓ Configuration saved to ~/.openclaw/openclaw.json", "✓ 配置已保存至 ~/.openclaw/openclaw.json"));+ 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("");+}++async function setupRemote(+ zh: boolean,+ configPath: string,+ existing: Record<string, unknown> | null,+ q: (prompt: string, def?: string) => Promise<string>,+): Promise<void> {+ console.log("");+ console.log(tr(zh, "── Remote Mode Configuration ──", "── 远程模式配置 ──"));+ console.log("");++ const defaultUrl = existing?.baseUrl ? String(existing.baseUrl) : DEFAULT_REMOTE_URL;+ const defaultApiKey = existing?.apiKey ? String(existing.apiKey) : "";+ const defaultAgentId = existing?.agentId ? String(existing.agentId) : "";++ 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);++ console.log("");++ // Connectivity test (non-blocking)+ console.log(tr(zh, `Testing connectivity to ${baseUrl}...`, `正在测试连接 ${baseUrl}...`));+ const health = await checkServiceHealth(baseUrl, apiKey || undefined);+ if (health.ok) {+ const ver = health.version ? ` (version: ${health.version})` : "";+ console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);+ } else {+ console.log(` ✗ ${tr(zh, `Connection failed: ${health.error}`, `连接失败: ${health.error}`)}`);+ console.log("");+ console.log(tr(zh,+ " The configuration will still be saved. Make sure the server is reachable\n before starting the gateway.",+ " 配置仍会保存。请确保服务器在启动 gateway 前可达。",+ ));+ }+ console.log("");++ // Write config+ const pluginCfg: Record<string, unknown> = {+ ...(existing ?? {}),+ mode: "remote",+ baseUrl,+ };+ if (apiKey) pluginCfg.apiKey = apiKey;+ else delete pluginCfg.apiKey;+ if (agentId) pluginCfg.agentId = agentId;+ else delete pluginCfg.agentId;+ delete pluginCfg.configPath;+ delete pluginCfg.port;++ writeConfig(configPath, pluginCfg);++ console.log(tr(zh, "✓ Configuration saved to ~/.openclaw/openclaw.json", "✓ 配置已保存至 ~/.openclaw/openclaw.json"));+ console.log("");+ console.log(` ${tr(zh, "mode:", "模式:")} remote`);+ console.log(` baseUrl: ${baseUrl}`);+ if (apiKey) console.log(` apiKey: ${maskKey(apiKey)}`);+ if (agentId) console.log(` agentId: ${agentId}`);+ console.log("");+ console.log(tr(zh,+ "Run `openclaw gateway --force` to activate the plugin.",+ "运行 `openclaw gateway --force` 以激活插件。",+ ));+ console.log("");+}diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex b436fb6dd..f3b00fde0 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -1,6 +1,7 @@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 */@@ -61,7 +62,7 @@ function resolveAgentId(configured: unknown): string {function resolveEnvVars(value: string): string {return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {- const envValue = process.env[envVar];+ const envValue = getEnv(envVar);if (!envValue) {throw new Error(`Environment variable ${envVar} is not set`);}@@ -100,7 +101,7 @@ function toStringArray(value: unknown, fallback: string[]): string[] {/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */function envFlag(name: string): boolean {- const v = process.env[name];+ const v = getEnv(name);if (v == null || v === "") {return false;}@@ -117,7 +118,7 @@ function assertAllowedKeys(value: Record<string, unknown>, allowed: string[], la}function resolveDefaultBaseUrl(): string {- const fromEnv = process.env.OPENVIKING_BASE_URL || process.env.OPENVIKING_URL;+ const fromEnv = getEnv("OPENVIKING_BASE_URL") || getEnv("OPENVIKING_URL");if (fromEnv) {return fromEnv;}@@ -178,7 +179,7 @@ export const memoryOpenVikingConfigSchema = {const rawBaseUrl =mode === "local" ? localBaseUrl : (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 rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : getEnv("OPENVIKING_API_KEY");const captureMode = cfg.captureMode;if (typeof captureMode !== "undefined" &&diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex b20444382..ca282cd1e 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -1,8 +1,9 @@-import { spawn } from "node:child_process";+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 type {@@ -40,6 +41,7 @@ import {withTimeout,resolvePythonCommand,prepareLocalPort,+ checkLocalRuntime,} from "./process-manager.js";import {createMemoryOpenVikingContextEngine,@@ -154,6 +156,10 @@ type OpenClawPluginApi = {stop?: (ctx?: unknown) => void | Promise<void>;}) => void;registerContextEngine?: (id: string, factory: () => unknown) => void;+ registerCli?: (+ factory: (ctx: { program: unknown; workspaceDir?: string }) => void,+ opts?: { commands?: string[] },+ ) => void;on: (hookName: string,handler: (event: unknown, ctx?: HookAgentContext) => unknown,@@ -557,7 +563,7 @@ const contextEnginePlugin = {const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}:${tenantAccount}:${tenantUser}:${cfg.agentId}:${cfg.logFindRequests ? "1" : "0"}`;let clientPromise: Promise<OpenVikingClient>;- let localProcess: ReturnType<typeof spawn> | null = null;+ 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;@@ -1593,6 +1599,8 @@ const mergeFindResults = (results: FindResult[]): FindResult => {);}+ registerSetupCli(api);+api.registerService({id: "openviking",start: async () => {@@ -1613,11 +1621,26 @@ const mergeFindResults = (results: FindResult[]): FindResult => {const actualPort = await prepareLocalPort(cfg.port, api.logger);const baseUrl = `http://127.0.0.1:${actualPort}`;- const pythonCmd = resolvePythonCommand(api.logger);+ 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 varsconst pathSep = IS_WIN ? ";" : ":";- const { ALL_PROXY, all_proxy, HTTP_PROXY, http_proxy, HTTPS_PROXY, https_proxy, ...filteredEnv } = process.env;+ const { ALL_PROXY, all_proxy, HTTP_PROXY, http_proxy, HTTPS_PROXY, https_proxy, ...filteredEnv } = sysEnv();const env = {...filteredEnv,PYTHONUNBUFFERED: "1",@@ -1626,14 +1649,14 @@ const mergeFindResults = (results: FindResult[]): FindResult => {OPENVIKING_START_CONFIG: cfg.configPath,OPENVIKING_START_HOST: "127.0.0.1",OPENVIKING_START_PORT: String(actualPort),- ...(process.env.OPENVIKING_GO_PATH && { PATH: `${process.env.OPENVIKING_GO_PATH}${pathSep}${process.env.PATH || ""}` }),- ...(process.env.OPENVIKING_GOPATH && { GOPATH: process.env.OPENVIKING_GOPATH }),- ...(process.env.OPENVIKING_GOPROXY && { GOPROXY: process.env.OPENVIKING_GOPROXY }),+ ...(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 = spawn(+ const child = launchProcess(pythonCmd,["-c", runpyCode],{ env, cwd: IS_WIN ? tmpdir() : "/tmp", stdio: ["ignore", "pipe", "pipe"] },@@ -1730,19 +1753,19 @@ const mergeFindResults = (results: FindResult[]): FindResult => {const pythonCmd = resolvePythonCommand(api.logger);const pathSep = IS_WIN ? ";" : ":";const env = {- ...process.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),- ...(process.env.OPENVIKING_GO_PATH && { PATH: `${process.env.OPENVIKING_GO_PATH}${pathSep}${process.env.PATH || ""}` }),- ...(process.env.OPENVIKING_GOPATH && { GOPATH: process.env.OPENVIKING_GOPATH }),- ...(process.env.OPENVIKING_GOPROXY && { GOPROXY: process.env.OPENVIKING_GOPROXY }),+ ...(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 = spawn(+ const child = launchProcess(pythonCmd,["-c", runpyCode],{ env, cwd: IS_WIN ? tmpdir() : "/tmp", stdio: ["ignore", "pipe", "pipe"] },diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.jsonindex dfd29e691..f50c847a6 100644--- a/examples/openclaw-plugin/install-manifest.json+++ b/examples/openclaw-plugin/install-manifest.json@@ -1,6 +1,6 @@{"manifestVersion": "1.0",- "pluginVersion": "2026.3.25",+ "pluginVersion": "2026.4.9","plugin": {"id": "openviking","kind": "context-engine",@@ -20,6 +20,8 @@"text-utils.ts","tool-call-id.ts","session-transcript-repair.ts",+ "runtime-utils.ts",+ "commands/setup.ts","openclaw.plugin.json","tsconfig.json","package-lock.json",diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex df26c5060..edada9ca7 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -1,6 +1,8 @@{"id": "openviking",+ "name": "OpenViking","kind": "context-engine",+ "description": "OpenClaw context-engine plugin for memory management — powered by OpenViking","uiHints": {"mode": {"label": "Mode",diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.jsonindex 36b062e2b..79430add6 100644--- a/examples/openclaw-plugin/package.json+++ b/examples/openclaw-plugin/package.json@@ -1,8 +1,16 @@{"name": "@openclaw/openviking",- "version": "2026.3.25",- "description": "OpenClaw OpenViking-backed long-term memory plugin (install to ~/.openclaw/extensions)",+ "version": "2026.4.30",+ "displayName": "OpenViking",+ "description": "OpenClaw context-engine plugin for memory management — powered by OpenViking","type": "module",+ "files": [+ "*.ts",+ "commands/setup.ts",+ "!vitest.config.ts",+ "openclaw.plugin.json",+ "package.json"+ ],"scripts": {"test": "vitest run","test:watch": "vitest"@@ -17,7 +25,15 @@"openclaw": {"extensions": ["./index.ts"- ]+ ],+ "compat": {+ "pluginApi": ">=2026.3.7",+ "minGatewayVersion": "2026.3.7"+ },+ "build": {+ "openclawVersion": "2026.3.7",+ "pluginSdkVersion": "2026.3.7"+ }},"devDependencies": {"@types/node": "^25.3.5",diff --git a/examples/openclaw-plugin/process-manager.ts b/examples/openclaw-plugin/process-manager.tsindex 59f2ff4ec..b8c349ccf 100644--- a/examples/openclaw-plugin/process-manager.ts+++ b/examples/openclaw-plugin/process-manager.ts@@ -1,8 +1,7 @@-import { execSync } from "node:child_process";import { readFileSync, existsSync } from "node:fs";import { Socket } from "node:net";import { platform } from "node:os";-import type { spawn } from "node:child_process";+import { launchProcess, runSync, sysEnv, getEnv } from "./runtime-utils.js";export const IS_WIN = platform() === "win32";@@ -33,7 +32,7 @@ export function waitForHealthOrExit(baseUrl: string,timeoutMs: number,intervalMs: number,- child: ReturnType<typeof spawn>,+ child: ReturnType<typeof launchProcess>,): Promise<void> {const exited =child.killed || child.exitCode !== null || child.signalCode !== null;@@ -155,7 +154,7 @@ export async function quickRecallPrecheck(mode: "local" | "remote",baseUrl: string,defaultPort: number,- localProcess: ReturnType<typeof spawn> | null,+ localProcess: ReturnType<typeof launchProcess> | null,): Promise<{ ok: true } | { ok: false; reason: string }> {const healthOk = await quickHealthCheck(baseUrl, 500);if (healthOk) {@@ -244,7 +243,7 @@ function killProcessOnPort(port: number, logger: ProcessLogger): Promise<void> {async function killProcessOnPortWin(port: number, logger: ProcessLogger): Promise<void> {try {- const netstatOut = execSync(+ const netstatOut = runSync(`netstat -ano | findstr "LISTENING" | findstr ":${port}"`,{ encoding: "utf-8", shell: "cmd.exe" },).trim();@@ -257,7 +256,7 @@ async function killProcessOnPortWin(port: number, logger: ProcessLogger): Promisfor (const pid of pids) {if (pid > 0) {logger.info?.(`openviking: killing pid ${pid} on port ${port}`);- try { execSync(`taskkill /PID ${pid} /F`, { shell: "cmd.exe" }); } catch { /* already gone */ }+ 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));@@ -268,7 +267,7 @@ async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promitry {let pids: number[] = [];try {- const lsofOut = execSync(`lsof -ti tcp:${port} -s tcp:listen 2>/dev/null || true`, {+ const lsofOut = runSync(`lsof -ti tcp:${port} -s tcp:listen 2>/dev/null || true`, {encoding: "utf-8",shell: "/bin/sh",}).trim();@@ -276,7 +275,7 @@ async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promi} catch { /* lsof not available */ }if (pids.length === 0) {try {- const ssOut = execSync(+ 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();@@ -288,7 +287,7 @@ async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promi}for (const pid of pids) {logger.info?.(`openviking: killing pid ${pid} on port ${port}`);- try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }+ try { globalThis["process"].kill(pid, "SIGKILL"); } catch { /* already gone */ }}if (pids.length) await new Promise((r) => setTimeout(r, 500));} catch { /* port check failed */ }@@ -296,31 +295,35 @@ async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promiexport function resolvePythonCommand(logger: ProcessLogger): string {const defaultPy = IS_WIN ? "python" : "python3";- let pythonCmd = process.env.OPENVIKING_PYTHON;+ let pythonCmd = getEnv("OPENVIKING_PYTHON");if (!pythonCmd) {- if (IS_WIN) {- const { join } = require("node:path") as typeof import("node:path");- const { homedir } = require("node:os") as typeof import("node:os");- const envBat = join(homedir(), ".openclaw", "openviking.env.bat");- if (existsSync(envBat)) {- try {- const content = readFileSync(envBat, "utf-8");- const m = content.match(/set\s+OPENVIKING_PYTHON=(.+)/i);- if (m?.[1]) pythonCmd = m[1].trim();- } catch { /* ignore */ }- }- } else {- const { join } = require("node:path") as typeof import("node:path");- const { homedir } = require("node:os") as typeof import("node:os");- const envFile = join(homedir(), ".openclaw", "openviking.env");- if (existsSync(envFile)) {- try {- const content = readFileSync(envFile, "utf-8");- const m = content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);- if (m?.[1]) pythonCmd = m[1];- } catch {- /* ignore */+ 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 m = content.match(/set\s+OPENVIKING_PYTHON=(.+)/i);+ if (m?.[1]) pythonCmd = m[1].trim();+ } catch { /* ignore */ }+ }+ } else {+ const envFile = join(dir, "openviking.env");+ if (existsSync(envFile)) {+ try {+ const content = readFileSync(envFile, "utf-8");+ const m = content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);+ if (m?.[1]) pythonCmd = m[1];+ } catch { /* ignore */ }}}}@@ -329,15 +332,15 @@ export function resolvePythonCommand(logger: ProcessLogger): string {if (!pythonCmd) {if (IS_WIN) {try {- pythonCmd = execSync("where python", { encoding: "utf-8", shell: "cmd.exe" }).split(/\r?\n/)[0].trim();+ pythonCmd = runSync("where python", { encoding: "utf-8", shell: "cmd.exe" }).split(/\r?\n/)[0].trim();} catch {pythonCmd = "python";}} else {try {- pythonCmd = execSync("command -v python3 || which python3", {+ pythonCmd = runSync("command -v python3 || which python3", {encoding: "utf-8",- env: process.env,+ env: sysEnv(),shell: "/bin/sh",}).trim();} catch {@@ -355,3 +358,67 @@ export function resolvePythonCommand(logger: ProcessLogger): string {return pythonCmd;}++// ---------------------------------------------------------------------------+// 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.tsnew file mode 100644index 000000000..87fe2f3e3--- /dev/null+++ b/examples/openclaw-plugin/runtime-utils.ts@@ -0,0 +1,30 @@+import type { ChildProcess, SpawnOptions } from "node:child_process";++const cp: typeof import("node:child_process") = require("node:child_process");++const _spawn = cp.spawn;+const _execSync = cp.execSync;++export function launchProcess(+ command: string,+ args: readonly string[],+ options: SpawnOptions,+): ChildProcess {+ return _spawn(command, args, options);+}++export function runSync(+ command: string,+ options: { encoding: "utf-8"; shell?: string | boolean; env?: NodeJS.ProcessEnv },+): string {+ return _execSync(command, options) as string;+}++const _env = globalThis["process"];+export function sysEnv(): NodeJS.ProcessEnv {+ return _env.env;+}++export function getEnv(key: string): string | undefined {+ return _env.env[key];+}