Skip to content

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

fix(openclaw-memory-plugin): improve port management and preserve existing config (#513)

Qin Haojie18ecc8eef86b
diff --git a/examples/openclaw-memory-plugin/config.ts b/examples/openclaw-memory-plugin/config.ts
index a8746f9c4..3fccd12ec 100644
--- a/examples/openclaw-memory-plugin/config.ts
+++ b/examples/openclaw-memory-plugin/config.ts
@@ -31,31 +31,22 @@ const DEFAULT_TARGET_URI = "viking://user/memories";
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_CAPTURE_MODE = "semantic";
const DEFAULT_CAPTURE_MAX_LENGTH = 24000;
-const DEFAULT_RECALL_LIMIT = 20;
+const DEFAULT_RECALL_LIMIT = 6;
const DEFAULT_RECALL_SCORE_THRESHOLD = 0.01;
const DEFAULT_INGEST_REPLY_ASSIST = true;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS = 2;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS = 120;
const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");
-function generateAgentId(): string {
- const { hostname } = require("node:os") as typeof import("node:os");
- const { randomBytes } = require("node:crypto") as typeof import("node:crypto");
- const host = hostname().split(".")[0]?.toLowerCase().replace(/[^a-z0-9-]/g, "") || "local";
- const random = randomBytes(4).toString("hex");
- return `openclaw-${host}-${random}`;
-}
+const DEFAULT_AGENT_ID = "default";
function resolveAgentId(configured: unknown): string {
if (typeof configured === "string" && configured.trim()) {
return configured.trim();
}
- // 生成随机唯一的默认 ID,不持久化
- return generateAgentId();
+ return DEFAULT_AGENT_ID;
}
-export { generateAgentId };
-
function resolveEnvVars(value: string): string {
return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
const envValue = process.env[envVar];
@@ -218,7 +209,7 @@ export const memoryOpenVikingConfigSchema = {
agentId: {
label: "Agent ID",
placeholder: "auto-generated",
- help: "Identifies this agent to OpenViking (sent as X-OpenViking-Agent header). A random unique ID is generated per session if not set.",
+ help: "Identifies this agent to OpenViking (sent as X-OpenViking-Agent header). Defaults to \"default\" if not set.",
},
apiKey: {
label: "OpenViking API Key",
diff --git a/examples/openclaw-memory-plugin/index.ts b/examples/openclaw-memory-plugin/index.ts
index 19eaab1f3..16d279507 100644
--- a/examples/openclaw-memory-plugin/index.ts
+++ b/examples/openclaw-memory-plugin/index.ts
@@ -28,9 +28,8 @@ import {
waitForHealth,
withTimeout,
quickRecallPrecheck,
- quickHealthCheck,
- quickTcpProbe,
resolvePythonCommand,
+ prepareLocalPort,
} from "./process-manager.js";
const memoryPlugin = {
@@ -539,34 +538,13 @@ const memoryPlugin = {
id: "memory-openviking",
start: async () => {
if (cfg.mode === "local" && resolveLocalClient) {
- const baseUrl = cfg.baseUrl;
const timeoutMs = 60_000;
const intervalMs = 500;
- // 1. Check if a healthy OpenViking is already running on this port — reuse it
- const existingHealthy = await quickHealthCheck(baseUrl, 2000);
- if (existingHealthy) {
- const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs);
- localClientCache.set(localCacheKey, { client, process: null });
- resolveLocalClient(client);
- rejectLocalClient = null;
- api.logger.info(
- `memory-openviking: reusing existing server at ${baseUrl}`,
- );
- return;
- }
- // 2. Check if port is occupied by something else
- const portOccupied = await quickTcpProbe("127.0.0.1", cfg.port, 500);
- if (portOccupied) {
- const msg = `memory-openviking: port ${cfg.port} is occupied by another process (not OpenViking). ` +
- `Change the port in your plugin config or ov.conf, e.g.: ` +
- `openclaw config set plugins.entries.memory-openviking.config.port 1934`;
- api.logger.warn(msg);
- markLocalUnavailable("port occupied", new Error(msg));
- throw new Error(msg);
- }
+ // Prepare port: kill stale OpenViking, or auto-find free port if occupied by others
+ const actualPort = await prepareLocalPort(cfg.port, api.logger);
+ const baseUrl = `http://127.0.0.1:${actualPort}`;
- // 3. Port is free — start OpenViking
const pythonCmd = resolvePythonCommand(api.logger);
// Inherit system environment; optionally override Go/Python paths via env vars
@@ -578,7 +556,7 @@ const memoryPlugin = {
OPENVIKING_CONFIG_FILE: cfg.configPath,
OPENVIKING_START_CONFIG: cfg.configPath,
OPENVIKING_START_HOST: "127.0.0.1",
- OPENVIKING_START_PORT: String(cfg.port),
+ 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 }),
diff --git a/examples/openclaw-memory-plugin/install.sh b/examples/openclaw-memory-plugin/install.sh
index 714d1e336..408801bbb 100644
--- a/examples/openclaw-memory-plugin/install.sh
+++ b/examples/openclaw-memory-plugin/install.sh
@@ -612,10 +612,24 @@ configure_openclaw_plugin() {
fi
"${oc_env[@]}" openclaw config set plugins.enabled true
- "${oc_env[@]}" openclaw config set plugins.allow '["memory-openviking"]' --json
+ # Merge into existing allow list instead of overwriting
+ local existing_allow
+ existing_allow=$("${oc_env[@]}" openclaw config get plugins.allow --json 2>/dev/null || echo '[]')
+ if ! echo "$existing_allow" | grep -q '"memory-openviking"'; then
+ existing_allow=$(echo "$existing_allow" | sed 's/]$//' | sed 's/$/,"memory-openviking"]/' | sed 's/\[,/[/')
+ fi
+ "${oc_env[@]}" openclaw config set plugins.allow "$existing_allow" --json
+
"${oc_env[@]}" openclaw config set gateway.mode local
"${oc_env[@]}" openclaw config set plugins.slots.memory memory-openviking
- "${oc_env[@]}" openclaw config set plugins.load.paths "[\"${PLUGIN_DEST}\"]" --json
+
+ # Merge into existing load paths instead of overwriting
+ local existing_paths
+ existing_paths=$("${oc_env[@]}" openclaw config get plugins.load.paths --json 2>/dev/null || echo '[]')
+ if ! echo "$existing_paths" | grep -q "\"${PLUGIN_DEST}\""; then
+ existing_paths=$(echo "$existing_paths" | sed 's/]$//' | sed "s/$/,\"${PLUGIN_DEST}\"]/" | sed 's/\[,/[/')
+ fi
+ "${oc_env[@]}" openclaw config set plugins.load.paths "$existing_paths" --json
"${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.mode "${SELECTED_MODE}"
"${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.targetUri viking://user/memories
"${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
diff --git a/examples/openclaw-memory-plugin/process-manager.ts b/examples/openclaw-memory-plugin/process-manager.ts
index 4972cbb0e..7a4f36379 100644
--- a/examples/openclaw-memory-plugin/process-manager.ts
+++ b/examples/openclaw-memory-plugin/process-manager.ts
@@ -134,6 +134,102 @@ export async function quickRecallPrecheck(
export interface ProcessLogger {
info?: (msg: string) => void;
+ warn?: (msg: string) => void;
+}
+
+/**
+ * Prepare a port for local OpenViking startup.
+ *
+ * 1. If the port hosts an OpenViking instance (health check passes) → kill it, return same port.
+ * 2. If the port is occupied by something else → auto-find the next free port.
+ * 3. If the port is free → return it as-is.
+ */
+export async function prepareLocalPort(
+ port: number,
+ logger: ProcessLogger,
+ maxRetries: number = 10,
+): Promise<number> {
+ const isOpenViking = await quickHealthCheck(`http://127.0.0.1:${port}`, 2000);
+ if (isOpenViking) {
+ logger.info?.(`memory-openviking: killing stale OpenViking on port ${port}`);
+ await killProcessOnPort(port, logger);
+ return port;
+ }
+
+ const occupied = await quickTcpProbe("127.0.0.1", port, 500);
+ if (!occupied) {
+ return port;
+ }
+
+ // Port occupied by non-OpenViking process — find next free port
+ logger.warn?.(`memory-openviking: port ${port} is occupied by another process, searching for a free port...`);
+ for (let candidate = port + 1; candidate <= port + maxRetries; candidate++) {
+ if (candidate > 65535) break;
+ const taken = await quickTcpProbe("127.0.0.1", candidate, 300);
+ if (!taken) {
+ logger.info?.(`memory-openviking: using free port ${candidate} instead of ${port}`);
+ return candidate;
+ }
+ }
+ throw new Error(
+ `memory-openviking: port ${port} is occupied and no free port found in range ${port + 1}-${port + maxRetries}`,
+ );
+}
+
+function killProcessOnPort(port: number, logger: ProcessLogger): Promise<void> {
+ return IS_WIN ? killProcessOnPortWin(port, logger) : killProcessOnPortUnix(port, logger);
+}
+
+async function killProcessOnPortWin(port: number, logger: ProcessLogger): Promise<void> {
+ try {
+ const netstatOut = execSync(
+ `netstat -ano | findstr "LISTENING" | findstr ":${port}"`,
+ { encoding: "utf-8", shell: "cmd.exe" },
+ ).trim();
+ if (!netstatOut) return;
+ const pids = new Set<number>();
+ for (const line of netstatOut.split(/\r?\n/)) {
+ const m = line.trim().match(/\s(\d+)\s*$/);
+ if (m) pids.add(Number(m[1]));
+ }
+ for (const pid of pids) {
+ if (pid > 0) {
+ logger.info?.(`memory-openviking: killing pid ${pid} on port ${port}`);
+ try { execSync(`taskkill /PID ${pid} /F`, { shell: "cmd.exe" }); } catch { /* already gone */ }
+ }
+ }
+ if (pids.size) await new Promise((r) => setTimeout(r, 500));
+ } catch { /* netstat not available or no stale process */ }
+}
+
+async function killProcessOnPortUnix(port: number, logger: ProcessLogger): Promise<void> {
+ try {
+ let pids: number[] = [];
+ try {
+ const lsofOut = execSync(`lsof -ti tcp:${port} -s tcp:listen 2>/dev/null || true`, {
+ encoding: "utf-8",
+ shell: "/bin/sh",
+ }).trim();
+ if (lsofOut) pids = lsofOut.split(/\s+/).map((s) => Number(s)).filter((n) => n > 0);
+ } catch { /* lsof not available */ }
+ if (pids.length === 0) {
+ try {
+ const ssOut = execSync(
+ `ss -tlnp 2>/dev/null | awk -v p=":${port}" '$4 ~ p {gsub(/.*pid=/,""); gsub(/,.*/,""); print; exit}'`,
+ { encoding: "utf-8", shell: "/bin/sh" },
+ ).trim();
+ if (ssOut) {
+ const n = Number(ssOut);
+ if (n > 0) pids = [n];
+ }
+ } catch { /* ss not available */ }
+ }
+ for (const pid of pids) {
+ logger.info?.(`memory-openviking: killing pid ${pid} on port ${port}`);
+ try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }
+ }
+ if (pids.length) await new Promise((r) => setTimeout(r, 500));
+ } catch { /* port check failed */ }
}
export function resolvePythonCommand(logger: ProcessLogger): string {
@@ -171,7 +267,7 @@ export function resolvePythonCommand(logger: ProcessLogger): string {
if (!pythonCmd) {
if (IS_WIN) {
try {
- pythonCmd = execSync("where python", { encoding: "utf-8", shell: true }).split(/\r?\n/)[0].trim();
+ pythonCmd = execSync("where python", { encoding: "utf-8", shell: "cmd.exe" }).split(/\r?\n/)[0].trim();
} catch {
pythonCmd = "python";
}
diff --git a/examples/openclaw-memory-plugin/setup-helper/cli.js b/examples/openclaw-memory-plugin/setup-helper/cli.js
index 3aa95b99a..6902abed6 100755
--- a/examples/openclaw-memory-plugin/setup-helper/cli.js
+++ b/examples/openclaw-memory-plugin/setup-helper/cli.js
@@ -488,7 +488,9 @@ async function configureOpenclawViaJson(pluginPath, serverPort, pluginMode = "lo
try { cfg = JSON.parse(await readFile(cfgPath, "utf8")); } catch { /* start fresh */ }
if (!cfg.plugins) cfg.plugins = {};
cfg.plugins.enabled = true;
- cfg.plugins.allow = ["memory-openviking"];
+ 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 = {};
@@ -535,7 +537,15 @@ async function configureOpenclawViaCli(pluginPath, serverPort, installMode, plug
await runNoShell("openclaw", ["config", "set", "plugins.load.paths", JSON.stringify([pluginPath])], { silent: true }).catch(() => {});
}
await runNoShell("openclaw", ["config", "set", "plugins.enabled", "true"]);
- await runNoShell("openclaw", ["config", "set", "plugins.allow", JSON.stringify(["memory-openviking"]), "--json"]);
+ // Merge into existing allow list instead of overwriting
+ let currentAllow = [];
+ try {
+ const raw = await run("openclaw", ["config", "get", "plugins.allow", "--json"], { ...extraEnv, silent: true });
+ currentAllow = JSON.parse(raw.stdout || "[]");
+ } 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]);
diff --git a/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
index e5789b052..545e2a0b8 100644
--- a/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
+++ b/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
@@ -60,7 +60,7 @@ Example: User says "Forget my phone number"
| `mode` | `remote` | `local` (start local server) or `remote` (connect to remote) |
| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL (remote mode) |
| `apiKey` | — | OpenViking API Key (optional) |
-| `agentId` | `openclaw-<hostname>` | Identifies this agent (auto-generated, persisted to `~/.openviking/.agent-id`) |
+| `agentId` | `default` | Identifies this agent to OpenViking |
| `configPath` | `~/.openviking/ov.conf` | Config file path (local mode) |
| `port` | `1933` | Local server port (local mode) |
| `targetUri` | `viking://user/memories` | Default search scope |