openclaw-openviking-setup-helper 0.2.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/install.js +1384 -113
  2. package/package.json +1 -1
package/install.js CHANGED
@@ -10,11 +10,11 @@
10
10
  * openclaw-openviking-install
11
11
  *
12
12
  * Direct run:
13
- * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ]
14
- * [ --openviking-version=V ] [ --repo=PATH ]
13
+ * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --upgrade-plugin ]
14
+ * [ --plugin-version=TAG ] [ --openviking-version=V ] [ --repo=PATH ]
15
15
  *
16
16
  * Environment variables:
17
- * REPO, BRANCH, OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING
17
+ * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING
18
18
  * OPENVIKING_VERSION Pip install openviking==VERSION (omit for latest)
19
19
  * OPENVIKING_REPO Repo path: source install (pip -e) + local plugin (default: off)
20
20
  * NPM_REGISTRY, PIP_INDEX_URL
@@ -23,26 +23,26 @@
23
23
  */
24
24
 
25
25
  import { spawn } from "node:child_process";
26
- import { mkdir, readFile, writeFile } from "node:fs/promises";
26
+ import { cp, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
27
27
  import { existsSync, readdirSync } from "node:fs";
28
- import { dirname, join } from "node:path";
28
+ import { basename, dirname, join, relative } from "node:path";
29
29
  import { createInterface } from "node:readline";
30
30
  import { fileURLToPath } from "node:url";
31
31
 
32
32
  const __dirname = dirname(fileURLToPath(import.meta.url));
33
33
 
34
- const REPO = process.env.REPO || "volcengine/OpenViking";
35
- const BRANCH = process.env.BRANCH || "main";
36
- const GH_RAW = `https://raw.githubusercontent.com/${REPO}/${BRANCH}`;
34
+ let REPO = process.env.REPO || "volcengine/OpenViking";
35
+ // PLUGIN_VERSION takes precedence over BRANCH (legacy)
36
+ let PLUGIN_VERSION = process.env.PLUGIN_VERSION || process.env.BRANCH || "main";
37
37
  const NPM_REGISTRY = process.env.NPM_REGISTRY || "https://registry.npmmirror.com";
38
- const PIP_INDEX_URL = process.env.PIP_INDEX_URL || "https://pypi.tuna.tsinghua.edu.cn/simple";
38
+ const PIP_INDEX_URL = process.env.PIP_INDEX_URL || "https://mirrors.volces.com/pypi/simple/";
39
39
 
40
40
  const IS_WIN = process.platform === "win32";
41
41
  const HOME = process.env.HOME || process.env.USERPROFILE || "";
42
42
 
43
43
  const DEFAULT_OPENCLAW_DIR = join(HOME, ".openclaw");
44
44
  let OPENCLAW_DIR = DEFAULT_OPENCLAW_DIR;
45
- let PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "openviking");
45
+ let PLUGIN_DEST = ""; // Will be set after resolving plugin config
46
46
 
47
47
  const OPENVIKING_DIR = join(HOME, ".openviking");
48
48
 
@@ -51,28 +51,62 @@ const DEFAULT_AGFS_PORT = 1833;
51
51
  const DEFAULT_VLM_MODEL = "doubao-seed-2-0-pro-260215";
52
52
  const DEFAULT_EMBED_MODEL = "doubao-embedding-vision-251215";
53
53
 
54
- const REQUIRED_PLUGIN_FILES = [
55
- "examples/openclaw-plugin/index.ts",
56
- "examples/openclaw-plugin/context-engine.ts",
57
- "examples/openclaw-plugin/config.ts",
58
- "examples/openclaw-plugin/openclaw.plugin.json",
59
- "examples/openclaw-plugin/package.json",
60
- "examples/openclaw-plugin/package-lock.json",
61
- "examples/openclaw-plugin/.gitignore",
54
+ // Fallback configs for old versions without manifest
55
+ const FALLBACK_LEGACY = {
56
+ dir: "openclaw-memory-plugin",
57
+ id: "memory-openviking",
58
+ kind: "memory",
59
+ slot: "memory",
60
+ required: ["index.ts", "config.ts", "openclaw.plugin.json", "package.json"],
61
+ optional: ["package-lock.json", ".gitignore"],
62
+ };
63
+
64
+ // Must match examples/openclaw-plugin/install-manifest.json (npm only installs package deps, not these .ts files).
65
+ const FALLBACK_CURRENT = {
66
+ dir: "openclaw-plugin",
67
+ id: "openviking",
68
+ kind: "context-engine",
69
+ slot: "contextEngine",
70
+ required: ["index.ts", "config.ts", "package.json"],
71
+ optional: [
72
+ "context-engine.ts",
73
+ "client.ts",
74
+ "process-manager.ts",
75
+ "memory-ranking.ts",
76
+ "text-utils.ts",
77
+ "tool-call-id.ts",
78
+ "session-transcript-repair.ts",
79
+ "openclaw.plugin.json",
80
+ "tsconfig.json",
81
+ "package-lock.json",
82
+ ".gitignore",
83
+ ],
84
+ };
85
+
86
+ const PLUGIN_VARIANTS = [
87
+ { ...FALLBACK_LEGACY, generation: "legacy", slotFallback: "none" },
88
+ { ...FALLBACK_CURRENT, generation: "current", slotFallback: "legacy" },
62
89
  ];
63
90
 
64
- const OPTIONAL_PLUGIN_FILES = [
65
- "examples/openclaw-plugin/client.ts",
66
- "examples/openclaw-plugin/process-manager.ts",
67
- "examples/openclaw-plugin/memory-ranking.ts",
68
- "examples/openclaw-plugin/text-utils.ts",
69
- ];
91
+ // Resolved plugin config (set by resolvePluginConfig)
92
+ let resolvedPluginDir = "";
93
+ let resolvedPluginId = "";
94
+ let resolvedPluginKind = "";
95
+ let resolvedPluginSlot = "";
96
+ let resolvedFilesRequired = [];
97
+ let resolvedFilesOptional = [];
98
+ let resolvedNpmOmitDev = true;
99
+ let resolvedMinOpenclawVersion = "";
100
+ let resolvedMinOpenvikingVersion = "";
101
+ let resolvedPluginReleaseId = "";
70
102
 
71
103
  let installYes = process.env.OPENVIKING_INSTALL_YES === "1";
72
104
  let langZh = false;
73
105
  let openvikingVersion = process.env.OPENVIKING_VERSION || "";
74
106
  let openvikingRepo = process.env.OPENVIKING_REPO || "";
75
107
  let workdirExplicit = false;
108
+ let upgradePluginOnly = false;
109
+ let rollbackLastUpgrade = false;
76
110
 
77
111
  let selectedMode = "local";
78
112
  let selectedServerPort = DEFAULT_SERVER_PORT;
@@ -80,6 +114,9 @@ let remoteBaseUrl = "http://127.0.0.1:1933";
80
114
  let remoteApiKey = "";
81
115
  let remoteAgentId = "";
82
116
  let openvikingPythonPath = "";
117
+ let upgradeRuntimeConfig = null;
118
+ let installedUpgradeState = null;
119
+ let upgradeAudit = null;
83
120
 
84
121
  const argv = process.argv.slice(2);
85
122
  for (let i = 0; i < argv.length; i++) {
@@ -92,6 +129,14 @@ for (let i = 0; i < argv.length; i++) {
92
129
  langZh = true;
93
130
  continue;
94
131
  }
132
+ if (arg === "--upgrade-plugin" || arg === "--update" || arg === "--upgrade") {
133
+ upgradePluginOnly = true;
134
+ continue;
135
+ }
136
+ if (arg === "--rollback" || arg === "--rollback-last-upgrade") {
137
+ rollbackLastUpgrade = true;
138
+ continue;
139
+ }
95
140
  if (arg === "--workdir") {
96
141
  const workdir = argv[i + 1]?.trim();
97
142
  if (!workdir) {
@@ -103,38 +148,128 @@ for (let i = 0; i < argv.length; i++) {
103
148
  i += 1;
104
149
  continue;
105
150
  }
151
+ if (arg.startsWith("--plugin-version=")) {
152
+ PLUGIN_VERSION = arg.slice("--plugin-version=".length).trim();
153
+ continue;
154
+ }
155
+ if (arg === "--plugin-version") {
156
+ const version = argv[i + 1]?.trim();
157
+ if (!version) {
158
+ console.error("--plugin-version requires a value");
159
+ process.exit(1);
160
+ }
161
+ PLUGIN_VERSION = version;
162
+ i += 1;
163
+ continue;
164
+ }
106
165
  if (arg.startsWith("--openviking-version=")) {
107
166
  openvikingVersion = arg.slice("--openviking-version=".length).trim();
108
167
  continue;
109
168
  }
169
+ if (arg === "--openviking-version") {
170
+ const version = argv[i + 1]?.trim();
171
+ if (!version) {
172
+ console.error("--openviking-version requires a value");
173
+ process.exit(1);
174
+ }
175
+ openvikingVersion = version;
176
+ i += 1;
177
+ continue;
178
+ }
110
179
  if (arg.startsWith("--repo=")) {
111
180
  openvikingRepo = arg.slice("--repo=".length).trim();
112
181
  continue;
113
182
  }
183
+ if (arg.startsWith("--github-repo=")) {
184
+ REPO = arg.slice("--github-repo=".length).trim();
185
+ continue;
186
+ }
187
+ if (arg === "--github-repo") {
188
+ const repo = argv[i + 1]?.trim();
189
+ if (!repo) {
190
+ console.error("--github-repo requires a value (e.g. owner/repo)");
191
+ process.exit(1);
192
+ }
193
+ REPO = repo;
194
+ i += 1;
195
+ continue;
196
+ }
114
197
  if (arg === "-h" || arg === "--help") {
115
198
  printHelp();
116
199
  process.exit(0);
117
200
  }
118
201
  }
119
202
 
120
- const OPENVIKING_PIP_SPEC = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";
121
-
122
203
  function setOpenClawDir(dir) {
123
204
  OPENCLAW_DIR = dir;
124
- PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", "openviking");
125
205
  }
126
206
 
127
207
  function printHelp() {
128
- console.log("Usage: node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --openviking-version=V ] [ --repo=PATH ]");
208
+ console.log("Usage: node install.js [ OPTIONS ]");
209
+ console.log("");
210
+ console.log("Options:");
211
+ console.log(" --github-repo=OWNER/REPO GitHub repository (default: volcengine/OpenViking)");
212
+ console.log(" --plugin-version=TAG Plugin version (Git tag, e.g. v0.2.9, default: main)");
213
+ console.log(" --openviking-version=V OpenViking PyPI version (e.g. 0.2.9, default: latest)");
214
+ console.log(" --workdir PATH OpenClaw config directory (default: ~/.openclaw)");
215
+ console.log(" --repo=PATH Use local OpenViking repo at PATH (pip -e + local plugin)");
216
+ console.log(" --update, --upgrade-plugin");
217
+ console.log(" Upgrade only the plugin to the requested --plugin-version; keep ov.conf and do not change the OpenViking service");
218
+ console.log(" --rollback, --rollback-last-upgrade");
219
+ console.log(" Roll back the last plugin upgrade using the saved audit/backup files");
220
+ console.log(" -y, --yes Non-interactive (use defaults)");
221
+ console.log(" --zh Chinese prompts");
222
+ console.log(" -h, --help This help");
129
223
  console.log("");
130
- console.log(" -y, --yes Non-interactive (use defaults)");
131
- console.log(" --zh Chinese prompts");
132
- console.log(" --workdir OpenClaw config directory (default: ~/.openclaw)");
133
- console.log(" --openviking-version=VERSION Pip install openviking==VERSION (default: latest)");
134
- console.log(" --repo=PATH Use OpenViking repo at PATH: pip install -e PATH, plugin from repo (default: off)");
135
- console.log(" -h, --help This help");
224
+ console.log("Examples:");
225
+ console.log(" # Install latest version");
226
+ console.log(" node install.js");
136
227
  console.log("");
137
- console.log("Env: OPENVIKING_REPO, REPO, BRANCH, SKIP_OPENCLAW, SKIP_OPENVIKING, OPENVIKING_VERSION, NPM_REGISTRY, PIP_INDEX_URL");
228
+ console.log(" # Install from a fork repository");
229
+ console.log(" node install.js --github-repo=yourname/OpenViking --plugin-version=dev-branch");
230
+ console.log("");
231
+ console.log(" # Install specific plugin version");
232
+ console.log(" node install.js --plugin-version=v0.2.8");
233
+ console.log("");
234
+ console.log(" # Upgrade only the plugin files");
235
+ console.log(" node install.js --update --plugin-version=main");
236
+ console.log("");
237
+ console.log(" # Roll back the last plugin upgrade");
238
+ console.log(" node install.js --rollback");
239
+ console.log("");
240
+ console.log("Env: REPO, PLUGIN_VERSION, OPENVIKING_VERSION, SKIP_OPENCLAW, SKIP_OPENVIKING, NPM_REGISTRY, PIP_INDEX_URL");
241
+ }
242
+
243
+ function formatCliArg(value) {
244
+ if (!value) {
245
+ return "";
246
+ }
247
+ return /[\s"]/u.test(value) ? JSON.stringify(value) : value;
248
+ }
249
+
250
+ function getLegacyInstallCommandHint() {
251
+ const override = process.env.OPENVIKING_INSTALL_LEGACY_HINT?.trim();
252
+ if (override) {
253
+ return override;
254
+ }
255
+
256
+ const invokedScript = process.argv[1] ? basename(process.argv[1]) : "";
257
+ const args = ["--plugin-version", "<legacy-version>"];
258
+ if (workdirExplicit || OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
259
+ args.push("--workdir", formatCliArg(OPENCLAW_DIR));
260
+ }
261
+ if (REPO !== "volcengine/OpenViking") {
262
+ args.push("--github-repo", formatCliArg(REPO));
263
+ }
264
+ if (langZh) {
265
+ args.push("--zh");
266
+ }
267
+
268
+ if (invokedScript === "install.js") {
269
+ return `node install.js ${args.join(" ")}`;
270
+ }
271
+
272
+ return `ov-install ${args.join(" ")}`;
138
273
  }
139
274
 
140
275
  function tr(en, zh) {
@@ -235,8 +370,19 @@ function question(prompt, defaultValue = "") {
235
370
  });
236
371
  }
237
372
 
373
+ async function resolveAbsoluteCommand(cmd) {
374
+ if (cmd.startsWith("/") || (IS_WIN && /^[A-Za-z]:[/\\]/.test(cmd))) return cmd;
375
+ if (IS_WIN) {
376
+ const r = await runCapture("where", [cmd], { shell: true });
377
+ return r.out.split(/\r?\n/)[0]?.trim() || cmd;
378
+ }
379
+ const r = await runCapture("which", [cmd], { shell: false });
380
+ return r.out.trim() || cmd;
381
+ }
382
+
238
383
  async function checkPython() {
239
- const py = process.env.OPENVIKING_PYTHON || (IS_WIN ? "python" : "python3");
384
+ const raw = process.env.OPENVIKING_PYTHON || (IS_WIN ? "python" : "python3");
385
+ const py = await resolveAbsoluteCommand(raw);
240
386
  const result = await runCapture(py, ["-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"]);
241
387
  if (result.code !== 0 || !result.out) {
242
388
  return {
@@ -390,6 +536,250 @@ async function checkOpenClaw() {
390
536
  process.exit(1);
391
537
  }
392
538
 
539
+ // Compare versions: returns true if v1 >= v2
540
+ function versionGte(v1, v2) {
541
+ const parseVersion = (v) => {
542
+ const cleaned = v.replace(/^v/, "").replace(/-.*$/, "");
543
+ const parts = cleaned.split(".").map((p) => Number.parseInt(p, 10) || 0);
544
+ while (parts.length < 3) parts.push(0);
545
+ return parts;
546
+ };
547
+ const [a1, a2, a3] = parseVersion(v1);
548
+ const [b1, b2, b3] = parseVersion(v2);
549
+ if (a1 !== b1) return a1 > b1;
550
+ if (a2 !== b2) return a2 > b2;
551
+ return a3 >= b3;
552
+ }
553
+
554
+ function isSemverLike(value) {
555
+ return /^v?\d+(\.\d+){1,2}$/.test(value);
556
+ }
557
+
558
+ function validateRequestedPluginVersion() {
559
+ if (!isSemverLike(PLUGIN_VERSION)) return;
560
+ if (versionGte(PLUGIN_VERSION, "v0.2.7") && !versionGte(PLUGIN_VERSION, "v0.2.8")) {
561
+ err(tr("Plugin version v0.2.7 does not exist.", "插件版本 v0.2.7 不存在。"));
562
+ process.exit(1);
563
+ }
564
+ }
565
+
566
+ if (upgradePluginOnly && rollbackLastUpgrade) {
567
+ console.error("--update/--upgrade-plugin and --rollback cannot be used together");
568
+ process.exit(1);
569
+ }
570
+
571
+ function ensurePluginOnlyOperationArgs() {
572
+ if ((upgradePluginOnly || rollbackLastUpgrade) && openvikingVersion) {
573
+ err(
574
+ tr(
575
+ "Plugin-only upgrade/rollback does not support --openviking-version. Use --plugin-version to choose the plugin release, and run a full install if you need to change the OpenViking service version.",
576
+ "仅插件升级或回滚不支持 --openviking-version。请使用 --plugin-version 指定插件版本;如果需要调整 OpenViking 服务版本,请执行完整安装流程。",
577
+ ),
578
+ );
579
+ process.exit(1);
580
+ }
581
+ }
582
+
583
+ // Detect OpenClaw version
584
+ async function detectOpenClawVersion() {
585
+ try {
586
+ const result = await runCapture("openclaw", ["--version"], { shell: IS_WIN });
587
+ if (result.code === 0 && result.out) {
588
+ const match = result.out.match(/\d+\.\d+(\.\d+)?/);
589
+ if (match) return match[0];
590
+ }
591
+ } catch {}
592
+ return "0.0.0";
593
+ }
594
+
595
+ // Try to fetch a URL, return response text or null
596
+ async function tryFetch(url, timeout = 15000) {
597
+ try {
598
+ const controller = new AbortController();
599
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
600
+ const response = await fetch(url, { signal: controller.signal });
601
+ clearTimeout(timeoutId);
602
+ if (response.ok) {
603
+ return await response.text();
604
+ }
605
+ } catch {}
606
+ return null;
607
+ }
608
+
609
+ // Check if a remote file exists
610
+ async function testRemoteFile(url) {
611
+ try {
612
+ const controller = new AbortController();
613
+ const timeoutId = setTimeout(() => controller.abort(), 10000);
614
+ const response = await fetch(url, { method: "HEAD", signal: controller.signal });
615
+ clearTimeout(timeoutId);
616
+ return response.ok;
617
+ } catch {}
618
+ return false;
619
+ }
620
+
621
+ // Resolve plugin configuration from manifest or fallback
622
+ async function resolvePluginConfig() {
623
+ const ghRaw = `https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}`;
624
+
625
+ info(tr(`Resolving plugin configuration for version: ${PLUGIN_VERSION}`, `正在解析插件配置,版本: ${PLUGIN_VERSION}`));
626
+
627
+ let pluginDir = "";
628
+ let manifestData = null;
629
+
630
+ // Try to detect plugin directory and download manifest
631
+ const manifestCurrent = await tryFetch(`${ghRaw}/examples/openclaw-plugin/install-manifest.json`);
632
+ if (manifestCurrent) {
633
+ pluginDir = "openclaw-plugin";
634
+ try {
635
+ manifestData = JSON.parse(manifestCurrent);
636
+ } catch {}
637
+ info(tr("Found manifest in openclaw-plugin", "在 openclaw-plugin 中找到 manifest"));
638
+ } else {
639
+ const manifestLegacy = await tryFetch(`${ghRaw}/examples/openclaw-memory-plugin/install-manifest.json`);
640
+ if (manifestLegacy) {
641
+ pluginDir = "openclaw-memory-plugin";
642
+ try {
643
+ manifestData = JSON.parse(manifestLegacy);
644
+ } catch {}
645
+ info(tr("Found manifest in openclaw-memory-plugin", "在 openclaw-memory-plugin 中找到 manifest"));
646
+ } else if (await testRemoteFile(`${ghRaw}/examples/openclaw-plugin/index.ts`)) {
647
+ pluginDir = "openclaw-plugin";
648
+ info(tr("No manifest found, using fallback for openclaw-plugin", "未找到 manifest,使用 openclaw-plugin 回退配置"));
649
+ } else if (await testRemoteFile(`${ghRaw}/examples/openclaw-memory-plugin/index.ts`)) {
650
+ pluginDir = "openclaw-memory-plugin";
651
+ info(tr("No manifest found, using fallback for openclaw-memory-plugin", "未找到 manifest,使用 openclaw-memory-plugin 回退配置"));
652
+ } else {
653
+ err(tr(`Cannot find plugin directory for version: ${PLUGIN_VERSION}`, `无法找到版本 ${PLUGIN_VERSION} 的插件目录`));
654
+ process.exit(1);
655
+ }
656
+ }
657
+
658
+ resolvedPluginDir = pluginDir;
659
+ resolvedPluginReleaseId = "";
660
+
661
+ if (manifestData) {
662
+ resolvedPluginId = manifestData.plugin?.id || "";
663
+ resolvedPluginKind = manifestData.plugin?.kind || "";
664
+ resolvedPluginSlot = manifestData.plugin?.slot || "";
665
+ resolvedMinOpenclawVersion = manifestData.compatibility?.minOpenclawVersion || "";
666
+ resolvedMinOpenvikingVersion = manifestData.compatibility?.minOpenvikingVersion || "";
667
+ resolvedPluginReleaseId = manifestData.pluginVersion || manifestData.release?.id || "";
668
+ resolvedNpmOmitDev = manifestData.npm?.omitDev !== false;
669
+ resolvedFilesRequired = manifestData.files?.required || [];
670
+ resolvedFilesOptional = manifestData.files?.optional || [];
671
+ } else {
672
+ // No manifest — determine plugin identity by package.json name
673
+ let fallbackKey = pluginDir === "openclaw-memory-plugin" ? "legacy" : "current";
674
+ let compatVer = "";
675
+
676
+ const pkgJson = await tryFetch(`${ghRaw}/examples/${pluginDir}/package.json`);
677
+ if (pkgJson) {
678
+ try {
679
+ const pkg = JSON.parse(pkgJson);
680
+ const pkgName = pkg.name || "";
681
+ resolvedPluginReleaseId = pkg.version || "";
682
+ if (pkgName && pkgName !== "@openclaw/openviking") {
683
+ fallbackKey = "legacy";
684
+ info(tr(`Detected legacy plugin by package name: ${pkgName}`, `通过 package.json 名称检测到旧版插件: ${pkgName}`));
685
+ } else if (pkgName) {
686
+ fallbackKey = "current";
687
+ }
688
+ compatVer = (pkg.engines?.openclaw || "").replace(/^>=?\s*/, "").trim();
689
+ if (compatVer) {
690
+ info(tr(`Read minOpenclawVersion from package.json engines.openclaw: >=${compatVer}`, `从 package.json engines.openclaw 读取到最低版本: >=${compatVer}`));
691
+ }
692
+ } catch {}
693
+ }
694
+
695
+ const fallback = fallbackKey === "legacy" ? FALLBACK_LEGACY : FALLBACK_CURRENT;
696
+ resolvedPluginDir = pluginDir;
697
+ resolvedPluginId = fallback.id;
698
+ resolvedPluginKind = fallback.kind;
699
+ resolvedPluginSlot = fallback.slot;
700
+ resolvedFilesRequired = fallback.required;
701
+ resolvedFilesOptional = fallback.optional;
702
+ resolvedNpmOmitDev = true;
703
+
704
+ // If no compatVer from package.json, try main branch manifest
705
+ if (!compatVer && PLUGIN_VERSION !== "main") {
706
+ const mainRaw = `https://raw.githubusercontent.com/${REPO}/main`;
707
+ const mainManifest = await tryFetch(`${mainRaw}/examples/openclaw-plugin/install-manifest.json`);
708
+ if (mainManifest) {
709
+ try {
710
+ const m = JSON.parse(mainManifest);
711
+ compatVer = m.compatibility?.minOpenclawVersion || "";
712
+ if (compatVer) {
713
+ info(tr(`Read minOpenclawVersion from main branch manifest: >=${compatVer}`, `从 main 分支 manifest 读取到最低版本: >=${compatVer}`));
714
+ }
715
+ } catch {}
716
+ }
717
+ }
718
+
719
+ resolvedMinOpenclawVersion = compatVer || "2026.3.7";
720
+ resolvedMinOpenvikingVersion = "";
721
+ }
722
+
723
+ // Set plugin destination
724
+ PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", resolvedPluginId);
725
+
726
+ info(tr(`Plugin: ${resolvedPluginId} (${resolvedPluginKind})`, `插件: ${resolvedPluginId} (${resolvedPluginKind})`));
727
+ }
728
+
729
+ // Check OpenClaw version compatibility
730
+ async function checkOpenClawCompatibility() {
731
+ if (process.env.SKIP_OPENCLAW === "1") {
732
+ return;
733
+ }
734
+
735
+ const ocVersion = await detectOpenClawVersion();
736
+ info(tr(`Detected OpenClaw version: ${ocVersion}`, `检测到 OpenClaw 版本: ${ocVersion}`));
737
+
738
+ // If no minimum version required, pass
739
+ if (!resolvedMinOpenclawVersion) {
740
+ return;
741
+ }
742
+
743
+ // If user explicitly requested an old version, pass
744
+ if (PLUGIN_VERSION !== "main" && isSemverLike(PLUGIN_VERSION) && !versionGte(PLUGIN_VERSION, "v0.2.8")) {
745
+ return;
746
+ }
747
+
748
+ // Check compatibility
749
+ if (!versionGte(ocVersion, resolvedMinOpenclawVersion)) {
750
+ err(tr(
751
+ `OpenClaw ${ocVersion} does not support this plugin (requires >= ${resolvedMinOpenclawVersion})`,
752
+ `OpenClaw ${ocVersion} 不支持此插件(需要 >= ${resolvedMinOpenclawVersion})`
753
+ ));
754
+ console.log("");
755
+ bold(tr("Please choose one of the following options:", "请选择以下方案之一:"));
756
+ console.log("");
757
+ console.log(` ${tr("Option 1: Upgrade OpenClaw", "方案 1:升级 OpenClaw")}`);
758
+ console.log(` npm update -g openclaw --registry ${NPM_REGISTRY}`);
759
+ console.log("");
760
+ console.log(` ${tr("Option 2: Install a legacy plugin release compatible with your current OpenClaw version", "方案 2:安装与当前 OpenClaw 版本兼容的旧版插件")}`);
761
+ console.log(` ${getLegacyInstallCommandHint()}`);
762
+ console.log("");
763
+ process.exit(1);
764
+ }
765
+ }
766
+
767
+ function checkRequestedOpenVikingCompatibility() {
768
+ if (!resolvedMinOpenvikingVersion || !openvikingVersion) return;
769
+ if (versionGte(openvikingVersion, resolvedMinOpenvikingVersion)) return;
770
+
771
+ err(tr(
772
+ `OpenViking ${openvikingVersion} does not support this plugin (requires >= ${resolvedMinOpenvikingVersion})`,
773
+ `OpenViking ${openvikingVersion} 不支持此插件(需要 >= ${resolvedMinOpenvikingVersion})`,
774
+ ));
775
+ console.log("");
776
+ console.log(tr(
777
+ "Use a newer OpenViking version, or omit --openviking-version to install the latest release.",
778
+ "请使用更新版本的 OpenViking,或省略 --openviking-version 以安装最新版本。",
779
+ ));
780
+ process.exit(1);
781
+ }
782
+
393
783
  async function installOpenViking() {
394
784
  if (process.env.SKIP_OPENVIKING === "1") {
395
785
  info(tr("Skipping OpenViking install (SKIP_OPENVIKING=1)", "跳过 OpenViking 安装 (SKIP_OPENVIKING=1)"));
@@ -401,6 +791,12 @@ async function installOpenViking() {
401
791
  err(tr("Python check failed.", "Python 校验失败"));
402
792
  process.exit(1);
403
793
  }
794
+ if (!python.ok) {
795
+ warn(tr(
796
+ `${python.detail}. Will attempt to find a suitable Python for pip install.`,
797
+ `${python.detail}。将尝试查找合适的 Python 进行 pip 安装。`,
798
+ ));
799
+ }
404
800
 
405
801
  const py = python.cmd;
406
802
 
@@ -413,14 +809,20 @@ async function installOpenViking() {
413
809
  return;
414
810
  }
415
811
 
416
- info(tr("Installing OpenViking from PyPI...", "正在安装 OpenViking (PyPI)..."));
812
+ // Determine package spec
813
+ const pkgSpec = openvikingVersion ? `openviking==${openvikingVersion}` : "openviking";
814
+ if (openvikingVersion) {
815
+ info(tr(`Installing OpenViking ${openvikingVersion} from PyPI...`, `正在安装 OpenViking ${openvikingVersion} (PyPI)...`));
816
+ } else {
817
+ info(tr("Installing OpenViking (latest) from PyPI...", "正在安装 OpenViking (最新版) (PyPI)..."));
818
+ }
417
819
  info(tr(`Using pip index: ${PIP_INDEX_URL}`, `使用 pip 镜像源: ${PIP_INDEX_URL}`));
418
820
 
419
- info(`Package: ${OPENVIKING_PIP_SPEC}`);
821
+ info(`Package: ${pkgSpec}`);
420
822
  await runCapture(py, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });
421
823
  const installResult = await runLiveCapture(
422
824
  py,
423
- ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
825
+ ["-m", "pip", "install", "--progress-bar", "on", pkgSpec, "-i", PIP_INDEX_URL],
424
826
  { shell: false },
425
827
  );
426
828
  if (installResult.code === 0) {
@@ -440,7 +842,7 @@ async function installOpenViking() {
440
842
  if (reuseCheck.code === 0) {
441
843
  await runLiveCapture(
442
844
  venvPy,
443
- ["-m", "pip", "install", "--progress-bar", "on", "-U", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
845
+ ["-m", "pip", "install", "--progress-bar", "on", "-U", pkgSpec, "-i", PIP_INDEX_URL],
444
846
  { shell: false },
445
847
  );
446
848
  openvikingPythonPath = venvPy;
@@ -476,7 +878,7 @@ async function installOpenViking() {
476
878
  await runCapture(venvPy, ["-m", "pip", "install", "--upgrade", "pip", "-q", "-i", PIP_INDEX_URL], { shell: false });
477
879
  const venvInstall = await runLiveCapture(
478
880
  venvPy,
479
- ["-m", "pip", "install", "--progress-bar", "on", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
881
+ ["-m", "pip", "install", "--progress-bar", "on", pkgSpec, "-i", PIP_INDEX_URL],
480
882
  { shell: false },
481
883
  );
482
884
  if (venvInstall.code === 0) {
@@ -493,7 +895,7 @@ async function installOpenViking() {
493
895
  if (process.env.OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES === "1") {
494
896
  const systemInstall = await runLiveCapture(
495
897
  py,
496
- ["-m", "pip", "install", "--progress-bar", "on", "--break-system-packages", OPENVIKING_PIP_SPEC, "-i", PIP_INDEX_URL],
898
+ ["-m", "pip", "install", "--progress-bar", "on", "--break-system-packages", pkgSpec, "-i", PIP_INDEX_URL],
497
899
  { shell: false },
498
900
  );
499
901
  if (systemInstall.code === 0) {
@@ -560,7 +962,7 @@ async function configureOvConf() {
560
962
  },
561
963
  embedding: {
562
964
  dense: {
563
- backend: "volcengine",
965
+ provider: "volcengine",
564
966
  api_key: embeddingApiKey || null,
565
967
  model: embeddingModel,
566
968
  api_base: "https://ark.cn-beijing.volces.com/api/v3",
@@ -569,7 +971,7 @@ async function configureOvConf() {
569
971
  },
570
972
  },
571
973
  vlm: {
572
- backend: "volcengine",
974
+ provider: "volcengine",
573
975
  api_key: vlmApiKey || null,
574
976
  model: vlmModel,
575
977
  api_base: "https://ark.cn-beijing.volces.com/api/v3",
@@ -583,118 +985,886 @@ async function configureOvConf() {
583
985
  info(tr(`Config generated: ${configPath}`, `已生成配置: ${configPath}`));
584
986
  }
585
987
 
586
- async function downloadPluginFile(relPath, required, index, total) {
587
- const fileName = relPath.split("/").pop();
588
- const url = `${GH_RAW}/${relPath}`;
988
+ function getOpenClawConfigPath() {
989
+ return join(OPENCLAW_DIR, "openclaw.json");
990
+ }
991
+
992
+ function getOpenClawEnv() {
993
+ if (OPENCLAW_DIR === DEFAULT_OPENCLAW_DIR) {
994
+ return { ...process.env };
995
+ }
996
+ return { ...process.env, OPENCLAW_STATE_DIR: OPENCLAW_DIR };
997
+ }
998
+
999
+ async function readJsonFileIfExists(filePath) {
1000
+ if (!existsSync(filePath)) return null;
1001
+ const raw = await readFile(filePath, "utf8");
1002
+ return JSON.parse(raw);
1003
+ }
1004
+
1005
+ function getInstallStatePathForPlugin(pluginId) {
1006
+ return join(OPENCLAW_DIR, "extensions", pluginId, ".ov-install-state.json");
1007
+ }
1008
+
1009
+ function getUpgradeAuditDir() {
1010
+ return join(OPENCLAW_DIR, ".openviking-upgrade-backup");
1011
+ }
1012
+
1013
+ function getUpgradeAuditPath() {
1014
+ return join(getUpgradeAuditDir(), "last-upgrade.json");
1015
+ }
1016
+
1017
+ function getOpenClawConfigBackupPath() {
1018
+ return join(getUpgradeAuditDir(), "openclaw.json.bak");
1019
+ }
1020
+
1021
+ function normalizePluginMode(value) {
1022
+ return value === "remote" ? "remote" : "local";
1023
+ }
1024
+
1025
+ function getPluginVariantById(pluginId) {
1026
+ return PLUGIN_VARIANTS.find((variant) => variant.id === pluginId) || null;
1027
+ }
1028
+
1029
+ function detectPluginPresence(config, variant) {
1030
+ const plugins = config?.plugins;
1031
+ const reasons = [];
1032
+ if (!plugins) {
1033
+ return { variant, present: false, reasons };
1034
+ }
1035
+
1036
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) {
1037
+ reasons.push("entry");
1038
+ }
1039
+ if (plugins.slots?.[variant.slot] === variant.id) {
1040
+ reasons.push("slot");
1041
+ }
1042
+ if (Array.isArray(plugins.allow) && plugins.allow.includes(variant.id)) {
1043
+ reasons.push("allow");
1044
+ }
1045
+ if (
1046
+ Array.isArray(plugins.load?.paths)
1047
+ && plugins.load.paths.some((item) => typeof item === "string" && (item.includes(variant.id) || item.includes(variant.dir)))
1048
+ ) {
1049
+ reasons.push("loadPath");
1050
+ }
1051
+ if (existsSync(join(OPENCLAW_DIR, "extensions", variant.id))) {
1052
+ reasons.push("dir");
1053
+ }
1054
+
1055
+ return { variant, present: reasons.length > 0, reasons };
1056
+ }
1057
+
1058
+ async function detectInstalledPluginState() {
1059
+ const configPath = getOpenClawConfigPath();
1060
+ const config = await readJsonFileIfExists(configPath);
1061
+ const detections = [];
1062
+ for (const variant of PLUGIN_VARIANTS) {
1063
+ const detection = detectPluginPresence(config, variant);
1064
+ if (!detection.present) continue;
1065
+ detection.installState = await readJsonFileIfExists(getInstallStatePathForPlugin(variant.id));
1066
+ detections.push(detection);
1067
+ }
1068
+
1069
+ let generation = "none";
1070
+ if (detections.length === 1) {
1071
+ generation = detections[0].variant.generation;
1072
+ } else if (detections.length > 1) {
1073
+ generation = "mixed";
1074
+ }
1075
+
1076
+ return {
1077
+ config,
1078
+ configPath,
1079
+ detections,
1080
+ generation,
1081
+ };
1082
+ }
1083
+
1084
+ function formatInstalledDetectionLabel(detection) {
1085
+ const requestedRef = detection.installState?.requestedRef;
1086
+ const releaseId = detection.installState?.releaseId;
1087
+ if (requestedRef) return `${detection.variant.id}@${requestedRef}`;
1088
+ if (releaseId) return `${detection.variant.id}#${releaseId}`;
1089
+ return `${detection.variant.id} (${detection.variant.generation}, exact version unknown)`;
1090
+ }
1091
+
1092
+ function formatInstalledStateLabel(installedState) {
1093
+ if (!installedState?.detections?.length) {
1094
+ return "not-installed";
1095
+ }
1096
+ return installedState.detections.map(formatInstalledDetectionLabel).join(" + ");
1097
+ }
1098
+
1099
+ function formatTargetVersionLabel() {
1100
+ const base = `${resolvedPluginId || "openviking"}@${PLUGIN_VERSION}`;
1101
+ if (resolvedPluginReleaseId && resolvedPluginReleaseId !== PLUGIN_VERSION) {
1102
+ return `${base} (${resolvedPluginReleaseId})`;
1103
+ }
1104
+ return base;
1105
+ }
1106
+
1107
+ function extractRuntimeConfigFromPluginEntry(entryConfig) {
1108
+ if (!entryConfig || typeof entryConfig !== "object") return null;
1109
+
1110
+ const mode = normalizePluginMode(entryConfig.mode);
1111
+ const runtime = { mode };
1112
+
1113
+ if (mode === "remote") {
1114
+ if (typeof entryConfig.baseUrl === "string" && entryConfig.baseUrl.trim()) {
1115
+ runtime.baseUrl = entryConfig.baseUrl.trim();
1116
+ }
1117
+ if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) {
1118
+ runtime.apiKey = entryConfig.apiKey;
1119
+ }
1120
+ if (typeof entryConfig.agentId === "string" && entryConfig.agentId.trim()) {
1121
+ runtime.agentId = entryConfig.agentId.trim();
1122
+ }
1123
+ return runtime;
1124
+ }
1125
+
1126
+ if (typeof entryConfig.configPath === "string" && entryConfig.configPath.trim()) {
1127
+ runtime.configPath = entryConfig.configPath.trim();
1128
+ }
1129
+ if (entryConfig.port !== undefined && entryConfig.port !== null && `${entryConfig.port}`.trim()) {
1130
+ const parsedPort = Number.parseInt(String(entryConfig.port), 10);
1131
+ if (Number.isFinite(parsedPort) && parsedPort > 0) {
1132
+ runtime.port = parsedPort;
1133
+ }
1134
+ }
1135
+ return runtime;
1136
+ }
1137
+
1138
+ async function readPortFromOvConf(configPath) {
1139
+ const filePath = configPath || join(OPENVIKING_DIR, "ov.conf");
1140
+ if (!existsSync(filePath)) return null;
1141
+ try {
1142
+ const ovConf = await readJsonFileIfExists(filePath);
1143
+ const parsedPort = Number.parseInt(String(ovConf?.server?.port ?? ""), 10);
1144
+ return Number.isFinite(parsedPort) && parsedPort > 0 ? parsedPort : null;
1145
+ } catch {
1146
+ return null;
1147
+ }
1148
+ }
1149
+
1150
+ async function backupOpenClawConfig(configPath) {
1151
+ await mkdir(getUpgradeAuditDir(), { recursive: true });
1152
+ const backupPath = getOpenClawConfigBackupPath();
1153
+ const configText = await readFile(configPath, "utf8");
1154
+ await writeFile(backupPath, configText, "utf8");
1155
+ return backupPath;
1156
+ }
1157
+
1158
+ async function writeUpgradeAuditFile(data) {
1159
+ await mkdir(getUpgradeAuditDir(), { recursive: true });
1160
+ await writeFile(getUpgradeAuditPath(), `${JSON.stringify(data, null, 2)}\n`, "utf8");
1161
+ }
1162
+
1163
+ async function writeInstallStateFile({ operation, fromVersion, configBackupPath, pluginBackups }) {
1164
+ const installStatePath = getInstallStatePathForPlugin(resolvedPluginId || "openviking");
1165
+ const state = {
1166
+ pluginId: resolvedPluginId || "openviking",
1167
+ generation: getPluginVariantById(resolvedPluginId || "openviking")?.generation || "unknown",
1168
+ requestedRef: PLUGIN_VERSION,
1169
+ releaseId: resolvedPluginReleaseId || "",
1170
+ operation,
1171
+ fromVersion: fromVersion || "",
1172
+ configBackupPath: configBackupPath || "",
1173
+ pluginBackups: pluginBackups || [],
1174
+ installedAt: new Date().toISOString(),
1175
+ repo: REPO,
1176
+ };
1177
+ await writeFile(installStatePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
1178
+ }
1179
+
1180
+ async function moveDirWithFallback(sourceDir, destDir) {
1181
+ try {
1182
+ await rename(sourceDir, destDir);
1183
+ } catch {
1184
+ await cp(sourceDir, destDir, { recursive: true, force: true });
1185
+ await rm(sourceDir, { recursive: true, force: true });
1186
+ }
1187
+ }
1188
+
1189
+ async function rollbackLastUpgradeOperation() {
1190
+ const auditPath = getUpgradeAuditPath();
1191
+ const audit = await readJsonFileIfExists(auditPath);
1192
+ if (!audit) {
1193
+ err(
1194
+ tr(
1195
+ `No rollback audit file found at ${auditPath}.`,
1196
+ `未找到回滚审计文件: ${auditPath}`,
1197
+ ),
1198
+ );
1199
+ process.exit(1);
1200
+ }
1201
+
1202
+ if (audit.rolledBackAt) {
1203
+ warn(
1204
+ tr(
1205
+ `The last recorded upgrade was already rolled back at ${audit.rolledBackAt}.`,
1206
+ `最近一次升级已在 ${audit.rolledBackAt} 回滚。`,
1207
+ ),
1208
+ );
1209
+ }
1210
+
1211
+ const configBackupPath = audit.configBackupPath || getOpenClawConfigBackupPath();
1212
+ if (!existsSync(configBackupPath)) {
1213
+ err(
1214
+ tr(
1215
+ `Rollback config backup is missing: ${configBackupPath}`,
1216
+ `回滚配置备份缺失: ${configBackupPath}`,
1217
+ ),
1218
+ );
1219
+ process.exit(1);
1220
+ }
1221
+
1222
+ const pluginBackups = Array.isArray(audit.pluginBackups) ? audit.pluginBackups : [];
1223
+ if (pluginBackups.length === 0) {
1224
+ err(tr("Rollback audit file contains no plugin backups.", "回滚审计文件中没有插件备份信息。"));
1225
+ process.exit(1);
1226
+ }
1227
+ for (const pluginBackup of pluginBackups) {
1228
+ if (!pluginBackup?.pluginId || !pluginBackup?.backupDir || !existsSync(pluginBackup.backupDir)) {
1229
+ err(
1230
+ tr(
1231
+ `Rollback plugin backup is missing: ${pluginBackup?.backupDir || "<unknown>"}`,
1232
+ `回滚插件备份缺失: ${pluginBackup?.backupDir || "<unknown>"}`,
1233
+ ),
1234
+ );
1235
+ process.exit(1);
1236
+ }
1237
+ }
1238
+
1239
+ info(tr(`Rolling back last upgrade: ${audit.fromVersion || "unknown"} <- ${audit.toVersion || "unknown"}`, `开始回滚最近一次升级: ${audit.fromVersion || "unknown"} <- ${audit.toVersion || "unknown"}`));
1240
+ await stopOpenClawGatewayForUpgrade();
1241
+
1242
+ const configText = await readFile(configBackupPath, "utf8");
1243
+ await writeFile(getOpenClawConfigPath(), configText, "utf8");
1244
+ info(tr(`Restored openclaw.json from backup: ${configBackupPath}`, `已从备份恢复 openclaw.json: ${configBackupPath}`));
1245
+
1246
+ const extensionsDir = join(OPENCLAW_DIR, "extensions");
1247
+ await mkdir(extensionsDir, { recursive: true });
1248
+ for (const variant of PLUGIN_VARIANTS) {
1249
+ const liveDir = join(extensionsDir, variant.id);
1250
+ if (existsSync(liveDir)) {
1251
+ await rm(liveDir, { recursive: true, force: true });
1252
+ }
1253
+ }
1254
+
1255
+ for (const pluginBackup of pluginBackups) {
1256
+ if (!pluginBackup?.pluginId || !pluginBackup?.backupDir) continue;
1257
+ if (!existsSync(pluginBackup.backupDir)) {
1258
+ err(
1259
+ tr(
1260
+ `Rollback plugin backup is missing: ${pluginBackup.backupDir}`,
1261
+ `回滚插件备份缺失: ${pluginBackup.backupDir}`,
1262
+ ),
1263
+ );
1264
+ process.exit(1);
1265
+ }
1266
+ const destDir = join(extensionsDir, pluginBackup.pluginId);
1267
+ await moveDirWithFallback(pluginBackup.backupDir, destDir);
1268
+ info(tr(`Restored plugin directory: ${destDir}`, `已恢复插件目录: ${destDir}`));
1269
+ }
1270
+
1271
+ audit.rolledBackAt = new Date().toISOString();
1272
+ audit.rollbackConfigPath = configBackupPath;
1273
+ await writeUpgradeAuditFile(audit);
1274
+
1275
+ console.log("");
1276
+ bold(tr("Rollback complete!", "回滚完成!"));
1277
+ console.log("");
1278
+ info(tr(`Rollback audit file: ${auditPath}`, `回滚审计文件: ${auditPath}`));
1279
+ info(tr("Run `openclaw gateway` and `openclaw status` to verify the restored plugin state.", "请运行 `openclaw gateway` 和 `openclaw status` 验证恢复后的插件状态。"));
1280
+ }
1281
+
1282
+ async function prepareUpgradeRuntimeConfig(installedState) {
1283
+ const plugins = installedState.config?.plugins ?? {};
1284
+ const candidateOrder = installedState.detections
1285
+ .map((item) => item.variant)
1286
+ .sort((left, right) => (right.generation === "current" ? 1 : 0) - (left.generation === "current" ? 1 : 0));
1287
+
1288
+ let runtime = null;
1289
+ for (const variant of candidateOrder) {
1290
+ const entryConfig = extractRuntimeConfigFromPluginEntry(plugins.entries?.[variant.id]?.config);
1291
+ if (entryConfig) {
1292
+ runtime = entryConfig;
1293
+ break;
1294
+ }
1295
+ }
1296
+
1297
+ if (!runtime) {
1298
+ runtime = { mode: "local" };
1299
+ }
1300
+
1301
+ if (runtime.mode === "remote") {
1302
+ runtime.baseUrl = runtime.baseUrl || remoteBaseUrl;
1303
+ return runtime;
1304
+ }
1305
+
1306
+ runtime.configPath = runtime.configPath || join(OPENVIKING_DIR, "ov.conf");
1307
+ runtime.port = runtime.port || await readPortFromOvConf(runtime.configPath) || DEFAULT_SERVER_PORT;
1308
+ return runtime;
1309
+ }
1310
+
1311
+ function removePluginConfig(config, variant) {
1312
+ const plugins = config?.plugins;
1313
+ if (!plugins) return false;
1314
+
1315
+ let changed = false;
1316
+
1317
+ if (Array.isArray(plugins.allow)) {
1318
+ const nextAllow = plugins.allow.filter((item) => item !== variant.id);
1319
+ changed = changed || nextAllow.length !== plugins.allow.length;
1320
+ plugins.allow = nextAllow;
1321
+ }
1322
+
1323
+ if (Array.isArray(plugins.load?.paths)) {
1324
+ const nextPaths = plugins.load.paths.filter(
1325
+ (item) => typeof item !== "string" || (!item.includes(variant.id) && !item.includes(variant.dir)),
1326
+ );
1327
+ changed = changed || nextPaths.length !== plugins.load.paths.length;
1328
+ plugins.load.paths = nextPaths;
1329
+ }
1330
+
1331
+ if (plugins.entries && Object.prototype.hasOwnProperty.call(plugins.entries, variant.id)) {
1332
+ delete plugins.entries[variant.id];
1333
+ changed = true;
1334
+ }
1335
+
1336
+ if (plugins.slots?.[variant.slot] === variant.id) {
1337
+ plugins.slots[variant.slot] = variant.slotFallback;
1338
+ changed = true;
1339
+ }
1340
+
1341
+ return changed;
1342
+ }
1343
+
1344
+ async function prunePreviousUpgradeBackups(disabledDir, variant, keepDir) {
1345
+ if (!existsSync(disabledDir)) return;
1346
+
1347
+ const prefix = `${variant.id}-upgrade-backup-`;
1348
+ const keepName = keepDir ? keepDir.split(/[\\/]/).pop() : "";
1349
+ const entries = readdirSync(disabledDir, { withFileTypes: true });
1350
+ for (const entry of entries) {
1351
+ if (!entry.isDirectory()) continue;
1352
+ if (!entry.name.startsWith(prefix)) continue;
1353
+ if (keepName && entry.name === keepName) continue;
1354
+ await rm(join(disabledDir, entry.name), { recursive: true, force: true });
1355
+ }
1356
+ }
1357
+
1358
+ async function backupPluginDirectory(variant) {
1359
+ const pluginDir = join(OPENCLAW_DIR, "extensions", variant.id);
1360
+ if (!existsSync(pluginDir)) return null;
1361
+
1362
+ const disabledDir = join(OPENCLAW_DIR, "disabled-extensions");
1363
+ const backupDir = join(disabledDir, `${variant.id}-upgrade-backup-${Date.now()}`);
1364
+ await mkdir(disabledDir, { recursive: true });
1365
+ try {
1366
+ await rename(pluginDir, backupDir);
1367
+ } catch {
1368
+ await cp(pluginDir, backupDir, { recursive: true, force: true });
1369
+ await rm(pluginDir, { recursive: true, force: true });
1370
+ }
1371
+ info(tr(`Backed up plugin directory: ${backupDir}`, `已备份插件目录: ${backupDir}`));
1372
+ await prunePreviousUpgradeBackups(disabledDir, variant, backupDir);
1373
+ return backupDir;
1374
+ }
1375
+
1376
+ async function stopOpenClawGatewayForUpgrade() {
1377
+ const result = await runCapture("openclaw", ["gateway", "stop"], {
1378
+ env: getOpenClawEnv(),
1379
+ shell: IS_WIN,
1380
+ });
1381
+ if (result.code === 0) {
1382
+ info(tr("Stopped OpenClaw gateway before plugin upgrade", "升级插件前已停止 OpenClaw gateway"));
1383
+ } else {
1384
+ warn(tr("OpenClaw gateway may not be running; continuing", "OpenClaw gateway 可能未在运行,继续执行"));
1385
+ }
1386
+ }
1387
+
1388
+ function shouldClaimTargetSlot(installedState) {
1389
+ const currentOwner = installedState.config?.plugins?.slots?.[resolvedPluginSlot];
1390
+ if (!currentOwner || currentOwner === "none" || currentOwner === "legacy" || currentOwner === resolvedPluginId) {
1391
+ return true;
1392
+ }
1393
+ const currentOwnerVariant = getPluginVariantById(currentOwner);
1394
+ if (currentOwnerVariant && installedState.detections.some((item) => item.variant.id === currentOwnerVariant.id)) {
1395
+ return true;
1396
+ }
1397
+ return false;
1398
+ }
1399
+
1400
+ async function cleanupInstalledPluginConfig(installedState) {
1401
+ if (!installedState.config || !installedState.config.plugins) {
1402
+ warn(tr("openclaw.json has no plugins section; skipped targeted plugin cleanup", "openclaw.json 中没有 plugins 配置,已跳过定向插件清理"));
1403
+ return;
1404
+ }
1405
+
1406
+ const nextConfig = structuredClone(installedState.config);
1407
+ let changed = false;
1408
+ for (const detection of installedState.detections) {
1409
+ changed = removePluginConfig(nextConfig, detection.variant) || changed;
1410
+ }
1411
+
1412
+ if (!changed) {
1413
+ info(tr("No OpenViking plugin config changes were required", "无需修改 OpenViking 插件配置"));
1414
+ return;
1415
+ }
1416
+
1417
+ await writeFile(installedState.configPath, `${JSON.stringify(nextConfig, null, 2)}\n`, "utf8");
1418
+ info(tr("Cleaned existing OpenViking plugin config only", "已仅清理 OpenViking 自身插件配置"));
1419
+ }
1420
+
1421
+ async function prepareStrongPluginUpgrade() {
1422
+ const installedState = await detectInstalledPluginState();
1423
+ if (installedState.generation === "none") {
1424
+ err(
1425
+ tr(
1426
+ "Plugin upgrade mode requires an existing OpenViking plugin entry in openclaw.json.",
1427
+ "插件升级模式要求 openclaw.json 中已经存在 OpenViking 插件记录。",
1428
+ ),
1429
+ );
1430
+ process.exit(1);
1431
+ }
1432
+
1433
+ installedUpgradeState = installedState;
1434
+ upgradeRuntimeConfig = await prepareUpgradeRuntimeConfig(installedState);
1435
+ const fromVersion = formatInstalledStateLabel(installedState);
1436
+ const toVersion = formatTargetVersionLabel();
1437
+ selectedMode = upgradeRuntimeConfig.mode;
1438
+ info(
1439
+ tr(
1440
+ `Detected installed OpenViking plugin state: ${installedState.generation}`,
1441
+ `检测到已安装 OpenViking 插件状态: ${installedState.generation}`,
1442
+ ),
1443
+ );
1444
+ if (upgradeRuntimeConfig.mode === "remote") {
1445
+ remoteBaseUrl = upgradeRuntimeConfig.baseUrl || remoteBaseUrl;
1446
+ remoteApiKey = upgradeRuntimeConfig.apiKey || "";
1447
+ remoteAgentId = upgradeRuntimeConfig.agentId || "";
1448
+ } else {
1449
+ selectedServerPort = upgradeRuntimeConfig.port || DEFAULT_SERVER_PORT;
1450
+ }
1451
+ info(tr(`Upgrade runtime mode: ${selectedMode}`, `升级运行模式: ${selectedMode}`));
1452
+
1453
+ info(tr(`Upgrade path: ${fromVersion} -> ${toVersion}`, `升级路径: ${fromVersion} -> ${toVersion}`));
1454
+
1455
+ await stopOpenClawGatewayForUpgrade();
1456
+ const configBackupPath = await backupOpenClawConfig(installedState.configPath);
1457
+ info(tr(`Backed up openclaw.json: ${configBackupPath}`, `已备份 openclaw.json: ${configBackupPath}`));
1458
+ const pluginBackups = [];
1459
+ for (const detection of installedState.detections) {
1460
+ const backupDir = await backupPluginDirectory(detection.variant);
1461
+ if (backupDir) {
1462
+ pluginBackups.push({ pluginId: detection.variant.id, backupDir });
1463
+ }
1464
+ }
1465
+ upgradeAudit = {
1466
+ operation: "upgrade",
1467
+ createdAt: new Date().toISOString(),
1468
+ fromVersion,
1469
+ toVersion,
1470
+ configBackupPath,
1471
+ pluginBackups,
1472
+ runtimeMode: selectedMode,
1473
+ };
1474
+ await writeUpgradeAuditFile(upgradeAudit);
1475
+ await cleanupInstalledPluginConfig(installedState);
1476
+
1477
+ info(
1478
+ tr(
1479
+ "Upgrade will keep the existing OpenViking runtime file and re-apply only the minimum plugin runtime settings.",
1480
+ "升级将保留现有 OpenViking 运行时文件,并只回填最小插件运行配置。",
1481
+ ),
1482
+ );
1483
+ info(tr(`Upgrade audit file: ${getUpgradeAuditPath()}`, `升级审计文件: ${getUpgradeAuditPath()}`));
1484
+ }
1485
+
1486
+ async function downloadPluginFile(destDir, fileName, url, required, index, total) {
589
1487
  const maxRetries = 3;
1488
+ const destPath = join(destDir, fileName);
590
1489
 
591
1490
  process.stdout.write(` [${index}/${total}] ${fileName} `);
592
1491
 
1492
+ let lastStatus = 0;
1493
+ let saw404 = false;
1494
+
593
1495
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
594
1496
  try {
595
1497
  const response = await fetch(url);
1498
+ lastStatus = response.status;
596
1499
  if (response.ok) {
597
1500
  const buffer = Buffer.from(await response.arrayBuffer());
598
- await writeFile(join(PLUGIN_DEST, fileName), buffer);
599
- console.log("✓");
600
- return;
1501
+ if (buffer.length === 0) {
1502
+ lastStatus = 0;
1503
+ } else {
1504
+ await mkdir(dirname(destPath), { recursive: true });
1505
+ await writeFile(destPath, buffer);
1506
+ console.log(" OK");
1507
+ return;
1508
+ }
1509
+ } else if (!required && response.status === 404) {
1510
+ saw404 = true;
1511
+ break;
601
1512
  }
602
- if (!required && response.status === 404) {
603
- console.log(tr("(not present in target branch, skipped)", "(目标分支不存在,已跳过)"));
604
- return;
605
- }
606
- } catch {}
1513
+ } catch {
1514
+ lastStatus = 0;
1515
+ }
607
1516
 
608
1517
  if (attempt < maxRetries) {
609
1518
  await new Promise((resolve) => setTimeout(resolve, 2000));
610
1519
  }
611
1520
  }
612
1521
 
613
- if (fileName === ".gitignore") {
614
- console.log(tr("(retries failed, using minimal .gitignore)", "(重试失败,使用最小 .gitignore"));
615
- await writeFile(join(PLUGIN_DEST, fileName), "node_modules/\n", "utf8");
1522
+ if (saw404 || lastStatus === 404) {
1523
+ if (fileName === ".gitignore") {
1524
+ await mkdir(dirname(destPath), { recursive: true });
1525
+ await writeFile(destPath, "node_modules/\n", "utf8");
1526
+ console.log(" OK");
1527
+ return;
1528
+ }
1529
+ console.log(tr(" skip", " 跳过"));
616
1530
  return;
617
1531
  }
618
1532
 
1533
+ if (!required) {
1534
+ console.log("");
1535
+ err(
1536
+ tr(
1537
+ `Optional file failed after ${maxRetries} retries (HTTP ${lastStatus || "network"}): ${url}`,
1538
+ `可选文件已重试 ${maxRetries} 次仍失败(HTTP ${lastStatus || "网络错误"}): ${url}`,
1539
+ ),
1540
+ );
1541
+ process.exit(1);
1542
+ }
1543
+
619
1544
  console.log("");
620
- err(tr(`Download failed: ${url}`, `下载失败: ${url}`));
1545
+ err(tr(`Download failed after ${maxRetries} retries: ${url}`, `下载失败(已重试 ${maxRetries} 次): ${url}`));
621
1546
  process.exit(1);
622
1547
  }
623
1548
 
624
- async function downloadPlugin() {
625
- await mkdir(PLUGIN_DEST, { recursive: true });
626
- const files = [
627
- ...REQUIRED_PLUGIN_FILES.map((relPath) => ({ relPath, required: true })),
628
- ...OPTIONAL_PLUGIN_FILES.map((relPath) => ({ relPath, required: false })),
629
- ];
1549
+ async function downloadPlugin(destDir) {
1550
+ const ghRaw = `https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}`;
1551
+ const pluginDir = resolvedPluginDir;
1552
+ const total = resolvedFilesRequired.length + resolvedFilesOptional.length;
1553
+
1554
+ await mkdir(destDir, { recursive: true });
1555
+
1556
+ info(tr(`Downloading plugin from ${REPO}@${PLUGIN_VERSION} (${total} files)...`, `正在从 ${REPO}@${PLUGIN_VERSION} 下载插件(共 ${total} 个文件)...`));
630
1557
 
631
- info(tr(`Downloading openviking plugin from ${REPO}@${BRANCH}...`, `正在从 ${REPO}@${BRANCH} 下载 openviking 插件...`));
632
- for (let i = 0; i < files.length; i++) {
633
- const file = files[i];
634
- await downloadPluginFile(file.relPath, file.required, i + 1, files.length);
1558
+ let i = 0;
1559
+ // Download required files
1560
+ for (const name of resolvedFilesRequired) {
1561
+ if (!name) continue;
1562
+ i++;
1563
+ const url = `${ghRaw}/examples/${pluginDir}/${name}`;
1564
+ await downloadPluginFile(destDir, name, url, true, i, total);
635
1565
  }
636
1566
 
1567
+ // Download optional files
1568
+ for (const name of resolvedFilesOptional) {
1569
+ if (!name) continue;
1570
+ i++;
1571
+ const url = `${ghRaw}/examples/${pluginDir}/${name}`;
1572
+ await downloadPluginFile(destDir, name, url, false, i, total);
1573
+ }
1574
+
1575
+ // npm install
637
1576
  info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
638
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: PLUGIN_DEST, silent: false });
1577
+ const npmArgs = resolvedNpmOmitDev
1578
+ ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
1579
+ : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
1580
+ await run("npm", npmArgs, { cwd: destDir, silent: false });
639
1581
  info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
640
1582
  }
641
1583
 
642
- async function configureOpenClawPlugin(pluginPath = PLUGIN_DEST) {
643
- info(tr("Configuring OpenClaw plugin...", "正在配置 OpenClaw 插件..."));
1584
+ async function deployLocalPlugin(localPluginDir, destDir) {
1585
+ await rm(destDir, { recursive: true, force: true });
1586
+ await mkdir(destDir, { recursive: true });
1587
+ await cp(localPluginDir, destDir, {
1588
+ recursive: true,
1589
+ force: true,
1590
+ filter: (sourcePath) => {
1591
+ const rel = relative(localPluginDir, sourcePath);
1592
+ if (!rel) return true;
1593
+ const firstSegment = rel.split(/[\\/]/)[0];
1594
+ return firstSegment !== "node_modules" && firstSegment !== ".git";
1595
+ },
1596
+ });
1597
+ }
644
1598
 
645
- const ocEnv = { ...process.env };
646
- if (OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
647
- ocEnv.OPENCLAW_STATE_DIR = OPENCLAW_DIR;
1599
+ async function installPluginDependencies(destDir) {
1600
+ info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
1601
+ const npmArgs = resolvedNpmOmitDev
1602
+ ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
1603
+ : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
1604
+ await run("npm", npmArgs, { cwd: destDir, silent: false });
1605
+ return info(tr(`Plugin prepared: ${destDir}`, `插件已准备: ${destDir}`));
1606
+ }
1607
+
1608
+ async function createPluginStagingDir() {
1609
+ const pluginId = resolvedPluginId || "openviking";
1610
+ const extensionsDir = join(OPENCLAW_DIR, "extensions");
1611
+ const stagingDir = join(extensionsDir, `.${pluginId}.staging-${process.pid}-${Date.now()}`);
1612
+ await mkdir(extensionsDir, { recursive: true });
1613
+ await rm(stagingDir, { recursive: true, force: true });
1614
+ await mkdir(stagingDir, { recursive: true });
1615
+ return stagingDir;
1616
+ }
1617
+
1618
+ async function finalizePluginDeployment(stagingDir) {
1619
+ await rm(PLUGIN_DEST, { recursive: true, force: true });
1620
+ try {
1621
+ await rename(stagingDir, PLUGIN_DEST);
1622
+ } catch {
1623
+ await cp(stagingDir, PLUGIN_DEST, { recursive: true, force: true });
1624
+ await rm(stagingDir, { recursive: true, force: true });
1625
+ }
1626
+ return info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
1627
+ }
1628
+
1629
+ async function deployPluginFromRemote() {
1630
+ const stagingDir = await createPluginStagingDir();
1631
+ try {
1632
+ await downloadPlugin(stagingDir);
1633
+ await finalizePluginDeployment(stagingDir);
1634
+ } catch (error) {
1635
+ await rm(stagingDir, { recursive: true, force: true });
1636
+ throw error;
1637
+ }
1638
+ }
1639
+
1640
+ /** Same as INSTALL*.md manual cleanup: stale entries block `plugins.slots.*` validation after reinstall. */
1641
+ function resolvedPluginSlotFallback() {
1642
+ if (resolvedPluginId === "memory-openviking") return "none";
1643
+ if (resolvedPluginId === "openviking") return "legacy";
1644
+ return "none";
1645
+ }
1646
+
1647
+ async function scrubStaleOpenClawPluginRegistration() {
1648
+ const configPath = getOpenClawConfigPath();
1649
+ if (!existsSync(configPath)) return;
1650
+ const pluginId = resolvedPluginId;
1651
+ const slot = resolvedPluginSlot;
1652
+ const slotFallback = resolvedPluginSlotFallback();
1653
+ let raw;
1654
+ try {
1655
+ raw = await readFile(configPath, "utf8");
1656
+ } catch {
1657
+ return;
1658
+ }
1659
+ let cfg;
1660
+ try {
1661
+ cfg = JSON.parse(raw);
1662
+ } catch {
1663
+ return;
1664
+ }
1665
+ if (!cfg.plugins) return;
1666
+ const p = cfg.plugins;
1667
+ let changed = false;
1668
+ if (p.entries && Object.prototype.hasOwnProperty.call(p.entries, pluginId)) {
1669
+ delete p.entries[pluginId];
1670
+ changed = true;
1671
+ }
1672
+ if (Array.isArray(p.allow)) {
1673
+ const next = p.allow.filter((id) => id !== pluginId);
1674
+ if (next.length !== p.allow.length) {
1675
+ p.allow = next;
1676
+ changed = true;
1677
+ }
1678
+ }
1679
+ if (p.load && Array.isArray(p.load.paths)) {
1680
+ const norm = (s) => String(s).replace(/\\/g, "/");
1681
+ const extNeedle = `/extensions/${pluginId}`;
1682
+ const next = p.load.paths.filter((path) => {
1683
+ if (typeof path !== "string") return true;
1684
+ return !norm(path).includes(extNeedle);
1685
+ });
1686
+ if (next.length !== p.load.paths.length) {
1687
+ p.load.paths = next;
1688
+ changed = true;
1689
+ }
648
1690
  }
1691
+ if (p.slots && p.slots[slot] === pluginId) {
1692
+ p.slots[slot] = slotFallback;
1693
+ changed = true;
1694
+ }
1695
+ if (!changed) return;
1696
+ const out = JSON.stringify(cfg, null, 2) + "\n";
1697
+ const tmp = `${configPath}.ov-install-tmp.${process.pid}`;
1698
+ await writeFile(tmp, out, "utf8");
1699
+ await rename(tmp, configPath);
1700
+ }
1701
+
1702
+ async function deployPluginFromLocal(localPluginDir) {
1703
+ const stagingDir = await createPluginStagingDir();
1704
+ try {
1705
+ await deployLocalPlugin(localPluginDir, stagingDir);
1706
+ await installPluginDependencies(stagingDir);
1707
+ await finalizePluginDeployment(stagingDir);
1708
+ } catch (error) {
1709
+ await rm(stagingDir, { recursive: true, force: true });
1710
+ throw error;
1711
+ }
1712
+ }
1713
+
1714
+ async function configureOpenClawPlugin({
1715
+ preserveExistingConfig = false,
1716
+ runtimeConfig = null,
1717
+ skipGatewayMode = false,
1718
+ claimSlot = true,
1719
+ } = {}) {
1720
+ info(tr("Configuring OpenClaw plugin...", "正在配置 OpenClaw 插件..."));
1721
+
1722
+ const pluginId = resolvedPluginId;
1723
+ const pluginSlot = resolvedPluginSlot;
1724
+
1725
+ const ocEnv = getOpenClawEnv();
1726
+
1727
+ const oc = async (args) => {
1728
+ const result = await runCapture("openclaw", args, { env: ocEnv, shell: IS_WIN });
1729
+ if (result.code !== 0) {
1730
+ const detail = result.err || result.out;
1731
+ throw new Error(`openclaw ${args.join(" ")} failed (exit code ${result.code})${detail ? `: ${detail}` : ""}`);
1732
+ }
1733
+ return result;
1734
+ };
649
1735
 
650
- const oc = (args) => runCapture("openclaw", args, { env: ocEnv, shell: IS_WIN });
1736
+ if (!preserveExistingConfig) {
1737
+ await scrubStaleOpenClawPluginRegistration();
1738
+ }
651
1739
 
652
1740
  // Enable plugin (files already deployed to extensions dir by deployPlugin)
653
- const enableResult = await oc(["plugins", "enable", "openviking"]);
654
- if (enableResult.code !== 0) throw new Error(`openclaw plugins enable failed (exit code ${enableResult.code})`);
655
- await oc(["config", "set", "plugins.slots.contextEngine", "openviking"]);
1741
+ await oc(["plugins", "enable", pluginId]);
1742
+ if (claimSlot) {
1743
+ await oc(["config", "set", `plugins.slots.${pluginSlot}`, pluginId]);
1744
+ } else {
1745
+ warn(
1746
+ tr(
1747
+ `Skipped claiming plugins.slots.${pluginSlot}; it is currently owned by another plugin.`,
1748
+ `已跳过设置 plugins.slots.${pluginSlot},当前该 slot 由其他插件占用。`,
1749
+ ),
1750
+ );
1751
+ }
656
1752
 
657
- // Set gateway mode
658
- await oc(["config", "set", "gateway.mode", "local"]);
1753
+ if (preserveExistingConfig) {
1754
+ info(
1755
+ tr(
1756
+ `Preserved existing plugin runtime config for ${pluginId}`,
1757
+ `已保留 ${pluginId} 的现有插件运行时配置`,
1758
+ ),
1759
+ );
1760
+ return;
1761
+ }
1762
+
1763
+ const effectiveRuntimeConfig = runtimeConfig || (
1764
+ selectedMode === "remote"
1765
+ ? { mode: "remote", baseUrl: remoteBaseUrl, apiKey: remoteApiKey, agentId: remoteAgentId }
1766
+ : { mode: "local", configPath: join(OPENVIKING_DIR, "ov.conf"), port: selectedServerPort }
1767
+ );
1768
+
1769
+ if (!skipGatewayMode) {
1770
+ await oc(["config", "set", "gateway.mode", effectiveRuntimeConfig.mode === "remote" ? "remote" : "local"]);
1771
+ }
659
1772
 
660
1773
  // Set plugin config for the selected mode
661
- if (selectedMode === "local") {
662
- const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
663
- await oc(["config", "set", "plugins.entries.openviking.config.mode", "local"]);
664
- await oc(["config", "set", "plugins.entries.openviking.config.configPath", ovConfPath]);
665
- await oc(["config", "set", "plugins.entries.openviking.config.port", String(selectedServerPort)]);
1774
+ if (effectiveRuntimeConfig.mode === "local") {
1775
+ const ovConfPath = effectiveRuntimeConfig.configPath || join(OPENVIKING_DIR, "ov.conf");
1776
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.mode`, "local"]);
1777
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.configPath`, ovConfPath]);
1778
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.port`, String(effectiveRuntimeConfig.port || DEFAULT_SERVER_PORT)]);
666
1779
  } else {
667
- await oc(["config", "set", "plugins.entries.openviking.config.mode", "remote"]);
668
- await oc(["config", "set", "plugins.entries.openviking.config.baseUrl", remoteBaseUrl]);
669
- if (remoteApiKey) {
670
- await oc(["config", "set", "plugins.entries.openviking.config.apiKey", remoteApiKey]);
1780
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.mode`, "remote"]);
1781
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.baseUrl`, effectiveRuntimeConfig.baseUrl || remoteBaseUrl]);
1782
+ if (effectiveRuntimeConfig.apiKey) {
1783
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.apiKey`, effectiveRuntimeConfig.apiKey]);
671
1784
  }
672
- if (remoteAgentId) {
673
- await oc(["config", "set", "plugins.entries.openviking.config.agentId", remoteAgentId]);
1785
+ if (effectiveRuntimeConfig.agentId) {
1786
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.agentId`, effectiveRuntimeConfig.agentId]);
674
1787
  }
675
1788
  }
676
1789
 
1790
+ // Legacy (memory) plugins need explicit targetUri/autoRecall/autoCapture (new version has defaults in config.ts)
1791
+ if (resolvedPluginKind === "memory") {
1792
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.targetUri`, "viking://user/memories"]);
1793
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.autoRecall`, "true", "--json"]);
1794
+ await oc(["config", "set", `plugins.entries.${pluginId}.config.autoCapture`, "true", "--json"]);
1795
+ }
1796
+
677
1797
  info(tr("OpenClaw plugin configured", "OpenClaw 插件配置完成"));
678
1798
  }
679
1799
 
1800
+ async function discoverOpenvikingPython(failedPy) {
1801
+ const candidates = IS_WIN
1802
+ ? ["python3", "python", "py -3"]
1803
+ : ["python3.13", "python3.12", "python3.11", "python3.10", "python3", "python"];
1804
+ for (const candidate of candidates) {
1805
+ if (candidate === failedPy) continue;
1806
+ const resolved = await resolveAbsoluteCommand(candidate);
1807
+ if (!resolved || resolved === candidate || resolved === failedPy) continue;
1808
+ const check = await runCapture(resolved, ["-c", "import openviking"], { shell: false });
1809
+ if (check.code === 0) return resolved;
1810
+ }
1811
+ return "";
1812
+ }
1813
+
680
1814
  async function resolvePythonPath() {
681
1815
  if (openvikingPythonPath) return openvikingPythonPath;
682
1816
  const python = await checkPython();
683
- const py = python.cmd;
684
- if (!py) return "";
685
-
686
- if (IS_WIN) {
687
- const result = await runCapture("where", [py], { shell: true });
688
- return result.out.split(/\r?\n/)[0]?.trim() || py;
689
- }
690
-
691
- const result = await runCapture("which", [py], { shell: false });
692
- return result.out.trim() || py;
1817
+ return python.cmd || "";
693
1818
  }
694
1819
 
695
1820
  async function writeOpenvikingEnv({ includePython }) {
696
1821
  const needStateDir = OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR;
697
- const pythonPath = includePython ? await resolvePythonPath() : "";
1822
+ let pythonPath = "";
1823
+ if (includePython) {
1824
+ pythonPath = await resolvePythonPath();
1825
+ if (!pythonPath) {
1826
+ pythonPath = (process.env.OPENVIKING_PYTHON || "").trim() || (IS_WIN ? "python" : "python3");
1827
+ warn(
1828
+ tr(
1829
+ "Could not resolve absolute Python path; wrote fallback OPENVIKING_PYTHON to openviking.env. Edit that file if OpenViking fails to start.",
1830
+ "未能解析 Python 绝对路径,已在 openviking.env 中写入后备值。若启动失败请手动修改为虚拟环境中的 python 可执行文件路径。",
1831
+ ),
1832
+ );
1833
+ }
1834
+
1835
+ // Verify the resolved Python can actually import openviking
1836
+ if (pythonPath) {
1837
+ const verify = await runCapture(pythonPath, ["-c", "import openviking"], { shell: false });
1838
+ if (verify.code !== 0) {
1839
+ warn(
1840
+ tr(
1841
+ `Resolved Python (${pythonPath}) cannot import openviking. The pip install target may differ from the runtime python3.`,
1842
+ `解析到的 Python(${pythonPath})无法 import openviking。pip 安装目标可能与运行时的 python3 不一致。`,
1843
+ ),
1844
+ );
1845
+ // Try to discover the correct Python via pip show
1846
+ const corrected = await discoverOpenvikingPython(pythonPath);
1847
+ if (corrected) {
1848
+ info(
1849
+ tr(
1850
+ `Auto-corrected OPENVIKING_PYTHON to ${corrected}`,
1851
+ `已自动修正 OPENVIKING_PYTHON 为 ${corrected}`,
1852
+ ),
1853
+ );
1854
+ pythonPath = corrected;
1855
+ } else {
1856
+ warn(
1857
+ tr(
1858
+ `Could not auto-detect the correct Python. Edit OPENVIKING_PYTHON in the env file manually.`,
1859
+ `无法自动检测正确的 Python。请手动修改 env 文件中的 OPENVIKING_PYTHON。`,
1860
+ ),
1861
+ );
1862
+ }
1863
+ }
1864
+ }
1865
+ }
1866
+
1867
+ // Remote mode + default state dir + no python line → nothing to persist
698
1868
  if (!needStateDir && !pythonPath) return null;
699
1869
 
700
1870
  await mkdir(OPENCLAW_DIR, { recursive: true });
@@ -741,45 +1911,128 @@ function wrapCommand(command, envFiles) {
741
1911
  return `source '${envFiles.shellPath.replace(/'/g, "'\"'\"'")}' && ${command}`;
742
1912
  }
743
1913
 
1914
+ function getExistingEnvFiles() {
1915
+ if (IS_WIN) {
1916
+ const batPath = join(OPENCLAW_DIR, "openviking.env.bat");
1917
+ const ps1Path = join(OPENCLAW_DIR, "openviking.env.ps1");
1918
+ if (existsSync(batPath)) {
1919
+ return { shellPath: batPath, powershellPath: existsSync(ps1Path) ? ps1Path : undefined };
1920
+ }
1921
+ if (existsSync(ps1Path)) {
1922
+ return { shellPath: ps1Path, powershellPath: ps1Path };
1923
+ }
1924
+ return null;
1925
+ }
1926
+
1927
+ const envPath = join(OPENCLAW_DIR, "openviking.env");
1928
+ return existsSync(envPath) ? { shellPath: envPath } : null;
1929
+ }
1930
+
1931
+ function ensureExistingPluginForUpgrade() {
1932
+ if (!existsSync(PLUGIN_DEST)) {
1933
+ err(
1934
+ tr(
1935
+ `Plugin upgrade mode expects an existing plugin at ${PLUGIN_DEST}. Run the full installer first if this is a fresh install.`,
1936
+ `插件升级模式要求 ${PLUGIN_DEST} 处已存在插件安装。若是首次安装,请先运行完整安装流程。`,
1937
+ ),
1938
+ );
1939
+ process.exit(1);
1940
+ }
1941
+ }
1942
+
744
1943
  async function main() {
745
1944
  console.log("");
746
1945
  bold(tr("🦣 OpenClaw + OpenViking Installer", "🦣 OpenClaw + OpenViking 一键安装"));
747
1946
  console.log("");
748
1947
 
1948
+ ensurePluginOnlyOperationArgs();
749
1949
  await selectWorkdir();
1950
+ if (rollbackLastUpgrade) {
1951
+ info(tr("Mode: rollback last plugin upgrade", "模式: 回滚最近一次插件升级"));
1952
+ if (PLUGIN_VERSION !== "main") {
1953
+ warn("--plugin-version is ignored in --rollback mode.");
1954
+ }
1955
+ await rollbackLastUpgradeOperation();
1956
+ return;
1957
+ }
1958
+ validateRequestedPluginVersion();
750
1959
  info(tr(`Target: ${OPENCLAW_DIR}`, `目标实例: ${OPENCLAW_DIR}`));
1960
+ info(tr(`Repository: ${REPO}`, `仓库: ${REPO}`));
1961
+ info(tr(`Plugin version: ${PLUGIN_VERSION}`, `插件版本: ${PLUGIN_VERSION}`));
1962
+ if (openvikingVersion) {
1963
+ info(tr(`OpenViking version: ${openvikingVersion}`, `OpenViking 版本: ${openvikingVersion}`));
1964
+ }
751
1965
 
752
- await selectMode();
1966
+ if (upgradePluginOnly) {
1967
+ selectedMode = "local";
1968
+ info("Mode: plugin upgrade only (backup old plugin, clean only OpenViking plugin config, keep ov.conf)");
1969
+ } else {
1970
+ await selectMode();
1971
+ }
753
1972
  info(tr(`Mode: ${selectedMode}`, `模式: ${selectedMode}`));
754
1973
 
755
- if (selectedMode === "local") {
1974
+ if (upgradePluginOnly) {
1975
+ await checkOpenClaw();
1976
+ await resolvePluginConfig();
1977
+ await checkOpenClawCompatibility();
1978
+ await prepareStrongPluginUpgrade();
1979
+ } else if (selectedMode === "local") {
756
1980
  await validateEnvironment();
757
1981
  await checkOpenClaw();
1982
+ // Resolve plugin config after OpenClaw is available (for version detection)
1983
+ await resolvePluginConfig();
1984
+ await checkOpenClawCompatibility();
1985
+ checkRequestedOpenVikingCompatibility();
758
1986
  await installOpenViking();
759
1987
  await configureOvConf();
760
1988
  } else {
761
1989
  await checkOpenClaw();
1990
+ await resolvePluginConfig();
1991
+ await checkOpenClawCompatibility();
762
1992
  await collectRemoteConfig();
763
1993
  }
764
1994
 
765
1995
  let pluginPath;
766
- const localPluginDir = openvikingRepo ? join(openvikingRepo, "examples", "openclaw-plugin") : "";
1996
+ const localPluginDir = openvikingRepo ? join(openvikingRepo, "examples", resolvedPluginDir || "openclaw-plugin") : "";
767
1997
  if (openvikingRepo && existsSync(join(localPluginDir, "index.ts"))) {
768
1998
  pluginPath = localPluginDir;
1999
+ PLUGIN_DEST = join(OPENCLAW_DIR, "extensions", resolvedPluginId || "openviking");
769
2000
  info(tr(`Using local plugin from repo: ${pluginPath}`, `使用仓库内插件: ${pluginPath}`));
770
- if (!existsSync(join(pluginPath, "node_modules"))) {
2001
+ await deployPluginFromLocal(pluginPath);
771
2002
  info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
772
- await run("npm", ["install", "--no-audit", "--no-fund"], { cwd: pluginPath, silent: false });
773
- }
2003
+ pluginPath = PLUGIN_DEST;
774
2004
  } else {
775
- await downloadPlugin();
2005
+ await deployPluginFromRemote();
776
2006
  pluginPath = PLUGIN_DEST;
777
2007
  }
778
2008
 
779
- await configureOpenClawPlugin(pluginPath);
780
- const envFiles = await writeOpenvikingEnv({
781
- includePython: selectedMode === "local",
2009
+ await configureOpenClawPlugin(
2010
+ upgradePluginOnly
2011
+ ? {
2012
+ runtimeConfig: upgradeRuntimeConfig,
2013
+ skipGatewayMode: true,
2014
+ claimSlot: installedUpgradeState ? shouldClaimTargetSlot(installedUpgradeState) : true,
2015
+ }
2016
+ : { preserveExistingConfig: false },
2017
+ );
2018
+ await writeInstallStateFile({
2019
+ operation: upgradePluginOnly ? "upgrade" : "install",
2020
+ fromVersion: upgradeAudit?.fromVersion || "",
2021
+ configBackupPath: upgradeAudit?.configBackupPath || "",
2022
+ pluginBackups: upgradeAudit?.pluginBackups || [],
782
2023
  });
2024
+ if (upgradeAudit) {
2025
+ upgradeAudit.completedAt = new Date().toISOString();
2026
+ await writeUpgradeAuditFile(upgradeAudit);
2027
+ }
2028
+ let envFiles = getExistingEnvFiles();
2029
+ if (!upgradePluginOnly) {
2030
+ envFiles = await writeOpenvikingEnv({
2031
+ includePython: selectedMode === "local",
2032
+ });
2033
+ } else if (!envFiles && OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR) {
2034
+ envFiles = await writeOpenvikingEnv({ includePython: false });
2035
+ }
783
2036
 
784
2037
  console.log("");
785
2038
  bold("═══════════════════════════════════════════════════════════");
@@ -787,6 +2040,16 @@ async function main() {
787
2040
  bold("═══════════════════════════════════════════════════════════");
788
2041
  console.log("");
789
2042
 
2043
+ if (upgradeAudit) {
2044
+ info(tr(`Upgrade path recorded: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`, `已记录升级路径: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`));
2045
+ info(tr(`Rollback config backup: ${upgradeAudit.configBackupPath}`, `回滚配置备份: ${upgradeAudit.configBackupPath}`));
2046
+ for (const pluginBackup of upgradeAudit.pluginBackups || []) {
2047
+ info(tr(`Rollback plugin backup: ${pluginBackup.backupDir}`, `回滚插件备份: ${pluginBackup.backupDir}`));
2048
+ }
2049
+ info(tr(`Rollback audit file: ${getUpgradeAuditPath()}`, `回滚审计文件: ${getUpgradeAuditPath()}`));
2050
+ console.log("");
2051
+ }
2052
+
790
2053
  if (selectedMode === "local") {
791
2054
  info(tr("Run these commands to start OpenClaw + OpenViking:", "请按以下命令启动 OpenClaw + OpenViking:"));
792
2055
  } else {
@@ -799,6 +2062,14 @@ async function main() {
799
2062
  console.log("");
800
2063
 
801
2064
  if (selectedMode === "local") {
2065
+ if (envFiles?.shellPath && !IS_WIN) {
2066
+ info(
2067
+ tr(
2068
+ 'If source fails, set: export OPENVIKING_PYTHON="$(command -v python3)"',
2069
+ '若 source 失败,可执行: export OPENVIKING_PYTHON="$(command -v python3)"',
2070
+ ),
2071
+ );
2072
+ }
802
2073
  info(tr(`You can edit the config freely: ${OPENVIKING_DIR}/ov.conf`, `你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf`));
803
2074
  } else {
804
2075
  info(tr(`Remote server: ${remoteBaseUrl}`, `远程服务器: ${remoteBaseUrl}`));