Skip to content

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

feat(openclaw-plugin): support OpenClaw install and ClawHub release flow (#1904)

LinQiang39172a3cd29f0bc
diff --git a/.github/workflows/clawhub-dev-release.yml b/.github/workflows/clawhub-dev-release.yml
new file mode 100644
index 000000000..5bad02b74
--- /dev/null
+++ b/.github/workflows/clawhub-dev-release.yml
@@ -0,0 +1,281 @@
+name: ClawHub release (OpenViking plugin)
+
+# Publishes examples/openclaw-plugin to ClawHub. The publish branch
+# intentionally does not commit dist/; this workflow builds and npm-packs the
+# plugin into a generated package branch, then lets ClawHub's official reusable
+# workflow perform trusted publishing from that package source while preserving
+# the original workflow commit as source metadata.
+
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: "Optional plugin version. Leave empty to auto-generate YYYY.M.D / YYYY.M.D-N / YYYY.M.D-dev.N."
+ required: false
+ channel:
+ description: "Publish channel. auto publishes latest from the configured upstream repository and dev from forks."
+ required: false
+ type: choice
+ default: "auto"
+ options:
+ - auto
+ - dev
+ - latest
+ changelog:
+ description: "Changelog text for this release."
+ required: false
+ default: "OpenViking plugin release via OIDC trusted publishing."
+
+permissions:
+ contents: read
+
+jobs:
+ guard:
+ name: Resolve release channel
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ outputs:
+ tags: ${{ steps.resolve.outputs.tags }}
+ version: ${{ steps.resolve.outputs.version }}
+ steps:
+ - name: Resolve release channel and version
+ id: resolve
+ shell: bash
+ run: |
+ repo="${{ github.repository }}"
+ requested="${{ github.event.inputs.channel || 'auto' }}"
+ requested_version="${{ github.event.inputs.version || '' }}"
+ configured_upstream="${{ vars.CLAWHUB_UPSTREAM_REPOSITORY }}"
+ configured_latest_repos="${{ vars.CLAWHUB_LATEST_REPOSITORIES }}"
+ configured_dev_repos="${{ vars.CLAWHUB_DEV_REPOSITORIES }}"
+ configured_timezone="${{ vars.CLAWHUB_RELEASE_TIMEZONE }}"
+ upstream_repo="${configured_upstream:-volcengine/OpenViking}"
+ release_timezone="${configured_timezone:-Asia/Shanghai}"
+
+ repo_in_list() {
+ local needle="$1"
+ local list="${2//,/ }"
+ for item in $list; do
+ if [ "$item" = "$needle" ]; then
+ return 0
+ fi
+ done
+ return 1
+ }
+
+ can_publish_latest=false
+ if [ "$repo" = "$upstream_repo" ] || repo_in_list "$repo" "$configured_latest_repos"; then
+ can_publish_latest=true
+ fi
+
+ can_publish_dev=true
+ if [ "$repo" = "$upstream_repo" ]; then
+ can_publish_dev=true
+ elif [ -n "$configured_dev_repos" ] && ! repo_in_list "$repo" "$configured_dev_repos"; then
+ can_publish_dev=false
+ fi
+
+ if [ "$requested" = "auto" ]; then
+ if [ "$can_publish_latest" = "true" ]; then
+ channel="latest"
+ elif [ "$can_publish_dev" = "true" ]; then
+ channel="dev"
+ else
+ echo "::error title=Repository not allowed::Repository '$repo' is not allowed to publish to ClawHub. Set CLAWHUB_DEV_REPOSITORIES or CLAWHUB_LATEST_REPOSITORIES repository variables if this is intentional."
+ exit 1
+ fi
+ else
+ channel="$requested"
+ fi
+
+ if [ "$channel" != "dev" ] && [ "$channel" != "latest" ]; then
+ echo "::error title=Invalid channel::Unsupported ClawHub channel '$channel'."
+ exit 1
+ fi
+
+ if [ "$channel" = "latest" ] && [ "$can_publish_latest" != "true" ]; then
+ echo "::error title=Refusing to publish::Repository '$repo' may not publish the latest channel. Only '$upstream_repo' and repositories listed in CLAWHUB_LATEST_REPOSITORIES may publish latest."
+ exit 1
+ fi
+
+ if [ "$channel" = "dev" ] && [ "$can_publish_dev" != "true" ]; then
+ echo "::error title=Refusing to publish::Repository '$repo' may not publish the dev channel. Configure CLAWHUB_DEV_REPOSITORIES if this repository should be allowed."
+ exit 1
+ fi
+
+ collect_published_versions() {
+ local target_repo="$1"
+ local remote="https://x-access-token:${{ github.token }}@github.com/${target_repo}.git"
+ local tmpdir
+ tmpdir="$(mktemp -d)"
+ git -C "$tmpdir" init -q
+ git -C "$tmpdir" remote add origin "$remote"
+ if git -C "$tmpdir" fetch --quiet --depth=1 origin '+refs/heads/clawhub-package-*:refs/remotes/origin/clawhub-package-*'; then
+ git -C "$tmpdir" for-each-ref --format='%(refname)' refs/remotes/origin/clawhub-package-* | while IFS= read -r ref; do
+ branch_version="$(
+ git -C "$tmpdir" show "$ref:package.json" 2>/dev/null \
+ | sed -n 's/^[[:space:]]*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
+ | head -n 1 || true
+ )"
+ if [ -n "$branch_version" ]; then
+ echo "$branch_version"
+ fi
+ done
+ fi
+ rm -rf "$tmpdir"
+ }
+
+ next_version_for_channel() {
+ local channel="$1"
+ local base_version
+ local existing_versions
+ base_version="$(TZ="$release_timezone" date +'%Y.%-m.%-d')"
+ existing_versions="$(collect_published_versions "$repo" | sort -u)"
+
+ if [ "$channel" = "dev" ]; then
+ local prefix="${base_version}-dev."
+ local max_dev=0
+ while IFS= read -r candidate; do
+ if [[ "$candidate" == "$prefix"* ]]; then
+ local suffix="${candidate#$prefix}"
+ if [[ "$suffix" =~ ^[0-9]+$ ]] && [ "$((10#$suffix))" -gt "$max_dev" ]; then
+ max_dev="$((10#$suffix))"
+ fi
+ fi
+ done <<< "$existing_versions"
+ echo "${base_version}-dev.$((max_dev + 1))"
+ return
+ fi
+
+ local max_latest=-1
+ while IFS= read -r candidate; do
+ if [ "$candidate" = "$base_version" ]; then
+ if [ "$max_latest" -lt 0 ]; then
+ max_latest=0
+ fi
+ elif [[ "$candidate" == "${base_version}-"* ]]; then
+ local suffix="${candidate#${base_version}-}"
+ if [[ "$suffix" =~ ^[0-9]+$ ]] && [ "$((10#$suffix))" -gt "$max_latest" ]; then
+ max_latest="$((10#$suffix))"
+ fi
+ fi
+ done <<< "$existing_versions"
+
+ if [ "$max_latest" -lt 0 ]; then
+ echo "$base_version"
+ else
+ echo "${base_version}-$((max_latest + 1))"
+ fi
+ }
+
+ if [ -n "$requested_version" ]; then
+ version="$requested_version"
+ else
+ version="$(next_version_for_channel "$channel")"
+ fi
+
+ if [ "$channel" = "dev" ] && [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-dev\.[0-9]+$ ]]; then
+ echo "::error title=Invalid dev version::The dev channel requires YYYY.M.D-dev.N, got '$version'."
+ exit 1
+ fi
+
+ if [ "$channel" = "latest" ] && [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9]+)?$ ]]; then
+ echo "::error title=Invalid latest version::The latest channel requires YYYY.M.D or YYYY.M.D-N, got '$version'."
+ exit 1
+ fi
+
+ echo "tags=$channel" >> "$GITHUB_OUTPUT"
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+
+ - name: Show inputs
+ run: |
+ echo "requested_version=${{ github.event.inputs.version || '' }}"
+ echo "resolved_version=${{ steps.resolve.outputs.version }}"
+ echo "channel=${{ github.event.inputs.channel || 'auto' }}"
+ echo "resolved_tags=${{ steps.resolve.outputs.tags }}"
+ echo "changelog=${{ github.event.inputs.changelog || 'OpenViking plugin release via OIDC trusted publishing.' }}"
+
+ prepare-package-source:
+ name: Prepare ClawHub package source
+ needs: guard
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: write
+ outputs:
+ package_branch: ${{ steps.package_branch.outputs.branch }}
+ source_url: ${{ steps.package_branch.outputs.source_url }}
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ ref: ${{ github.sha }}
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: examples/openclaw-plugin/package-lock.json
+
+ - name: Pack OpenViking plugin
+ id: pack
+ working-directory: examples/openclaw-plugin
+ env:
+ VERSION: ${{ needs.guard.outputs.version }}
+ run: |
+ set -euo pipefail
+ npm version --no-git-tag-version --allow-same-version "$VERSION"
+ npm ci
+ pack_dir="$RUNNER_TEMP/openviking-pack"
+ package_dir="$RUNNER_TEMP/openviking-package"
+ mkdir -p "$pack_dir" "$package_dir"
+ npm pack --pack-destination "$pack_dir"
+ tarball="$(find "$pack_dir" -maxdepth 1 -name '*.tgz' -print -quit)"
+ if [ -z "$tarball" ]; then
+ echo "::error title=Pack failed::npm pack did not produce a tgz file."
+ exit 1
+ fi
+ tar -xzf "$tarball" -C "$package_dir"
+ echo "package_dir=$package_dir/package" >> "$GITHUB_OUTPUT"
+ find "$package_dir/package" -maxdepth 3 -type f | sort
+
+ - name: Push generated package branch
+ id: package_branch
+ env:
+ PACKAGE_DIR: ${{ steps.pack.outputs.package_dir }}
+ VERSION: ${{ needs.guard.outputs.version }}
+ BRANCH: clawhub-package-${{ github.run_id }}
+ run: |
+ set -euo pipefail
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git switch --orphan "$BRANCH"
+ git rm -r --cached . || true
+ find . -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
+ cp -a "$PACKAGE_DIR"/. .
+ git add .
+ git commit -m "chore(clawhub): package openviking plugin $VERSION"
+ git push --force origin "HEAD:$BRANCH"
+ source_url="${GITHUB_REPOSITORY}@${BRANCH}"
+ echo "branch=$BRANCH" >> "$GITHUB_OUTPUT"
+ echo "source_url=$source_url" >> "$GITHUB_OUTPUT"
+ echo "source_url=$source_url"
+
+ publish:
+ name: Publish to ClawHub (official trusted workflow)
+ needs:
+ - guard
+ - prepare-package-source
+ permissions:
+ contents: read
+ id-token: write
+ uses: openclaw/clawhub/.github/workflows/[email protected]
+ with:
+ source: ${{ needs.prepare-package-source.outputs.source_url }}
+ dry_run: false
+ json: true
+ version: ${{ needs.guard.outputs.version }}
+ tags: ${{ needs.guard.outputs.tags }}
+ source_repo: ${{ github.repository }}
+ source_commit: ${{ github.sha }}
+ source_ref: ${{ github.ref }}
diff --git a/examples/openclaw-plugin/.clawhubignore b/examples/openclaw-plugin/.clawhubignore
index fda8472b4..5b5a3bbd0 100644
--- a/examples/openclaw-plugin/.clawhubignore
+++ b/examples/openclaw-plugin/.clawhubignore
@@ -4,8 +4,13 @@ __tests__/
images/
health_check_tools/
upgrade_scripts/
-skills/
INSTALL*.md
-README*.md
+README_CN.md
install.sh
vitest.config.ts
+# Excluded so ClawHub CLI's bundle marker pre-scan does not misclassify this
+# code-plugin as a bundle-plugin. The later npm pack step still includes
+# commands/setup.ts and skills/ through package.json "files".
+commands/
+skills/
+*.tgz
diff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.md
index be613c1c5..f3659ab96 100644
--- a/examples/openclaw-plugin/INSTALL-AGENT.md
+++ b/examples/openclaw-plugin/INSTALL-AGENT.md
@@ -1,41 +1,149 @@
# OpenViking Plugin Agent Install Guide
-This guide is for AI agents such as Claude Code, Cursor, or similar operator flows. Prefer automation. Ask the user only when detection fails or a choice materially changes the outcome.
+This guide is for AI agents and operator automation. Prefer deterministic commands, parse JSON output, and ask the user only when a choice changes the outcome.
-For user-facing installation details, see [INSTALL.md](./INSTALL.md) or [INSTALL-ZH.md](./INSTALL-ZH.md).
+User-facing docs:
-## Goal
+- [INSTALL.md](./INSTALL.md)
+- [INSTALL-ZH.md](./INSTALL-ZH.md)
-Choose the smallest action that matches the user's intent:
+## Identity
+
+This package is the OpenClaw plugin `@openclaw/openviking`.
| User intent | Command |
| --- | --- |
-| Fresh install, latest | `npm install -g openclaw-openviking-setup-helper@latest && ov-install` |
-| Upgrade plugin to latest | `npm install -g openclaw-openviking-setup-helper@latest && ov-install -y` |
-| Install or upgrade a specific release | `npm install -g openclaw-openviking-setup-helper@latest && ov-install -y --version 0.2.9` |
-| Upgrade only the plugin | `ov-install --update` |
-| Show installed versions | `ov-install --current-version` |
+| Fresh install, latest | `openclaw plugins install @openclaw/openviking` |
+| Upgrade plugin to latest | `openclaw plugins install @openclaw/openviking` |
+| Install or upgrade a specific release | Use the published ClawHub package selector if available; otherwise ask before using backup `ov-install --plugin-version=<REF>` |
+| Upgrade only the plugin | `openclaw plugins install @openclaw/openviking` |
+| Show installed plugins | `openclaw plugins list` |
+| Backup install when ClawHub is unavailable | `npx -y openclaw-openviking-setup-helper@latest --base-url <URL> [--api-key <KEY>]` |
| Operate on a specific OpenClaw instance | add `--workdir <path>` |
| Start missing OpenViking server | `openviking-server init && openviking-server doctor && openviking-server` |
-Default rule: when upgrading, refresh the setup helper first unless the user explicitly asks to pin the helper itself.
+Do not install it with:
+
+```bash
+clawhub install openviking
+```
+
+That installs an AgentSkill, not the plugin. The plugin install command is:
+
+```bash
+openclaw plugins install @openclaw/openviking
+```
+
+## Required Inputs
+
+Before setup, determine:
+
+| Input | Required | How to get it |
+| --- | --- | --- |
+| OpenViking base URL | Yes | Ask user or read `OPENVIKING_BASE_URL` |
+| API key | Usually | Ask user or read `OPENVIKING_API_KEY` |
+| Account ID | Only for root API keys | Ask user if setup reports root-key tenant context is needed |
+| User ID | Only for root API keys | Ask user if setup reports root-key tenant context is needed |
+| Slot replacement approval | Only if another context engine owns the slot | Ask user before using `--force-slot` |
+
+Never silently replace another context engine.
+
+## Primary Workflow
+
+Use this workflow for normal installs and upgrades from published packages.
+
+```bash
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+openclaw gateway restart
+openclaw openviking status --json
+```
+
+If the registry prefix is required:
+
+```bash
+openclaw plugins install clawhub:@openclaw/openviking
+```
+
+## Setup JSON Contract
+
+Run setup with `--json` whenever possible:
+
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+```
-## Detection Rules
+Branch on the result:
-### 1. Detect OpenClaw instance
+| JSON result | Meaning | Agent action |
+| --- | --- | --- |
+| `success: true` | Setup completed | Restart gateway, then run status |
+| `success: false`, `action: "slot_blocked"` | Another plugin owns `plugins.slots.contextEngine` | Ask user before rerunning with `--force-slot` |
+| `success: false`, `action: "error"` | Validation failed | Report `error`; do not continue as success |
+| `health.ok: false` | Server unreachable | Check URL/service; use `--allow-offline` only with user approval |
+| `keyProbe.keyType: "root_key"` | Root key requires tenant fields | Rerun with `--account-id <ACCOUNT_ID> --user-id <USER_ID>` |
+| `health.compatibility: "server_too_old"` | Server may not support plugin features | Warn user and recommend server upgrade |
+| `health.compatibility: "server_too_new"` | Plugin may be too old | Warn user and recommend plugin upgrade |
-If the user did not specify a workdir, check for multiple OpenClaw instances:
+Root-key retry:
```bash
-ls -d ~/.openclaw* 2>/dev/null
+openclaw openviking setup \
+ --base-url <OPENVIKING_URL> \
+ --api-key <ROOT_API_KEY> \
+ --account-id <ACCOUNT_ID> \
+ --user-id <USER_ID> \
+ --json
```
-- If only one instance exists, use it.
-- If multiple instances exist, ask which instance to operate on, or pass `--workdir`.
+Custom agent routing prefix (optional; only when the user explicitly requests a prefix):
+
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json
+```
+
+Slot replacement retry, only after user approval:
+
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json
+```
+
+Offline config save, only after user approval:
+
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --allow-offline --json
+```
-### 2. Detect environment
+## Status JSON Contract
-Verify:
+After restart, run:
+
+```bash
+openclaw openviking status --json
+```
+
+Ready state:
+
+```json
+{
+ "configured": true,
+ "slotActive": true
+}
+```
+
+Also inspect:
+
+| Field | Use |
+| --- | --- |
+| `health.ok` | Confirms server reachability |
+| `health.version` | Records server version |
+| `health.compatibility` | Determines whether to warn |
+| `config.hasApiKey` | Confirms whether an API key was saved |
+| `config.agent_prefix` | Confirms configured agent prefix when present |
+
+## Environment Detection
+
+Check tools:
```bash
node -v
@@ -45,7 +153,15 @@ openclaw --version
Requirements:
- Node.js >= 22
-- OpenClaw >= 2026.4.24
+- OpenClaw >= 2026.4.8
+
+Version boundaries:
+
+- `2026.4.8` is the minimum supported OpenClaw version for the current `@openclaw/openviking` plugin.
+- `2026.5.3` starts requiring compiled JavaScript runtime output during package install when a plugin package declares TypeScript entries.
+- `2026.5.4` and later no longer fall back to `.ts` source for installed/global plugin runtime loading when the compiled JavaScript output is missing; the plugin may be skipped.
+- Published ClawHub packages are built before release and include `dist/*.js`, so normal users do not need to build locally.
+- `ov-install` is the backup/source install path. Use it only after the OpenClaw plugin manager or ClawHub path is unavailable/rate-limited, or when the user explicitly asks to install a source ref. For OpenClaw `>= 2026.5.3`, it builds the plugin during installation.
### 3. Detect or start OpenViking server
@@ -70,159 +186,170 @@ Keep `openviking-server` running while OpenClaw uses the plugin. Use `http://127
For a remote server, confirm the reachable URL with the user and use that URL as `baseUrl`.
-If OpenClaw is missing, tell the user to run:
+If OpenClaw is missing, tell the user to install and initialize OpenClaw:
```bash
-npm install -g openclaw && openclaw onboard
+npm install -g openclaw
+openclaw onboard
```
### 4. Detect existing install state
-Use:
-
-```bash
-ov-install --current-version
-```
-
-This reports:
-
-- installed plugin release
-- requested plugin ref
-- installation time
-
-## Standard Workflows
+If the user has multiple OpenClaw state directories, ask which one to operate on before changing config.
-### Latest Install
+## Existing State Detection
-Use for fresh installs:
+Try status first:
```bash
-npm install -g openclaw-openviking-setup-helper@latest
-ov-install
+openclaw openviking status --json
```
-Notes:
-
-- `ov-install` is interactive on first install.
-- It stores remote connection settings in `plugins.entries.openviking.config`.
-
-### Latest Upgrade
+If the command is unavailable, install the plugin first. If it returns `configured: true` and `slotActive: true`, do not reinstall unless the user requested upgrade or reconfigure.
-Use when the user wants the plugin upgraded:
+Manual inspection:
```bash
-npm install -g openclaw-openviking-setup-helper@latest
-ov-install -y
+openclaw config get plugins.entries.openviking.config
+openclaw config get plugins.slots.contextEngine
+openclaw plugins list
```
-Current behavior:
-
-- plugin version defaults to the latest repo tag
-- `-y` runs the non-interactive path; verify the resulting plugin config after upgrade if the target instance has custom settings
+## Standard Operations
-### Release-Pinned Install or Upgrade
-
-Use when the user names a release such as `0.2.9`:
+Fresh install:
```bash
-npm install -g openclaw-openviking-setup-helper@latest
-ov-install -y --version 0.2.9
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+openclaw gateway restart
+openclaw openviking status --json
```
-This sets the plugin version to `v0.2.9`.
+Reconfigure:
-### Plugin-Only Upgrade
+```bash
+openclaw openviking setup --reconfigure
+openclaw gateway restart
+openclaw openviking status --json
+```
-Use only when the user explicitly wants to upgrade just the plugin:
+Upgrade:
```bash
-ov-install --update
+openclaw plugins update openviking
+openclaw gateway restart
+openclaw openviking status --json
```
-### Legacy Plugin Cleanup
-
-If the machine previously used `memory-openviking`, run the bundled cleanup script from this repository:
+Uninstall:
```bash
-bash examples/openclaw-plugin/upgrade_scripts/cleanup-memory-openviking.sh
+openclaw plugins uninstall openviking
+openclaw config set plugins.slots.contextEngine legacy
+openclaw gateway restart
```
-Then continue with install or upgrade.
+Native uninstall may not reset `plugins.slots.contextEngine`. Always run the explicit `config set` step after uninstall.
-## Verification
+## Config Fields
-### Check plugin slot
+Config path:
-```bash
-openclaw config get plugins.slots.contextEngine
+```text
+plugins.entries.openviking.config
```
-Expected output:
+Core fields:
-```text
-openviking
-```
+| Field | Meaning |
+| --- | --- |
+| `mode` | Legacy compatibility field. Expected value: `remote`. |
+| `baseUrl` | OpenViking HTTP endpoint |
+| `apiKey` | OpenViking API key |
+| `agent_prefix` | Optional; prefix for OpenClaw agent IDs when set. Interactive setup accepts only letters, digits, `_`, and `-`. If unset, the plugin follows session agent IDs. |
+| `accountId` | Required for root API keys |
+| `userId` | Required for root API keys |
-### Check plugin config
+## Verification
+
+Quick verification:
```bash
-openclaw config get plugins.entries.openviking.config
+openclaw openviking status --json
```
-### Check logs
-
-OpenClaw log:
+Manual verification:
```bash
+openclaw config get plugins.slots.contextEngine
+openclaw config get plugins.entries.openviking.config
openclaw logs --follow
```
-Look for:
+Expected log signal:
```text
openviking: registered context-engine
```
-OpenViking service log, default path:
-
-```bash
-cat ~/.openviking/data/log/openviking.log
-```
-
-### Pipeline Health Check (Optional)
-
-If the checks above all pass and you want to further verify the full Gateway → OpenViking pipeline, run the health check script:
+Optional end-to-end health check from a repository checkout:
```bash
python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
```
-This injects a real conversation through Gateway and verifies from the OpenViking side that the session was captured, committed, archived, and had memories extracted. See [health_check_tools/HEALTHCHECK.md](./health_check_tools/HEALTHCHECK.md) for full details.
+## Migrate From ov-install
+
+If ov-install was previously used, clean up before switching to `openclaw plugins install`:
-### Start command
+Same plugin ID (openviking, >= 0.3.x):
```bash
+rm -rf ~/.openclaw/extensions/openviking/
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --reconfigure
openclaw gateway restart
+openclaw openviking status --json
```
-## Plugin Config Reference
-
-Check the whole config first:
+Old plugin ID (memory-openviking, < 0.3.x):
```bash
-openclaw config get plugins.entries.openviking.config
+openclaw plugins uninstall memory-openviking 2>/dev/null || true
+openclaw config set plugins.slots.memory none
+rm -rf ~/.openclaw/extensions/memory-openviking/
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+openclaw gateway restart
+openclaw openviking status --json
```
-Core OpenClaw plugin fields:
+Existing config fields are preserved during migration. The new plugin reads old field names at runtime.
- `baseUrl`
- `apiKey`
- `agent_prefix`: optional; interactive setup accepts only letters, digits, `_`, and `-`
-## Uninstall
+## Backup Path: ov-install
-Plugin only:
+`ov-install` is the backup path, not the primary user install path. Use it when `openclaw plugins install @openclaw/openviking` cannot reach ClawHub, is rate-limited, or when the user explicitly wants a source ref / Git branch install.
+
+Backup install:
```bash
-bash examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh
+npm install -g openclaw-openviking-setup-helper
+ov-install
```
+
+Backup/source commands:
+
+| Intent | Command |
+| --- | --- |
+| Install from a source ref | `ov-install --plugin-version=<REF>` |
+| Non-interactive backup install | `ov-install --base-url <URL> --api-key <KEY>` |
+| Target a non-default OpenClaw state directory | `ov-install --workdir <PATH>` |
+| Show helper-tracked version | `ov-install --current-version` |
+| Update helper-managed install | `ov-install --update` |
+
+For user installs, always try `openclaw plugins install @openclaw/openviking` first. Choose `ov-install` only as the backup path.
diff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.md
index b6482e638..198960a43 100644
--- a/examples/openclaw-plugin/INSTALL-ZH.md
+++ b/examples/openclaw-plugin/INSTALL-ZH.md
@@ -1,18 +1,44 @@
-# 为 OpenClaw 安装 OpenViking 记忆功能
+# 为 OpenClaw 安装 OpenViking
-通过 [OpenViking](https://github.com/volcengine/OpenViking) 为 [OpenClaw](https://github.com/openclaw/openclaw) 提供长效记忆能力。安装完成后,OpenClaw 会自动记住对话中的重要信息,并在回复前回忆相关内容。
+OpenViking 通过 `@openclaw/openviking` 插件为 OpenClaw 提供长期记忆、知识库检索、语义搜索和 RAG 上下文能力。
-> 当前文档介绍的是基于 `context-engine` 架构的新版 OpenViking 插件。
+这份文档同时面向用户和自动化 agent:用户可以按步骤执行,agent 可以按命令和 JSON 结果判断下一步。
-## 前置条件
+## 不要把插件和 Skill 装混
-| 组件 | 版本要求 |
+`@openclaw/openviking` 是 OpenClaw 插件。
+
+不要用下面这个命令安装本插件:
+
+```bash
+clawhub install openviking
+```
+
+这个命令安装的是名为 `openviking` 的 AgentSkill,不是 OpenClaw 插件。
+
+安装插件应使用:
+
+```bash
+openclaw plugins install @openclaw/openviking
+```
+
+## 前置要求
+
+| 组件 | 要求 |
| --- | --- |
| Node.js | >= 22 |
-| OpenClaw | >= 2026.4.24 |
+| OpenClaw | >= 2026.4.8 |
插件以远程模式连接到已有的 OpenViking 服务。它不会帮你启动 OpenViking server。需要先启动 OpenViking,并保持服务运行,再把插件的 `baseUrl` 指向这个 HTTP 服务。默认本地地址是 `http://127.0.0.1:1933`。
+OpenClaw 插件包版本边界:
+
+- `2026.4.8` 是当前插件支持的最低 OpenClaw 版本。
+- `2026.5.3` 开始,OpenClaw 在安装包时会校验 TypeScript 插件入口是否有编译后的 JavaScript 产物。
+- `2026.5.4` 及之后,已安装/全局插件如果缺少编译后的 JavaScript,运行时不再回退加载 `.ts` 源码,插件可能被跳过。
+- 推荐的 `openclaw plugins install @openclaw/openviking` 会安装已经发布并包含 `dist/*.js` 的插件包,普通用户不需要本地编译。
+- `ov-install` 是备用/源码安装路径。当 ClawHub 或 OpenClaw 插件管理器路径不可用、被限流,或者明确需要测试源码 ref 时才使用。目标 OpenClaw `>= 2026.5.3` 时,它会在安装过程中编译插件。
+
快速检查:
```bash
@@ -54,79 +80,142 @@ openviking-server --host 0.0.0.0 --port 1933
curl http://127.0.0.1:1933/health
```
-## 旧版升级说明
+## 推荐安装方式
-如果你之前安装过旧版 `memory-openviking`,先清理旧插件,再执行下面的安装或升级命令。
+普通用户、正式环境和 agent 自动安装都优先使用这条路径。
-- 新版 `openviking` 与旧版 `memory-openviking` 不兼容,不能混装。
-- 如果你从未安装过旧版插件,可以跳过本节。
+### 1. 安装插件
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/cleanup-memory-openviking.sh -o cleanup-memory-openviking.sh
-bash cleanup-memory-openviking.sh
+openclaw plugins install @openclaw/openviking
```
-## 通过 ClawHub 安装(推荐)
+如果你的 OpenClaw 环境需要显式 registry 前缀,使用:
```bash
openclaw plugins install clawhub:@openclaw/openviking
```
-安装完成后运行交互式配置向导:
+### 2. 配置插件
+
+用户交互式配置:
```bash
openclaw openviking setup
```
-向导会提示你填写远程 OpenViking 服务地址和可选的 API Key,并将配置写入 `$OPENCLAW_STATE_DIR/openclaw.json`(默认:`~/.openclaw/openclaw.json`)。
+Agent 非交互配置:
-## 通过 ov-install 安装(替代方案)
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+```
-`ov-install` 一键完成插件部署。macOS、Linux、Windows 的流程相同。
+示例:
```bash
-npm install -g openclaw-openviking-setup-helper
+openclaw openviking setup --base-url http://127.0.0.1:1933 --api-key sk-xxx --json
+```
-# 安装插件
-ov-install
+`setup` 会写入 `plugins.entries.openviking.config`,并激活 `plugins.slots.contextEngine=openviking`。
+
+如果 OpenViking 服务暂时不可达,但你仍希望先保存配置:
+
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --allow-offline --json
+```
+
+如果使用 root API key,可能还需要租户上下文:
-# 安装插件到指定 OpenClaw 实例
-ov-install --workdir ~/.openclaw-second
+```bash
+openclaw openviking setup \
+ --base-url <OPENVIKING_URL> \
+ --api-key <ROOT_API_KEY> \
+ --account-id <ACCOUNT_ID> \
+ --user-id <USER_ID> \
+ --json
```
-## 升级
+如果已有其他 context engine 占用 slot,setup 默认不会替换。确认要替换时再使用:
-要把插件升级到最新版本,执行:
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json
+```
+
+如需自定义 agent 路由前缀(可选;多数用户留空即可):
```bash
-npm install -g openclaw-openviking-setup-helper@latest && ov-install -y
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json
```
-## 安装或升级到指定版本
+### 3. 重启 OpenClaw Gateway
-如果要安装或升级到某个正式发布版本,执行:
+```bash
+openclaw gateway restart
+```
+
+如果你的 OpenClaw 版本使用不同的重启命令,请使用对应的 gateway 重启方式。
+
+### 4. 验证
```bash
-ov-install -y --version 0.2.9
+openclaw openviking status --json
```
-## 参数说明
+期望结果:
-| 参数 | 含义 |
+| JSON 字段 | 期望值 |
| --- | --- |
-| `--workdir PATH` | 指定 OpenClaw 数据目录 |
-| `--version VER` | 指定插件版本,例如 `0.2.9` 会对应插件 `v0.2.9` |
-| `--current-version` | 查看当前已安装的插件版本 |
-| `--plugin-version REF` | 指定插件版本,支持 tag、分支或 commit |
-| `--github-repo owner/repo` | 指定插件来源仓库,默认 `volcengine/OpenViking` |
-| `--update` | 只升级插件 |
-| `-y` | 非交互模式,使用默认配置 |
+| `configured` | `true` |
+| `slotActive` | `true` |
+| `health.ok` | 服务可达时应为 `true` |
+
+也可以直接查看 OpenClaw 配置:
+
+```bash
+openclaw config get plugins.entries.openviking.config
+openclaw config get plugins.slots.contextEngine
+```
-## OpenClaw 插件参数说明
+`plugins.slots.contextEngine` 应输出 `openviking`。
-插件配置写在 `plugins.entries.openviking.config` 下。通常安装助手会自动写好,只有在你需要手动调整时,才需要关注下面这些参数。
+## Agent 判断规则
-查看当前插件整体配置:
+Agent 应优先使用 `--json`,并根据这些字段判断下一步:
+
+| 结果 | 含义 | 建议动作 |
+| --- | --- | --- |
+| `success: true` | 配置已保存,setup 完成 | 重启 gateway,然后执行 status |
+| `success: false`, `action: "slot_blocked"` | 配置可能已保存,但其他插件占用 `contextEngine` | 询问用户后再用 `--force-slot` |
+| `success: false`, `action: "error"` | 校验失败 | 展示 `error`,不要宣称安装成功 |
+| `health.ok: false` | 服务不可达 | 检查 URL/服务状态;只有用户接受时才用 `--allow-offline` |
+| `keyProbe.keyType: "root_key"` | root key 需要租户上下文 | 追加 `--account-id` 和 `--user-id` |
+
+## 配置说明
+
+插件配置位于:
+
+```text
+plugins.entries.openviking.config
+```
+
+核心字段:
+
+| 字段 | 默认值 | 说明 |
+| --- | --- | --- |
+| `mode` | `remote` | 兼容旧配置的字段。当前只支持 remote。 |
+| `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP 地址 |
+| `apiKey` | 空 | OpenViking API key |
+| `agent_prefix` | 空 | OpenClaw agent ID 的可选前缀;若没有 agent ID,插件使用 `main`。交互式配置只接受字母、数字、`_` 和 `-`。 |
+| `accountId` | 空 | 使用 root API key 时需要 |
+| `userId` | 空 | 使用 root API key 时需要 |
+
+普通修改优先使用 setup:
+
+```bash
+openclaw openviking setup --reconfigure
+```
+
+查看当前配置:
```bash
openclaw config get plugins.entries.openviking.config
@@ -150,74 +239,107 @@ openclaw config set plugins.entries.openviking.config.apiKey your-api-key
openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix
```
-## 启动
-
-安装完成后,运行:
+## 升级
```bash
+openclaw plugins update openviking
openclaw gateway restart
+openclaw openviking status --json
```
-Windows PowerShell:
+确认 `configured` 和 `slotActive` 都是 `true`。
+
+## 卸载
-```powershell
+```bash
+openclaw plugins uninstall openviking
+openclaw config set plugins.slots.contextEngine legacy
openclaw gateway restart
```
-## 验证
+当前 OpenClaw 原生卸载不一定会把 `plugins.slots.contextEngine` 恢复为 `legacy`。显式执行 `config set` 可以避免 slot 继续指向已卸载插件。
+
+## 可选链路健康检查
-检查插件是否已接管 `contextEngine`:
+如果 status 已通过,还想验证 Gateway 到 OpenViking 的完整链路,可以在仓库 checkout 中运行:
```bash
-openclaw config get plugins.slots.contextEngine
+python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
```
-输出 `openviking` 即表示插件已生效。
+该脚本会注入一次真实对话,并在 OpenViking 侧验证会话捕获、提交、归档和记忆提取。详见 [health_check_tools/HEALTHCHECK-ZH.md](./health_check_tools/HEALTHCHECK-ZH.md)。
-查看运行日志:
+## 备用路径:ov-install
+
+`ov-install` 是备用路径,不是主安装方式。仅当 `openclaw plugins install @openclaw/openviking` 无法访问 ClawHub、被限流,或者你明确需要从 Git 分支/源码 ref 安装测试时使用。
+
+先尝试 OpenClaw 插件管理器。如果该路径不可用,再执行:
```bash
-openclaw logs --follow
+npm install -g openclaw-openviking-setup-helper
+ov-install
```
-日志中出现 `openviking: registered context-engine`,表示插件已成功加载。
-
-查看 OpenViking 自身日志:
+常用备用/源码参数:
-默认日志文件在你的 `workspace/data/log/openviking.log`。如果使用默认配置,通常对应:
+| 参数 | 含义 |
+| --- | --- |
+| `--workdir PATH` | 指定 OpenClaw state 目录 |
+| `--version REF` | 指定 Git ref、tag、branch 或发布版本 |
+| `--current-version` | 查看 helper 记录的当前版本 |
+| `--base-url URL` | OpenViking 服务器地址(启用非交互模式) |
+| `--api-key KEY` | OpenViking API key |
+| `--agent-prefix PREFIX` | Agent 路由前缀 |
+| `--update` | 更新 helper 管理的安装 |
-```bash
-cat ~/.openviking/data/log/openviking.log
-```
+面向用户的安装,请先使用 `openclaw plugins install @openclaw/openviking`。只有作为备用路径时才选择 `ov-install`。
-查看当前已安装版本:
+## 从 ov-install 迁移到 openclaw plugin install
-```bash
-ov-install --current-version
-```
+如果之前通过 `ov-install` 安装了 OpenViking,切换到推荐的 `openclaw plugins install` 安装方式前需要清理。
-### 链路检查(可选)
+### 同一插件 ID(openviking,版本 >= 0.3.x)
-如果上述验证都正常,还想进一步确认从 Gateway 到 OpenViking 的完整链路是否通畅,可以使用插件自带的健康检查脚本:
+ov-install 的 context-engine 部署会将文件写入 `~/.openclaw/extensions/openviking/`。通过 npm 安装后,OpenClaw 可能仍从旧目录加载。清理步骤:
```bash
-python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
+# 删除 ov-install 部署的文件
+rm -rf ~/.openclaw/extensions/openviking/
+
+# 通过 OpenClaw 插件管理器安装
+openclaw plugins install @openclaw/openviking
+
+# 重新配置(openclaw.json 中的已有配置会保留)
+openclaw openviking setup --reconfigure
+openclaw gateway restart
+openclaw openviking status --json
```
-该脚本会进行一次真实的对话注入,然后从 OpenViking 侧验证会话是否被正确捕获、提交、归档并提取出记忆。详细说明见 [health_check_tools/HEALTHCHECK-ZH.md](./health_check_tools/HEALTHCHECK-ZH.md)。
+已有的配置字段(`baseUrl`、`apiKey`、`agentId` 等)会保留。新版本在运行时兼容读取旧字段名,无需手动修改配置。
-## 卸载
+### 旧插件 ID(memory-openviking,版本 < 0.3.x)
-卸载 OpenClaw 插件:
+旧版 memory 插件使用了不同的插件 ID 和 slot:
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh
-bash uninstall-openviking.sh
+# 卸载旧插件
+openclaw plugins uninstall memory-openviking 2>/dev/null || true
+
+# 清理旧 slot 和文件
+openclaw config set plugins.slots.memory none
+rm -rf ~/.openclaw/extensions/memory-openviking/
+
+# 安装新插件
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+openclaw gateway restart
+openclaw openviking status --json
```
-如果你的 OpenClaw 数据目录不是默认路径:
+或使用清理脚本:
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh
-bash uninstall-openviking.sh --workdir ~/.openclaw-second
+bash examples/openclaw-plugin/upgrade_scripts/cleanup-memory-openviking.sh
```
+
+另见:[INSTALL.md](./INSTALL.md) 和 [INSTALL-AGENT.md](./INSTALL-AGENT.md)。
diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.md
index 54e3272c2..6af9fa128 100644
--- a/examples/openclaw-plugin/INSTALL.md
+++ b/examples/openclaw-plugin/INSTALL.md
@@ -1,18 +1,44 @@
-# Installing OpenViking for OpenClaw
+# Install OpenViking for OpenClaw
-Use [OpenViking](https://github.com/volcengine/OpenViking) as the long-term memory backend for [OpenClaw](https://github.com/openclaw/openclaw). After installation, OpenClaw will automatically remember important facts from conversations and recall relevant context before replying.
+OpenViking provides long-term memory, knowledge base search, semantic retrieval, and RAG-style context for OpenClaw through the `@openclaw/openviking` plugin.
-> This document covers the current OpenViking plugin built on OpenClaw's `context-engine` architecture.
+This guide describes the current plugin install flow. It is written for both people and automation agents.
-## Prerequisites
+## Do Not Install The Skill By Mistake
-| Component | Required Version |
+`@openclaw/openviking` is an OpenClaw plugin.
+
+Do not use this command for plugin installation:
+
+```bash
+clawhub install openviking
+```
+
+That command installs an AgentSkill named `openviking`, not the OpenClaw plugin.
+
+Use this plugin command instead:
+
+```bash
+openclaw plugins install @openclaw/openviking
+```
+
+## Requirements
+
+| Component | Required |
| --- | --- |
| Node.js | >= 22 |
-| OpenClaw | >= 2026.4.24 |
+| OpenClaw | >= 2026.4.8 |
The plugin connects to an existing OpenViking server. It does not start the OpenViking server for you. Start OpenViking first, keep it running, then point the plugin `baseUrl` at that HTTP service. The default local URL is `http://127.0.0.1:1933`.
+OpenClaw plugin package boundaries:
+
+- `2026.4.8` is the minimum supported OpenClaw version for the current plugin.
+- `2026.5.3` starts validating package installs so TypeScript plugin entries need compiled JavaScript output.
+- `2026.5.4` and later stop falling back to `.ts` source for installed/global plugin runtime loading when compiled JavaScript is missing.
+- The recommended `openclaw plugins install @openclaw/openviking` path installs a published package that already includes `dist/*.js`.
+- `ov-install` is the backup/source install path. Use it when ClawHub or the OpenClaw plugin manager path is unavailable/rate-limited, or when explicitly testing a source ref. For OpenClaw `>= 2026.5.3`, it builds the plugin during installation.
+
Quick check:
```bash
@@ -54,181 +80,283 @@ Verify the server before installing or restarting the plugin:
curl http://127.0.0.1:1933/health
```
-## Legacy Upgrade Note
+## Recommended Install Path
-If you previously installed the legacy `memory-openviking` plugin, remove it first, then continue with the install or upgrade commands below.
+Use this path for normal users, production installs, and agent-assisted installs.
-- The new `openviking` plugin is not compatible with the legacy `memory-openviking` plugin.
-- If you never installed the legacy plugin, skip this section.
+### 1. Install The Plugin
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/cleanup-memory-openviking.sh -o cleanup-memory-openviking.sh
-bash cleanup-memory-openviking.sh
+openclaw plugins install @openclaw/openviking
```
-## Install via ClawHub (Recommended)
+If your OpenClaw installation requires an explicit registry prefix, use:
```bash
openclaw plugins install clawhub:@openclaw/openviking
```
-After installation, run the interactive setup wizard:
+### 2. Configure The Plugin
+
+For interactive human setup:
```bash
openclaw openviking setup
```
-The wizard prompts for your remote OpenViking server URL and optional API key, then writes configuration to `$OPENCLAW_STATE_DIR/openclaw.json` (default: `~/.openclaw/openclaw.json`).
+For non-interactive agent setup:
-## Install via ov-install (Alternative)
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+```
-The `ov-install` helper automates plugin deployment:
+Example:
```bash
-npm install -g openclaw-openviking-setup-helper
-ov-install
+openclaw openviking setup --base-url http://127.0.0.1:1933 --api-key sk-xxx --json
```
-Common variant:
+The setup command writes `plugins.entries.openviking.config` and activates `plugins.slots.contextEngine=openviking`.
+
+If the OpenViking server is temporarily unreachable but you still want to save the config:
```bash
-ov-install --workdir ~/.openclaw-second
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --allow-offline --json
```
-## Upgrade
-
-To upgrade the plugin to the latest version:
+If your API key is a root key, setup may require tenant context:
```bash
-npm install -g openclaw-openviking-setup-helper@latest && ov-install -y
+openclaw openviking setup \
+ --base-url <OPENVIKING_URL> \
+ --api-key <ROOT_API_KEY> \
+ --account-id <ACCOUNT_ID> \
+ --user-id <USER_ID> \
+ --json
```
-## Install or Upgrade a Specific Release
+If another context engine already owns the slot, setup will not replace it by default. To intentionally replace the current owner:
-To install or upgrade to a specific release:
+```bash
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json
+```
+
+If you need a custom agent routing prefix (optional; most users leave this empty):
```bash
-ov-install -y --version 0.2.9
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json
```
-## Parameters
+### 3. Restart OpenClaw Gateway
-| Parameter | Meaning |
-| --- | --- |
-| `--workdir PATH` | Target OpenClaw data directory |
-| `--version VER` | Set plugin version. For example, `0.2.9` maps to plugin `v0.2.9` |
-| `--current-version` | Print the currently installed plugin version |
-| `--plugin-version REF` | Set only the plugin version. Supports tag, branch, or commit |
-| `--github-repo owner/repo` | Use a different GitHub repository for plugin files. Default: `volcengine/OpenViking` |
-| `--update` | Upgrade only the plugin |
-| `-y` | Non-interactive mode, use default values |
+```bash
+openclaw gateway restart
+```
+
+If your OpenClaw version uses a different restart command, use the equivalent gateway restart for your environment.
-If you need to pin the installer itself:
+### 4. Verify
```bash
-npm install -g openclaw-openviking-setup-helper@VERSION
+openclaw openviking status --json
```
-## OpenClaw Plugin Configuration
+Expected result:
-The plugin configuration lives under `plugins.entries.openviking.config`.
+| JSON field | Expected value |
+| --- | --- |
+| `configured` | `true` |
+| `slotActive` | `true` |
+| `health.ok` | `true` when the server is reachable |
-Get the current full plugin configuration:
+You can also inspect the raw OpenClaw config:
```bash
openclaw config get plugins.entries.openviking.config
+openclaw config get plugins.slots.contextEngine
```
-### Configuration Parameters
+`plugins.slots.contextEngine` should be `openviking`.
-The plugin connects to an existing remote OpenViking server.
+## Agent Result Handling
-| Parameter | Default | Meaning |
+Automation should prefer `--json` and branch on these fields:
+
+| Result | Meaning | Recommended action |
| --- | --- | --- |
-| `baseUrl` | `http://127.0.0.1:1933` | Remote OpenViking HTTP endpoint |
-| `apiKey` | empty | Optional OpenViking API key |
-| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. If no agent ID is available, the plugin uses `main`. Interactive setup accepts only letters, digits, `_`, and `-` |
+| `success: true` | Config saved and setup completed | Restart gateway, then run status |
+| `success: false`, `action: "slot_blocked"` | Config may be saved, but another plugin owns `contextEngine` | Ask before rerunning with `--force-slot` |
+| `success: false`, `action: "error"` | Validation failed | Show `error`; do not claim install succeeded |
+| `health.ok: false` | Server unreachable | Check URL/server, or rerun with `--allow-offline` only if the user accepts |
+| `keyProbe.keyType: "root_key"` | Root key needs tenant context | Rerun with `--account-id` and `--user-id` |
-Common settings:
+## Configuration Reference
+
+The plugin config lives at:
+
+```text
+plugins.entries.openviking.config
+```
+
+Core fields:
+
+| Field | Default | Description |
+| --- | --- | --- |
+| `mode` | `remote` | Legacy compatibility field. Only remote mode is supported. |
+| `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP endpoint |
+| `apiKey` | empty | OpenViking API key |
+| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. If no agent ID is available, the plugin uses `main`. Interactive setup accepts only letters, digits, `_`, and `-`. |
+| `accountId` | empty | Required when using a root API key |
+| `userId` | empty | Required when using a root API key |
+
+Use setup for normal changes when possible:
```bash
-openclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933
-openclaw config set plugins.entries.openviking.config.apiKey your-api-key
-openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix
+openclaw openviking setup --reconfigure
```
-## Start
+Manual config inspection:
-After installation:
+```bash
+openclaw config get plugins.entries.openviking.config
+```
+
+## Upgrade
```bash
+openclaw plugins update openviking
openclaw gateway restart
+openclaw openviking status --json
```
-Windows PowerShell:
+Confirm that `configured` and `slotActive` are both `true`.
-```powershell
+## Uninstall
+
+```bash
+openclaw plugins uninstall openviking
+openclaw config set plugins.slots.contextEngine legacy
openclaw gateway restart
```
-## Verify
+Current OpenClaw native uninstall does not always reset `plugins.slots.contextEngine`. The explicit `config set` step avoids leaving the slot pointed at an uninstalled plugin.
-Check that the plugin owns the `contextEngine` slot:
+## Optional Pipeline Health Check
+
+After status passes, you can run the bundled end-to-end health check from a repository checkout:
```bash
-openclaw config get plugins.slots.contextEngine
+python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
```
-If the output is `openviking`, the plugin is active.
+This checks the Gateway to OpenViking path by injecting a real conversation and verifying capture, commit, archive, and memory extraction. See [health_check_tools/HEALTHCHECK.md](./health_check_tools/HEALTHCHECK.md).
-Follow OpenClaw logs:
+## Backup Path: ov-install
+
+`ov-install` is the backup path, not the primary install path. Use it when `openclaw plugins install @openclaw/openviking` cannot reach ClawHub, is rate-limited, or when you explicitly need to install/test plugin files from a Git branch or source ref.
+
+Try the OpenClaw plugin manager first. If that path is unavailable, run:
```bash
-openclaw logs --follow
+npm install -g openclaw-openviking-setup-helper
+ov-install
```
-If you see `openviking: registered context-engine`, the plugin loaded successfully.
+Useful backup/source flags:
+
+| Flag | Meaning |
+| --- | --- |
+| `--workdir PATH` | Target OpenClaw state directory |
+| `--version REF` | Git ref, tag, branch, or release version to install |
+| `--current-version` | Print the version tracked by the helper |
+| `--base-url URL` | OpenViking server URL (enables non-interactive mode) |
+| `--api-key KEY` | OpenViking API key |
+| `--agent-prefix PREFIX` | Agent routing prefix |
+| `--update` | Update an existing helper-managed install |
+
+For user-facing installs, use `openclaw plugins install @openclaw/openviking` first. Choose `ov-install` only as the backup path.
-Check the OpenViking service log:
+## Migrate From ov-install To openclaw plugin install
-By default the log file lives under `workspace/data/log/openviking.log`. With the default setup this is usually:
+If you previously installed OpenViking with `ov-install`, follow these steps before switching to the recommended `openclaw plugins install` path.
+
+### Same Plugin ID (openviking, version >= 0.3.x)
+
+The ov-install context-engine deployment writes files to `~/.openclaw/extensions/openviking/`. After installing via npm, OpenClaw may still load from the old directory. Clean it up:
```bash
-cat ~/.openviking/data/log/openviking.log
+# Remove ov-install deployed files
+rm -rf ~/.openclaw/extensions/openviking/
+
+# Install via the OpenClaw plugin manager
+openclaw plugins install @openclaw/openviking
+
+# Reconfigure (your existing config in openclaw.json is preserved)
+openclaw openviking setup --reconfigure
+openclaw gateway restart
+openclaw openviking status --json
```
-Check installed versions:
+Your existing config fields (`baseUrl`, `apiKey`, `agentId`, etc.) are preserved. The new plugin version reads old field names at runtime — no manual config edits needed.
+
+The plugin configuration lives under `plugins.entries.openviking.config`.
+
+Get the current full plugin configuration:
```bash
-ov-install --current-version
+openclaw config get plugins.entries.openviking.config
```
-### Pipeline Health Check (Optional)
+### Configuration Parameters
-If the steps above all look good and you want to further verify the full Gateway → OpenViking pipeline, run the plugin's health check script:
+The plugin connects to an existing remote OpenViking server.
+
+| Parameter | Default | Meaning |
+| --- | --- | --- |
+| `baseUrl` | `http://127.0.0.1:1933` | Remote OpenViking HTTP endpoint |
+| `apiKey` | empty | Optional OpenViking API key |
+| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. If no agent ID is available, the plugin uses `main`. Interactive setup accepts only letters, digits, `_`, and `-` |
+
+Common settings:
```bash
-python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
+openclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933
+openclaw config set plugins.entries.openviking.config.apiKey your-api-key
+openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix
```
-This script injects a real conversation through Gateway and then verifies from the OpenViking side that the session was captured, committed, archived, and had memories extracted. See [health_check_tools/HEALTHCHECK.md](./health_check_tools/HEALTHCHECK.md) for full details.
-
-## Uninstall
+## Start
-To remove the OpenClaw plugin:
+After installation (if you skipped reconfigure above):
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh
-bash uninstall-openviking.sh
+openclaw gateway restart
+openclaw openviking status --json
```
-For a non-default OpenClaw state directory:
+### Old Plugin ID (memory-openviking, version < 0.3.x)
+
+The old memory plugin used a different plugin ID and slot:
```bash
-curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-plugin/upgrade_scripts/uninstall-openclaw-plugin.sh -o uninstall-openviking.sh
-bash uninstall-openviking.sh --workdir ~/.openclaw-second
+# Uninstall old plugin
+openclaw plugins uninstall memory-openviking 2>/dev/null || true
+
+# Clean up old slot and files
+openclaw config set plugins.slots.memory none
+rm -rf ~/.openclaw/extensions/memory-openviking/
+
+# Install new plugin
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --json
+openclaw gateway restart
+openclaw openviking status --json
```
----
+Or use the cleanup script:
+
+```bash
+bash examples/openclaw-plugin/upgrade_scripts/cleanup-memory-openviking.sh
+```
-See also: [INSTALL-ZH.md](./INSTALL-ZH.md)
+See also: [INSTALL-ZH.md](./INSTALL-ZH.md) and [INSTALL-AGENT.md](./INSTALL-AGENT.md).
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 729757ae8..8d890675f 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -1,8 +1,45 @@
-# OpenClaw + OpenViking Context-Engine Plugin
+# @openclaw/openviking — OpenViking OpenClaw Plugin
-Use [OpenViking](https://github.com/volcengine/OpenViking) as the long-term memory backend for [OpenClaw](https://github.com/openclaw/openclaw). In OpenClaw, this plugin is registered as the `openviking` context engine.
+OpenClaw context-engine plugin for OpenViking remote memory, context database, RAG and semantic retrieval.
+
+## Important: Plugin vs Skill
+
+This page is for the **OpenClaw plugin package**:
+
+```
+@openclaw/openviking
+```
+
+**Do NOT** install the plugin with `clawhub install openviking` — that installs the `openviking` AgentSkill (under `skills/openviking`), which is a different thing.
+
+For **agent-assisted plugin setup**, ask the agent to follow [INSTALL-AGENT.md](./INSTALL-AGENT.md). The primary install path is still `openclaw plugins install @openclaw/openviking`.
+
+## Install (Natural Language)
+
+Ask your agent:
+
+> Install the OpenClaw plugin @openclaw/openviking for OpenViking remote memory. My server is at `http://my-server:1933` and my API key is `sk-xxx`.
+
+Or in Chinese:
+
+> 帮我安装 OpenViking 远程记忆插件 @openclaw/openviking。我的服务器地址是 `http://my-server:1933`,API key 是 `sk-xxx`。
-This document is not an installation guide. It is an implementation-focused design note for integrators and engineers. It describes how the plugin works today based on the code under `examples/openclaw-plugin`, not a future refactor target.
+The agent will automatically run install → setup → restart → verify. No manual steps needed.
+
+## Install (Command Line)
+
+```bash
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url http://my-server:1933 --api-key sk-xxx --json
+openclaw gateway restart
+openclaw openviking status --json
+```
+
+The `setup` command automatically activates the context-engine slot and validates the server connection.
+
+## Search Keywords
+
+@openclaw/openviking, openclaw openviking plugin, openviking remote memory plugin, OpenViking Context Database plugin, install-openviking-memory.
## Documentation
@@ -10,6 +47,14 @@ This document is not an installation guide. It is an implementation-focused desi
- Chinese design and install guide: [INSTALL-ZH.md](./INSTALL-ZH.md)
- Agent-oriented operator guide: [INSTALL-AGENT.md](./INSTALL-AGENT.md)
+---
+
+## Technical Overview
+
+Use [OpenViking](https://github.com/volcengine/OpenViking) as the long-term memory backend for [OpenClaw](https://github.com/openclaw/openclaw). In OpenClaw, this plugin is registered as the `openviking` context engine.
+
+The remainder of this document is an implementation-focused design note for integrators and engineers.
+
## Design Positioning
- OpenClaw still owns the agent runtime, prompt orchestration, and tool execution.
@@ -223,7 +268,8 @@ If you need to debug this plugin, start with these entry points.
### Inspect the current setup
```bash
-ov-install --current-version
+openclaw openviking status --json
+openclaw plugins list
openclaw config get plugins.entries.openviking.config
openclaw config get plugins.slots.contextEngine
```
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index b89d921f8..297f224d6 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -1,8 +1,41 @@
-# OpenClaw + OpenViking 上下文引擎插件
+# @openclaw/openviking — OpenViking OpenClaw 插件
-使用 [OpenViking](https://github.com/volcengine/OpenViking) 作为 [OpenClaw](https://github.com/openclaw/openclaw) 的长期记忆后端。在 OpenClaw 中,此插件注册为 `openviking` 上下文引擎。
+OpenClaw 上下文引擎插件,用于接入 OpenViking 远程记忆、上下文数据库、RAG 和语义检索。
+
+## 重要:插件 vs Skill 区分
+
+本页面是 **OpenClaw 插件包**:
+
+```
+@openclaw/openviking
+```
+
+**不要** 使用 `clawhub install openviking` 安装插件——那安装的是 `openviking` AgentSkill(`skills/openviking` 下的技能描述),不是本插件。
+
+如需 **Agent 辅助安装插件**,让 agent 按 [INSTALL-AGENT.md](./INSTALL-AGENT.md) 执行。主安装方式仍然是 `openclaw plugins install @openclaw/openviking`。
+
+## 安装(自然语言)
+
+对你的 agent 说:
+
+> 帮我安装 OpenViking 远程记忆插件 @openclaw/openviking。我的服务器地址是 `http://my-server:1933`,API key 是 `sk-xxx`。
+
+Agent 会自动完成安装 → 配置 → 重启 → 验证,无需手动操作。
-本文档不是安装教程,而是面向集成方和工程师的"当前实现设计说明"。它基于 `examples/openclaw-plugin` 里的现有代码,重点解释这套插件今天实际上如何工作,而不是未来可能的重构方向。
+## 安装(命令行)
+
+```bash
+openclaw plugins install @openclaw/openviking
+openclaw openviking setup --base-url http://my-server:1933 --api-key sk-xxx --json
+openclaw gateway restart
+openclaw openviking status --json
+```
+
+`setup` 命令会自动激活 context-engine slot 并验证服务器连接。
+
+## 搜索关键词
+
+@openclaw/openviking, openclaw openviking 插件, openviking 远程记忆插件, OpenViking 上下文数据库插件, install-openviking-memory
## 文档入口
@@ -10,6 +43,14 @@
- English install guide: [INSTALL.md](./INSTALL.md)
- Agent 专用操作文档:[INSTALL-AGENT.md](./INSTALL-AGENT.md)
+---
+
+## 技术概述
+
+使用 [OpenViking](https://github.com/volcengine/OpenViking) 作为 [OpenClaw](https://github.com/openclaw/openclaw) 的长期记忆后端。在 OpenClaw 中,此插件注册为 `openviking` 上下文引擎。
+
+以下内容是面向集成方和工程师的实现设计说明。
+
## 设计定位
- OpenClaw 仍然负责 agent runtime、prompt 编排和工具执行。
@@ -223,7 +264,8 @@ OpenViking 服务需要独立部署并运行,插件才能连接到它。
### 查看当前配置
```bash
-ov-install --current-version
+openclaw openviking status --json
+openclaw plugins list
openclaw config get plugins.entries.openviking.config
openclaw config get plugins.slots.contextEngine
```
diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.ts
index 16e48458f..d4e6fff04 100644
--- a/examples/openclaw-plugin/commands/setup.ts
+++ b/examples/openclaw-plugin/commands/setup.ts
@@ -2,14 +2,61 @@ 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";
+import { fileURLToPath } from "node:url";
+import { getEnv } from "../runtime-utils.js";
const HOME = os.homedir();
const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");
const DEFAULT_REMOTE_URL = "http://127.0.0.1:1933";
+function findPluginPackageRoot(fromDir = path.dirname(fileURLToPath(import.meta.url))): string | null {
+ let current = path.resolve(fromDir);
+ for (let depth = 0; depth < 5; depth += 1) {
+ if (
+ fs.existsSync(path.join(current, "package.json")) &&
+ fs.existsSync(path.join(current, "openclaw.plugin.json"))
+ ) {
+ return current;
+ }
+
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+ return null;
+}
+
+function readPluginVersion(): string {
+ try {
+ const packageRoot = findPluginPackageRoot();
+ if (!packageRoot) return "unknown";
+ const pkgPath = path.join(packageRoot, "package.json");
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
+ return String(pkg.version ?? "unknown");
+ } catch {
+ return "unknown";
+ }
+}
+
+function readCompatRangeFromManifest(): { min: string; max: string } {
+ try {
+ const packageRoot = findPluginPackageRoot();
+ if (!packageRoot) return { min: "", max: "" };
+ const manifestPath = path.join(packageRoot, "install-manifest.json");
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
+ const compat = manifest?.compatibility ?? {};
+ return {
+ min: String(compat.minOpenvikingVersion ?? ""),
+ max: String(compat.maxOpenvikingVersion ?? ""),
+ };
+ } catch {
+ return { min: "", max: "" };
+ }
+}
+
+const PLUGIN_VERSION = readPluginVersion();
+const { min: COMPATIBLE_SERVER_MIN, max: COMPATIBLE_SERVER_MAX } = readCompatRangeFromManifest();
+
type CommandProgram = {
command: (name: string) => CommandBuilder;
};
@@ -71,42 +118,144 @@ function ask(rl: readline.Interface, prompt: string, defaultValue = ""): Promise
});
}
-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() }); });
- });
+type VersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";
+
+type HealthResult = {
+ ok: boolean;
+ version: string;
+ error: string;
+ compatibility: VersionCompatibility;
+ pluginVersion: string;
+ compatRange: string;
+};
+
+function parseVersionTuple(v: string): number[] | null {
+ const cleaned = v.replace(/^v/i, "").split("-")[0];
+ const parts = cleaned.split(".").map(Number);
+ if (parts.some(isNaN)) return null;
+ return parts;
}
-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;
+function compareVersions(a: number[], b: number[]): number {
+ const len = Math.max(a.length, b.length);
+ for (let i = 0; i < len; i++) {
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
+ if (diff !== 0) return diff;
}
- const r = await capture("which", [cmd]);
- return r.out.trim() || cmd;
+ return 0;
}
-async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<{ ok: boolean; version: string; error: string }> {
+function checkVersionCompatibility(serverVersion: string): VersionCompatibility {
+ if (!serverVersion) return "unknown";
+ const sv = parseVersionTuple(serverVersion);
+ if (!sv) return "unknown";
+
+ if (COMPATIBLE_SERVER_MIN) {
+ const minV = parseVersionTuple(COMPATIBLE_SERVER_MIN);
+ if (minV && compareVersions(sv, minV) < 0) return "server_too_old";
+ }
+ if (COMPATIBLE_SERVER_MAX) {
+ const maxV = parseVersionTuple(COMPATIBLE_SERVER_MAX);
+ if (maxV && compareVersions(sv, maxV) > 0) return "server_too_new";
+ }
+ return "compatible";
+}
+
+function formatCompatRange(): string {
+ if (COMPATIBLE_SERVER_MIN && COMPATIBLE_SERVER_MAX) return `${COMPATIBLE_SERVER_MIN} ~ ${COMPATIBLE_SERVER_MAX}`;
+ if (COMPATIBLE_SERVER_MIN) return `>= ${COMPATIBLE_SERVER_MIN}`;
+ if (COMPATIBLE_SERVER_MAX) return `<= ${COMPATIBLE_SERVER_MAX}`;
+ return "any";
+}
+
+type ApiKeyProbeResult = {
+ keyType: "user_key" | "root_key" | "no_key" | "unknown";
+ needsAccountId: boolean;
+ needsUserId: boolean;
+ detail: string;
+};
+
+async function probeApiKeyType(baseUrl: string, apiKey?: string): Promise<ApiKeyProbeResult> {
+ if (!apiKey) return { keyType: "no_key", needsAccountId: false, needsUserId: false, detail: "No API key configured" };
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10_000);
+ const sessionsUrl = `${baseUrl.replace(/\/+$/, "")}/api/v1/sessions?limit=1`;
+ try {
+ const headers: Record<string, string> = { "X-API-Key": apiKey };
+ const response = await fetch(sessionsUrl, {
+ headers,
+ signal: controller.signal,
+ });
+
+ if (response.ok) {
+ return { keyType: "user_key", needsAccountId: false, needsUserId: false, detail: "API key has full user context" };
+ }
+
+ // Server raises InvalidArgumentError (-> HTTP 400) when a ROOT key calls
+ // tenant-scoped endpoints without X-OpenViking-Account / X-OpenViking-User.
+ // 401/403 may also be returned by older versions, FastAPI validation can
+ // surface as 422. Treat all four as candidates for tenant-context errors.
+ if ([400, 401, 403, 422].includes(response.status)) {
+ let body = "";
+ try {
+ body = await response.text();
+ } catch { /* ignore parse errors */ }
+ const lower = body.toLowerCase();
+ const needsAccount = /x-openviking-account|account[_ ]?id|account context|tenant/.test(lower);
+ const needsUser = /x-openviking-user|user[_ ]?id|user context|user key/.test(lower);
+ if (needsAccount || needsUser) {
+ return {
+ keyType: "root_key",
+ needsAccountId: needsAccount,
+ needsUserId: needsUser,
+ detail: body.slice(0, 200),
+ };
+ }
+
+ // Body did not name account/user/tenant explicitly (custom auth middleware,
+ // localized message, etc.). Re-probe with placeholder tenant headers; if
+ // the failure was due to missing tenant headers the response will change.
+ try {
+ const probeHeaders: Record<string, string> = {
+ "X-API-Key": apiKey,
+ "X-OpenViking-Account": "__probe__",
+ "X-OpenViking-User": "__probe__",
+ };
+ const probe2 = await fetch(sessionsUrl, {
+ headers: probeHeaders,
+ signal: controller.signal,
+ });
+ if (probe2.status !== response.status) {
+ return {
+ keyType: "root_key",
+ needsAccountId: true,
+ needsUserId: true,
+ detail: body.slice(0, 200) || `HTTP ${response.status} -> ${probe2.status} after adding tenant headers`,
+ };
+ }
+ } catch { /* ignore probe errors, fall through to unknown */ }
+
+ if (response.status === 401 || response.status === 403) {
+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status} - authentication failed, verify your API key` };
+ }
+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status}${body ? ` - ${body.slice(0, 160)}` : ""}` };
+ }
+
+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status}` };
+ } catch (err) {
+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: String(err instanceof Error ? err.message : err) };
+ } finally {
+ clearTimeout(timeoutId);
+ }
+}
+
+async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<HealthResult> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10_000);
try {
const headers: Record<string, string> = {};
- if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
+ if (apiKey) headers["X-API-Key"] = apiKey;
const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/health`, {
headers,
signal: controller.signal,
@@ -114,14 +263,17 @@ async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<{ o
if (response.ok) {
try {
const data = await response.json() as Record<string, unknown>;
- return { ok: true, version: String(data.version ?? ""), error: "" };
+ const result = (data.result ?? data) as Record<string, unknown>;
+ const version = String(result.version ?? data.version ?? "");
+ const compatibility = checkVersionCompatibility(version);
+ return { ok: true, version, error: "", compatibility, pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
} catch {
- return { ok: true, version: "", error: "" };
+ return { ok: true, version: "", error: "", compatibility: "unknown", pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
}
}
- return { ok: false, version: "", error: `HTTP ${response.status}` };
+ return { ok: false, version: "", error: `HTTP ${response.status}`, compatibility: "unknown", pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
} catch (err) {
- return { ok: false, version: "", error: String(err instanceof Error ? err.message : err) };
+ return { ok: false, version: "", error: String(err instanceof Error ? err.message : err), compatibility: "unknown", pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
} finally {
clearTimeout(timeoutId);
}
@@ -147,6 +299,31 @@ function getExistingPluginConfig(config: Record<string, unknown>): Record<string
return cfg && cfg.mode ? cfg : null;
}
+function backupConfig(configPath: string): string | null {
+ if (!fs.existsSync(configPath)) return null;
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
+ const backupPath = `${configPath}.bak.${timestamp}`;
+ try {
+ fs.copyFileSync(configPath, backupPath);
+ return backupPath;
+ } catch {
+ return null;
+ }
+}
+
+function ensureInstallRecord(plugins: Record<string, unknown>): void {
+ const installs = plugins.installs as Record<string, unknown> | undefined;
+ if (installs && typeof installs === "object") {
+ delete installs.openviking;
+ }
+
+ if (!plugins.allow) plugins.allow = [];
+ const allow = plugins.allow as string[];
+ if (!allow.includes("openviking")) {
+ allow.push("openviking");
+ }
+}
+
function writeConfig(
configPath: string,
pluginCfg: Record<string, unknown>,
@@ -154,6 +331,8 @@ function writeConfig(
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
+ backupConfig(configPath);
+
const config = readOpenClawConfig(configPath);
if (!config.plugins) config.plugins = {};
@@ -164,6 +343,8 @@ function writeConfig(
const existingEntry = (entries.openviking as Record<string, unknown>) ?? {};
entries.openviking = { ...existingEntry, config: pluginCfg };
+ ensureInstallRecord(plugins);
+
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
}
@@ -178,6 +359,78 @@ function isLegacyLocalMode(existing: Record<string, unknown>): boolean {
return mode !== "remote";
}
+type SetupResult = {
+ success: boolean;
+ action: "configured" | "existing" | "error" | "slot_blocked";
+ config?: {
+ mode: string;
+ baseUrl: string;
+ apiKey?: string;
+ agent_prefix?: string;
+ accountId?: string;
+ userId?: string;
+ };
+ health?: HealthResult;
+ keyProbe?: ApiKeyProbeResult;
+ slot: SlotActivationResult;
+ error?: string;
+};
+
+function setExitCodeOnFailure(result: { success: boolean }): void {
+ if (!result.success) {
+ process.exitCode = 1;
+ }
+}
+
+type StatusResult = {
+ configured: boolean;
+ config?: {
+ mode: string;
+ baseUrl: string;
+ hasApiKey: boolean;
+ agent_prefix?: string;
+ hasAccountId: boolean;
+ hasUserId: boolean;
+ };
+ health?: HealthResult;
+ keyProbe?: ApiKeyProbeResult;
+ slotActive: boolean;
+};
+
+type SlotActivationResult = {
+ activated: boolean;
+ previousOwner?: string;
+ replaced: boolean;
+};
+
+function activateContextEngineSlot(configPath: string, force = false): SlotActivationResult {
+ const config = readOpenClawConfig(configPath);
+ if (!config.plugins) config.plugins = {};
+ const plugins = config.plugins as Record<string, unknown>;
+ if (!plugins.slots) plugins.slots = {};
+ const slots = plugins.slots as Record<string, unknown>;
+
+ const current = slots.contextEngine as string | undefined;
+
+ if (current === "openviking") return { activated: false, replaced: false };
+
+ if (current && current !== "openviking" && !force) {
+ return { activated: false, previousOwner: current, replaced: false };
+ }
+
+ slots.contextEngine = "openviking";
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
+ return { activated: true, previousOwner: current || undefined, replaced: !!current };
+}
+
+function isContextEngineSlotActive(configPath: string): boolean {
+ const config = readOpenClawConfig(configPath);
+ const plugins = config.plugins as Record<string, unknown> | undefined;
+ if (!plugins) return false;
+ const slots = plugins.slots as Record<string, unknown> | undefined;
+ return slots?.contextEngine === "openviking";
+}
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function registerSetupCli(api: any): void {
if (!api.registerCli) {
@@ -191,14 +444,63 @@ export function registerSetupCli(api: any): void {
ovCmd
.command("setup")
- .description("Interactive setup wizard for OpenViking plugin configuration")
+ .description("Setup OpenViking plugin (supports both interactive and non-interactive modes)")
.option("--reconfigure", "Force re-entry of all configuration values")
.option("--zh", "Chinese prompts")
- .action(async (rawOptions: unknown) => {
- const options = (rawOptions ?? {}) as { reconfigure?: boolean; zh?: boolean };
- const zh = detectLangZh(options as Record<string, unknown>);
- const configDir = OPENCLAW_DIR;
- const configPath = path.join(configDir, "openclaw.json");
+ .option("--base-url <url>", "OpenViking server URL (enables non-interactive mode)")
+ .option("--api-key <key>", "API key for authentication")
+ .option("--agent-prefix <prefix>", "Agent routing prefix for namespace isolation")
+ .option("--account-id <id>", "Account ID (required for root API keys)")
+ .option("--user-id <id>", "User ID (required for root API keys)")
+ .option("--allow-offline", "Allow config write even if server is unreachable")
+ .option("--force-slot", "Replace existing contextEngine slot even if owned by another plugin")
+ .option("--json", "Output result as JSON (machine-readable)")
+ .action(async (...args: unknown[]) => {
+ const options = (args[0] ?? {}) as Record<string, unknown>;
+ const {
+ reconfigure, zh: zhOpt, baseUrl, apiKey, agentPrefix,
+ accountId, userId, allowOffline, forceSlot, json: jsonOpt,
+ } = options as {
+ reconfigure?: boolean; zh?: boolean; baseUrl?: string;
+ apiKey?: string; agentPrefix?: string; accountId?: string;
+ userId?: string; allowOffline?: boolean; forceSlot?: boolean;
+ json?: boolean;
+ };
+ const zh = detectLangZh(options);
+ const configPath = path.join(OPENCLAW_DIR, "openclaw.json");
+ const jsonMode = !!jsonOpt;
+ const nonInteractive = !!baseUrl;
+
+ if (nonInteractive) {
+ const result = await setupNonInteractive(configPath, {
+ baseUrl: baseUrl!,
+ apiKey,
+ agentPrefix,
+ accountId,
+ userId,
+ allowOffline: !!allowOffline,
+ forceSlot: !!forceSlot,
+ });
+ if (jsonMode) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ printSetupResult(zh, result);
+ }
+ setExitCodeOnFailure(result);
+ return;
+ }
+
+ if (jsonMode && !nonInteractive) {
+ const result: SetupResult = {
+ success: false,
+ action: "error",
+ slot: { activated: false, replaced: false },
+ error: "--json requires --base-url for non-interactive mode",
+ };
+ console.log(JSON.stringify(result, null, 2));
+ setExitCodeOnFailure(result);
+ return;
+ }
console.log("");
console.log(`🦣 ${tr(zh, "OpenViking Plugin Setup", "OpenViking 插件配置向导")}`);
@@ -211,7 +513,7 @@ export function registerSetupCli(api: any): void {
const q = (prompt: string, def = "") => ask(rl, prompt, def);
try {
- if (existing && !options.reconfigure) {
+ if (existing && !reconfigure) {
if (isLegacyLocalMode(existing)) {
console.log(tr(
zh,
@@ -244,6 +546,9 @@ export function registerSetupCli(api: any): void {
await runRemoteCheck(zh, existing);
+ const slotResult = activateContextEngineSlot(configPath);
+ printSlotResult(zh, slotResult);
+
console.log(tr(zh,
"✓ Plugin is ready. Run `openclaw gateway --force` to activate.",
"✓ 插件已就绪。运行 `openclaw gateway --force` 以激活。",
@@ -280,11 +585,52 @@ export function registerSetupCli(api: any): void {
rl.close();
}
});
+
+ ovCmd
+ .command("status")
+ .description("Show current OpenViking plugin status and connectivity")
+ .option("--zh", "Chinese prompts")
+ .option("--json", "Output result as JSON (machine-readable)")
+ .action(async (...args: unknown[]) => {
+ const options = (args[0] ?? {}) as Record<string, unknown>;
+ const { zh: zhOpt, json: jsonOpt } = options as { zh?: boolean; json?: boolean };
+ const zh = detectLangZh(options);
+ const configPath = path.join(OPENCLAW_DIR, "openclaw.json");
+ const jsonMode = !!jsonOpt;
+
+ const result = await getStatus(configPath);
+
+ if (jsonMode) {
+ console.log(JSON.stringify(result, null, 2));
+ return;
+ }
+
+ printStatus(zh, result);
+ });
},
{ commands: ["openviking"] },
);
}
+function printCompatibilityWarning(zh: boolean, health: HealthResult): void {
+ if (health.compatibility === "server_too_old") {
+ console.log(` ⚠ ${tr(zh,
+ `Server version ${health.version} is older than recommended (${health.compatRange}). Some features may not work. Please upgrade OpenViking server.`,
+ `服务端版本 ${health.version} 低于推荐范围(${health.compatRange})。部分功能可能不可用,请升级 OpenViking 服务端。`,
+ )}`);
+ } else if (health.compatibility === "server_too_new") {
+ console.log(` ⚠ ${tr(zh,
+ `Server version ${health.version} is newer than supported (${health.compatRange}). Please upgrade the OpenViking plugin.`,
+ `服务端版本 ${health.version} 高于插件支持范围(${health.compatRange})。请升级 OpenViking 插件。`,
+ )}`);
+ } else if (health.compatibility === "unknown" && health.ok) {
+ console.log(` ⚠ ${tr(zh,
+ "Could not determine server version. Compatibility check skipped.",
+ "无法获取服务端版本,已跳过兼容性检查。",
+ )}`);
+ }
+}
+
async function runRemoteCheck(
zh: boolean,
existing: Record<string, unknown>,
@@ -296,12 +642,254 @@ async function runRemoteCheck(
if (health.ok) {
const ver = health.version ? ` (version: ${health.version})` : "";
console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
+ printCompatibilityWarning(zh, health);
} else {
console.log(` ✗ ${tr(zh, `Connection failed: ${health.error}`, `连接失败: ${health.error}`)}`);
}
console.log("");
}
+async function setupNonInteractive(
+ configPath: string,
+ params: { baseUrl: string; apiKey?: string; agentPrefix?: string; accountId?: string; userId?: string; allowOffline?: boolean; forceSlot?: boolean },
+): Promise<SetupResult> {
+ try {
+ const { baseUrl, apiKey, agentPrefix, accountId, userId, allowOffline, forceSlot } = params;
+
+ // Phase 1: validate connectivity and key type BEFORE writing config
+ const health = await checkServiceHealth(baseUrl, apiKey);
+
+ if (!health.ok && !allowOffline) {
+ return {
+ success: false,
+ action: "error",
+ config: { mode: "remote", baseUrl },
+ health,
+ slot: { activated: false, replaced: false },
+ error: `Server unreachable: ${health.error}. Use --allow-offline to save config anyway.`,
+ };
+ }
+
+ const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;
+
+ if (keyProbe?.keyType === "root_key" && (!accountId || !userId)) {
+ const missing: string[] = [];
+ if (!accountId) missing.push("--account-id");
+ if (!userId) missing.push("--user-id");
+ return {
+ success: false,
+ action: "error",
+ config: {
+ mode: "remote",
+ baseUrl,
+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),
+ },
+ health,
+ keyProbe,
+ slot: { activated: false, replaced: false },
+ error: `Root API key detected. Missing: ${missing.join(", ")}. Re-run with: ${missing.map(f => `${f} <value>`).join(" ")}`,
+ };
+ }
+
+ // Phase 2: all checks passed (or --allow-offline), write config and activate slot
+ const pluginCfg: Record<string, unknown> = { mode: "remote", baseUrl };
+ if (apiKey) pluginCfg.apiKey = apiKey;
+ if (agentPrefix) pluginCfg.agent_prefix = agentPrefix;
+ if (accountId) pluginCfg.accountId = accountId;
+ if (userId) pluginCfg.userId = userId;
+
+ writeConfig(configPath, pluginCfg);
+ const slot = activateContextEngineSlot(configPath, !!forceSlot);
+
+ if (!slot.activated && slot.previousOwner) {
+ return {
+ success: false,
+ action: "slot_blocked",
+ config: {
+ mode: "remote",
+ baseUrl,
+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),
+ ...(agentPrefix ? { agent_prefix: agentPrefix } : {}),
+ ...(accountId ? { accountId } : {}),
+ ...(userId ? { userId } : {}),
+ },
+ health,
+ keyProbe,
+ slot,
+ error: `contextEngine slot is owned by "${slot.previousOwner}". Config was saved but slot was NOT changed. Use --force-slot to replace.`,
+ };
+ }
+
+ return {
+ success: true,
+ action: "configured",
+ config: {
+ mode: "remote",
+ baseUrl,
+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),
+ ...(agentPrefix ? { agent_prefix: agentPrefix } : {}),
+ ...(accountId ? { accountId } : {}),
+ ...(userId ? { userId } : {}),
+ },
+ health,
+ keyProbe,
+ slot,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ action: "error",
+ slot: { activated: false, replaced: false },
+ error: String(err instanceof Error ? err.message : err),
+ };
+ }
+}
+
+function printSetupResult(zh: boolean, result: SetupResult): void {
+ console.log("");
+ if (result.success) {
+ console.log(`🦣 ${tr(zh, "OpenViking Plugin Setup Complete", "OpenViking 插件配置完成")}`);
+ console.log("");
+ if (result.config) {
+ console.log(` mode: ${result.config.mode}`);
+ console.log(` baseUrl: ${result.config.baseUrl}`);
+ if (result.config.apiKey) console.log(` apiKey: ${result.config.apiKey}`);
+ if (result.config.agent_prefix) console.log(` agent_prefix: ${result.config.agent_prefix}`);
+ if (result.config.accountId) console.log(` accountId: ${result.config.accountId}`);
+ if (result.config.userId) console.log(` userId: ${result.config.userId}`);
+ }
+ console.log("");
+ if (result.health?.ok) {
+ const ver = result.health.version ? ` (version: ${result.health.version})` : "";
+ console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
+ printCompatibilityWarning(zh, result.health);
+ } else if (result.health) {
+ console.log(` ✗ ${tr(zh, `Connection failed: ${result.health.error}`, `连接失败: ${result.health.error}`)}`);
+ }
+ if (result.keyProbe) {
+ printKeyProbeWarning(zh, result.keyProbe);
+ }
+ printSlotResult(zh, result.slot);
+ console.log("");
+ console.log(tr(zh,
+ "Run `openclaw gateway --force` to activate the plugin.",
+ "运行 `openclaw gateway --force` 以激活插件。",
+ ));
+ } else {
+ console.log(`✗ ${tr(zh, "Setup failed", "配置失败")}: ${result.error}`);
+ if (result.keyProbe?.keyType === "root_key") {
+ printKeyProbeWarning(zh, result.keyProbe);
+ }
+ }
+ console.log("");
+}
+
+async function getStatus(configPath: string): Promise<StatusResult> {
+ const config = readOpenClawConfig(configPath);
+ const existing = getExistingPluginConfig(config);
+ const slotActive = isContextEngineSlotActive(configPath);
+
+ if (!existing) {
+ return { configured: false, slotActive };
+ }
+
+ const baseUrl = String(existing.baseUrl ?? DEFAULT_REMOTE_URL);
+ const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;
+ const health = await checkServiceHealth(baseUrl, apiKey);
+ const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;
+
+ const agentPrefix = existing.agent_prefix ?? existing.agentId;
+ return {
+ configured: true,
+ config: {
+ mode: String(existing.mode ?? "remote"),
+ baseUrl,
+ hasApiKey: !!existing.apiKey,
+ ...(agentPrefix ? { agent_prefix: String(agentPrefix) } : {}),
+ hasAccountId: !!existing.accountId,
+ hasUserId: !!existing.userId,
+ },
+ health,
+ keyProbe,
+ slotActive,
+ };
+}
+
+function printSlotResult(zh: boolean, slot: SlotActivationResult): void {
+ if (slot.activated && slot.replaced) {
+ console.log(` ⚠ ${tr(zh,
+ `Replaced context-engine slot: ${slot.previousOwner} → openviking`,
+ `已替换 context-engine 插槽: ${slot.previousOwner} → openviking`,
+ )}`);
+ } else if (slot.activated) {
+ console.log(` ✓ ${tr(zh, "Activated context-engine slot: openviking", "已激活 context-engine 插槽: openviking")}`);
+ } else if (slot.previousOwner && slot.previousOwner !== "openviking") {
+ console.log(` ⚠ ${tr(zh,
+ `Context-engine slot is owned by "${slot.previousOwner}". Run: openclaw config set plugins.slots.contextEngine openviking`,
+ `context-engine 插槽当前由 "${slot.previousOwner}" 占用。运行: openclaw config set plugins.slots.contextEngine openviking`,
+ )}`);
+ }
+}
+
+function printKeyProbeWarning(zh: boolean, probe: ApiKeyProbeResult): void {
+ if (probe.keyType === "root_key") {
+ console.log(` ⚠ ${tr(zh,
+ "Root API key detected. accountId and userId are required for this key type.",
+ "检测到 Root API Key,此类型密钥需要提供 accountId 和 userId。",
+ )}`);
+ if (probe.needsAccountId) {
+ console.log(` ${tr(zh,
+ "→ Missing: accountId (use --account-id or set in config)",
+ "→ 缺少: accountId(使用 --account-id 或在配置中设置)",
+ )}`);
+ }
+ if (probe.needsUserId) {
+ console.log(` ${tr(zh,
+ "→ Missing: userId (use --user-id or set in config)",
+ "→ 缺少: userId(使用 --user-id 或在配置中设置)",
+ )}`);
+ }
+ }
+}
+
+function printStatus(zh: boolean, result: StatusResult): void {
+ console.log("");
+ console.log(`🦣 ${tr(zh, "OpenViking Plugin Status", "OpenViking 插件状态")}`);
+ console.log("");
+
+ if (!result.configured) {
+ console.log(` ${tr(zh, "Status: Not configured", "状态: 未配置")}`);
+ console.log(` ${tr(zh, "Run `openclaw openviking setup` to configure.", "运行 `openclaw openviking setup` 进行配置。")}`);
+ console.log("");
+ return;
+ }
+
+ console.log(` ${tr(zh, "Status: Configured", "状态: 已配置")}`);
+ if (result.config) {
+ console.log(` mode: ${result.config.mode}`);
+ console.log(` baseUrl: ${result.config.baseUrl}`);
+ console.log(` apiKey: ${result.config.hasApiKey ? "set" : "not set"}`);
+ if (result.config.agent_prefix) console.log(` agent_prefix: ${result.config.agent_prefix}`);
+ console.log(` accountId: ${result.config.hasAccountId ? "set" : "not set"}`);
+ console.log(` userId: ${result.config.hasUserId ? "set" : "not set"}`);
+ }
+ console.log(` slot: ${result.slotActive ? "active" : "inactive"}`);
+ console.log("");
+
+ if (result.health?.ok) {
+ const ver = result.health.version ? ` (version: ${result.health.version})` : "";
+ console.log(` ✓ ${tr(zh, `Server reachable${ver}`, `服务器可达${ver}`)}`);
+ printCompatibilityWarning(zh, result.health);
+ } else if (result.health) {
+ console.log(` ✗ ${tr(zh, `Server unreachable: ${result.health.error}`, `服务器不可达: ${result.health.error}`)}`);
+ }
+
+ if (result.keyProbe) {
+ printKeyProbeWarning(zh, result.keyProbe);
+ }
+ console.log("");
+}
+
async function setupRemote(
zh: boolean,
configPath: string,
@@ -320,16 +908,35 @@ async function setupRemote(
const baseUrl = await q(tr(zh, "OpenViking server URL", "OpenViking 服务器地址"), defaultUrl);
const apiKey = await q(tr(zh, "API Key (optional)", "API Key(可选)"), defaultApiKey);
+
+ let accountId = existing?.accountId ? String(existing.accountId) : "";
+ let userId = existing?.userId ? String(existing.userId) : "";
+
+ if (apiKey) {
+ console.log(tr(zh, " Detecting API key type...", " 正在检测 API Key 类型..."));
+ const probe = await probeApiKeyType(baseUrl, apiKey);
+ if (probe.keyType === "root_key") {
+ console.log(tr(zh,
+ " ⚠ Root API key detected. accountId and userId are required.",
+ " ⚠ 检测到 Root API Key,需要提供 accountId 和 userId。",
+ ));
+ accountId = await q(tr(zh, "Account ID (required for root key)", "Account ID(root key 必填)"), accountId);
+ userId = await q(tr(zh, "User ID (required for root key)", "User ID(root key 必填)"), userId);
+ } else if (probe.keyType === "user_key") {
+ console.log(tr(zh, " ✓ User key verified", " ✓ User key 已验证"));
+ }
+ }
+
const agentPrefix = await askAgentPrefix(zh, q, defaultAgentPrefix);
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}`)}`);
+ printCompatibilityWarning(zh, health);
} else {
console.log(` ✗ ${tr(zh, `Connection failed: ${health.error}`, `连接失败: ${health.error}`)}`);
console.log("");
@@ -340,7 +947,6 @@ async function setupRemote(
}
console.log("");
- // Write config
const pluginCfg: Record<string, unknown> = {
...(existing ?? {}),
mode: "remote",
@@ -350,16 +956,25 @@ async function setupRemote(
else delete pluginCfg.apiKey;
if (agentPrefix) pluginCfg.agent_prefix = agentPrefix;
else delete pluginCfg.agent_prefix;
+ if (accountId) pluginCfg.accountId = accountId;
+ else delete pluginCfg.accountId;
+ if (userId) pluginCfg.userId = userId;
+ else delete pluginCfg.userId;
delete pluginCfg.configPath;
delete pluginCfg.port;
writeConfig(configPath, pluginCfg);
+ const slotResult = activateContextEngineSlot(configPath);
+
console.log("");
console.log(` ${tr(zh, "mode:", "模式:")} remote`);
console.log(` baseUrl: ${baseUrl}`);
if (apiKey) console.log(` apiKey: ${maskKey(apiKey)}`);
if (agentPrefix) console.log(` agent_prefix: ${agentPrefix}`);
+ if (accountId) console.log(` accountId: ${accountId}`);
+ if (userId) console.log(` userId: ${userId}`);
+ printSlotResult(zh, slotResult);
console.log("");
console.log(tr(zh,
"Run `openclaw gateway --force` to activate the plugin.",
@@ -369,7 +984,19 @@ async function setupRemote(
}
export const __test__ = {
- resolveAbsoluteCommand,
isLegacyLocalMode,
isValidAgentPrefixInput,
+ activateContextEngineSlot,
+ isContextEngineSlotActive,
+ getStatus,
+ setupNonInteractive,
+ checkVersionCompatibility,
+ parseVersionTuple,
+ compareVersions,
+ probeApiKeyType,
+ ensureInstallRecord,
+ findPluginPackageRoot,
+ readCompatRangeFromManifest,
+ readPluginVersion,
+ setExitCodeOnFailure,
};
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index fc9c439d4..08f50c336 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -199,7 +199,7 @@ export const memoryOpenVikingConfigSchema = {
const mode = "remote" as const;
const rawBaseUrl = typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl();
const resolvedBaseUrl = resolveEnvVars(rawBaseUrl).replace(/\/+$/, "");
- const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : process.env.OPENVIKING_API_KEY;
+ const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : getEnv("OPENVIKING_API_KEY");
const captureMode = cfg.captureMode;
if (
typeof captureMode !== "undefined" &&
@@ -212,15 +212,15 @@ export const memoryOpenVikingConfigSchema = {
const accountId =
typeof cfg.accountId === "string" && cfg.accountId.trim()
? cfg.accountId.trim()
- : (process.env.OPENVIKING_ACCOUNT_ID?.trim() || "");
+ : (getEnv("OPENVIKING_ACCOUNT_ID")?.trim() || "");
const userId =
typeof cfg.userId === "string" && cfg.userId.trim()
? cfg.userId.trim()
- : (process.env.OPENVIKING_USER_ID?.trim() || "");
+ : (getEnv("OPENVIKING_USER_ID")?.trim() || "");
const hasExplicitAgentScopeMode =
- typeof cfg.agentScopeMode === "string" || process.env.OPENVIKING_AGENT_SCOPE_MODE !== undefined;
- const rawAgentScope = cfg.agentScopeMode ?? process.env.OPENVIKING_AGENT_SCOPE_MODE;
+ typeof cfg.agentScopeMode === "string" || getEnv("OPENVIKING_AGENT_SCOPE_MODE") !== undefined;
+ const rawAgentScope = cfg.agentScopeMode ?? getEnv("OPENVIKING_AGENT_SCOPE_MODE");
const agentScopeMode =
rawAgentScope === "user_agent" ? "user_agent" as const : "agent" as const;
const explicitIsolateUserScopeByAgent =
@@ -233,12 +233,12 @@ export const memoryOpenVikingConfigSchema = {
: undefined;
const envIsolateUserScopeByAgent =
explicitIsolateUserScopeByAgent === undefined &&
- process.env.OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT !== undefined
+ getEnv("OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT") !== undefined
? envFlag("OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT")
: undefined;
const envIsolateAgentScopeByUser =
explicitIsolateAgentScopeByUser === undefined &&
- process.env.OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER !== undefined
+ getEnv("OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER") !== undefined
? envFlag("OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER")
: undefined;
const isolateUserScopeByAgent =
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 2aa43cc07..3069bdd91 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -517,7 +517,31 @@ const contextEnginePlugin = {
api.pluginConfig && typeof api.pluginConfig === "object" && !Array.isArray(api.pluginConfig)
? (api.pluginConfig as Record<string, unknown>)
: {};
- const cfg = memoryOpenVikingConfigSchema.parse(api.pluginConfig);
+
+ if (rawCfg.mode && rawCfg.mode !== "remote") {
+ api.logger.warn(
+ `openviking: legacy local mode detected (mode="${String(rawCfg.mode)}"). ` +
+ "Migrating to remote mode. Please run 'openclaw openviking setup' to configure the remote server.",
+ );
+ rawCfg.mode = "remote";
+ delete rawCfg.localBinaryPath;
+ delete rawCfg.localDataDir;
+ delete rawCfg.localPort;
+ delete rawCfg.autoStart;
+ }
+
+ let cfg: ReturnType<typeof memoryOpenVikingConfigSchema.parse>;
+ try {
+ cfg = memoryOpenVikingConfigSchema.parse(rawCfg);
+ } catch (parseErr) {
+ api.logger.warn(
+ `openviking: config parse failed (${parseErr instanceof Error ? parseErr.message : String(parseErr)}). ` +
+ "Plugin loaded in setup-only mode. Run: openclaw openviking setup",
+ );
+ registerSetupCli(api);
+ return;
+ }
+
const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);
const rawAgentId = rawCfg.agent_prefix;
if (cfg.logFindRequests) {
diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.json
index 746b37615..180e4be26 100644
--- a/examples/openclaw-plugin/install-manifest.json
+++ b/examples/openclaw-plugin/install-manifest.json
@@ -1,6 +1,6 @@
{
"manifestVersion": "1.0",
- "pluginVersion": "2026.4.33",
+ "pluginVersion": "2026.5.8",
"plugin": {
"id": "openviking",
"kind": "context-engine",
@@ -10,10 +10,6 @@
"required": [
"index.ts",
"config.ts",
- "package.json",
- "openclaw.plugin.json"
- ],
- "optional": [
"context-engine.ts",
"auto-recall.ts",
"client.ts",
@@ -25,16 +21,27 @@
"runtime-utils.ts",
"commands/setup.ts",
"tsconfig.json",
+ "tsconfig.build.json",
+ "package.json",
+ "openclaw.plugin.json"
+ ],
+ "optional": [
"package-lock.json",
- ".gitignore"
+ ".gitignore",
+ "skills/install-openviking-memory/SKILL.md",
+ "INSTALL-AGENT.md"
]
},
"npm": {
"install": true,
- "omitDev": true
+ "omitDev": true,
+ "build": true,
+ "buildMinOpenclawVersion": "2026.5.3",
+ "buildScript": "build",
+ "pruneAfterBuild": true
},
"compatibility": {
- "minOpenclawVersion": "2026.4.24",
+ "minOpenclawVersion": "2026.4.8",
"minOpenvikingVersion": "0.2.9"
}
}
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index dece4db23..c5f32807e 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -21,6 +21,53 @@
"ov_archive_expand"
]
},
+ "commandAliases": [
+ {
+ "name": "setup",
+ "kind": "runtime-slash",
+ "cliCommand": "openviking"
+ },
+ {
+ "name": "status",
+ "kind": "runtime-slash",
+ "cliCommand": "openviking"
+ }
+ ],
+ "providerAuthEnvVars": {
+ "openviking": [
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_BASE_URL"
+ ]
+ },
+ "skills": [
+ "./skills/install-openviking-memory"
+ ],
+ "setup": {
+ "providers": [
+ {
+ "id": "openviking",
+ "authMethods": [
+ "api_key",
+ "trusted"
+ ],
+ "envVars": [
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_BASE_URL"
+ ],
+ "cliFlags": {
+ "api_key": [
+ "--base-url",
+ "--api-key"
+ ],
+ "trusted": [
+ "--base-url"
+ ]
+ }
+ }
+ ],
+ "requiresRuntime": true,
+ "cliCommand": "openclaw openviking setup"
+ },
"uiHints": {
"baseUrl": {
"label": "OpenViking Base URL",
@@ -169,6 +216,10 @@
"type": "object",
"additionalProperties": false,
"properties": {
+ "mode": {
+ "type": "string",
+ "description": "Legacy field kept for backward compatibility. Only 'remote' is supported."
+ },
"baseUrl": {
"type": "string"
},
diff --git a/examples/openclaw-plugin/package-lock.json b/examples/openclaw-plugin/package-lock.json
index 421ffa5c7..da80620c9 100644
--- a/examples/openclaw-plugin/package-lock.json
+++ b/examples/openclaw-plugin/package-lock.json
@@ -1,22 +1,24 @@
{
"name": "@openclaw/openviking",
- "version": "2026.4.33",
+ "version": "2026.5.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openclaw/openviking",
- "version": "2026.4.33",
+ "version": "2026.5.8",
+ "license": "MIT",
"dependencies": {
"@sinclair/typebox": "0.34.48",
"fflate": "^0.8.2"
},
"devDependencies": {
"@types/node": "^25.3.5",
+ "typescript": "^5.8.0",
"vitest": "^4.1.0"
},
"engines": {
- "openclaw": ">=2026.4.24"
+ "openclaw": ">=2026.4.8"
}
},
"node_modules/@emnapi/core": {
@@ -1127,6 +1129,20 @@
"license": "0BSD",
"optional": true
},
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.18.2.tgz",
diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.json
index e01691ec7..74c6fadc6 100644
--- a/examples/openclaw-plugin/package.json
+++ b/examples/openclaw-plugin/package.json
@@ -1,42 +1,75 @@
{
"name": "@openclaw/openviking",
- "version": "2026.4.33",
+ "version": "2026.5.8",
"displayName": "OpenViking",
- "description": "OpenClaw context-engine plugin for memory management — powered by OpenViking",
+ "description": "OpenClaw context-engine plugin — OpenViking AI memory, long-term memory, knowledge base, semantic search, RAG, context engine. 长期记忆 · 知识库 · 语义检索 · 上下文引擎",
"type": "module",
+ "keywords": [
+ "openclaw",
+ "openviking",
+ "plugin",
+ "context-engine",
+ "memory",
+ "remote-memory",
+ "RAG",
+ "semantic-retrieval",
+ "context-database",
+ "long-term-memory",
+ "auto-recall",
+ "auto-capture"
+ ],
"files": [
+ "dist/",
"*.ts",
"commands/setup.ts",
"!vitest.config.ts",
+ "install-manifest.json",
"openclaw.plugin.json",
- "package.json"
+ "package.json",
+ "README.md",
+ "INSTALL.md",
+ "INSTALL-ZH.md",
+ "INSTALL-AGENT.md",
+ "skills/"
],
"scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "prepack": "npm run build",
"test": "vitest run",
+ "typecheck": "tsc -p tsconfig.json",
"test:watch": "vitest"
},
"engines": {
- "openclaw": ">=2026.4.24"
+ "openclaw": ">=2026.4.8"
},
"dependencies": {
"@sinclair/typebox": "0.34.48",
"fflate": "^0.8.2"
},
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/volcengine/OpenViking"
+ },
+ "homepage": "https://github.com/volcengine/OpenViking/tree/main/examples/openclaw-plugin",
+ "license": "MIT",
+ "author": "OpenViking Contributors",
"openclaw": {
"extensions": [
"./index.ts"
],
+ "setupEntry": "./commands/setup.ts",
"compat": {
- "pluginApi": ">=2026.4.24",
- "minGatewayVersion": "2026.4.24"
+ "pluginApi": ">=2026.4.8",
+ "minGatewayVersion": "2026.4.8"
},
"build": {
- "openclawVersion": "2026.4.24",
- "pluginSdkVersion": "2026.4.24"
+ "openclawVersion": "2026.4.8",
+ "pluginSdkVersion": "2026.4.8"
}
},
"devDependencies": {
"@types/node": "^25.3.5",
+ "typescript": "^5.8.0",
"vitest": "^4.1.0"
}
}
diff --git a/examples/openclaw-plugin/process-manager.ts b/examples/openclaw-plugin/process-manager.ts
index ec09dac76..8bd5aac0d 100644
--- a/examples/openclaw-plugin/process-manager.ts
+++ b/examples/openclaw-plugin/process-manager.ts
@@ -1,5 +1,12 @@
import { Socket } from "node:net";
-import { launchProcess } from "./runtime-utils.js";
+
+type ChildLike = {
+ killed?: boolean;
+ exitCode?: number | null;
+ signalCode?: string | null;
+ off?: (event: string, listener: (...args: any[]) => void) => void;
+ once: (event: string, listener: (...args: any[]) => void) => void;
+};
export function waitForHealth(baseUrl: string, timeoutMs: number, intervalMs: number): Promise<void> {
const deadline = Date.now() + timeoutMs;
@@ -28,7 +35,7 @@ export function waitForHealthOrExit(
baseUrl: string,
timeoutMs: number,
intervalMs: number,
- child: ReturnType<typeof launchProcess>,
+ child: ChildLike,
): Promise<void> {
const exited =
child.killed || child.exitCode !== null || child.signalCode !== null;
diff --git a/examples/openclaw-plugin/runtime-utils.ts b/examples/openclaw-plugin/runtime-utils.ts
index 953e7cb1e..630b8b110 100644
--- a/examples/openclaw-plugin/runtime-utils.ts
+++ b/examples/openclaw-plugin/runtime-utils.ts
@@ -1,25 +1,3 @@
-import type { ChildProcess, ExecSyncOptionsWithStringEncoding, 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: ExecSyncOptionsWithStringEncoding,
-): string {
- return _execSync(command, options);
-}
-
const _env = globalThis["process"];
export function sysEnv(): NodeJS.ProcessEnv {
return _env.env;
diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.js
index 99b9f83bc..a75ee2212 100755
--- a/examples/openclaw-plugin/setup-helper/install.js
+++ b/examples/openclaw-plugin/setup-helper/install.js
@@ -3,18 +3,18 @@
* OpenClaw OpenViking plugin installer (remote OpenViking server — does not install Python/OpenViking server).
*
* One-liner (after npm publish; use package name + bin name):
- * npx -p openclaw-openviking-setup-helper ov-install [ -y ] [ --zh ] [ --workdir PATH ]
+ * npx -p openclaw-openviking-setup-helper ov-install [ --base-url URL ] [ --api-key KEY ] [ --zh ] [ --workdir PATH ]
* Or install globally then run:
* npm i -g openclaw-openviking-setup-helper
* ov-install
* openclaw-openviking-install
*
* Direct run:
- * node install.js [ -y | --yes ] [ --zh ] [ --workdir PATH ] [ --upgrade-plugin ]
+ * node install.js [ --base-url URL ] [ --api-key KEY ] [ --zh ] [ --workdir PATH ] [ --upgrade-plugin ]
* [ --plugin-version=TAG ]
*
* Environment variables:
- * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_INSTALL_YES, SKIP_OPENCLAW
+ * REPO, PLUGIN_VERSION (or BRANCH), OPENVIKING_BASE_URL, OPENVIKING_API_KEY, SKIP_OPENCLAW
* NPM_REGISTRY
*/
@@ -33,6 +33,8 @@ const pluginVersionEnv = (process.env.PLUGIN_VERSION || process.env.BRANCH || ""
let PLUGIN_VERSION = pluginVersionEnv;
let pluginVersionExplicit = Boolean(pluginVersionEnv);
const NPM_REGISTRY = process.env.NPM_REGISTRY || "https://registry.npmmirror.com";
+const DEFAULT_NPM_BUILD_MIN_OPENCLAW_VERSION = "2026.5.3";
+const OPENCLAW_SHORT_VERSION_YEAR = 2026;
const IS_WIN = process.platform === "win32";
const HOME = process.env.HOME || process.env.USERPROFILE || "";
@@ -48,8 +50,8 @@ const FALLBACK_LEGACY = {
kind: "memory",
slot: "memory",
minOpenclawVersion: "2026.3.7",
- required: ["index.ts", "config.ts", "openclaw.plugin.json", "package.json"],
- optional: ["package-lock.json", ".gitignore"],
+ required: ["index.ts", "config.ts", "client.ts", "openclaw.plugin.json", "package.json"],
+ optional: ["package-lock.json", ".gitignore", "memory-ranking.ts", "text-utils.ts", "process-manager.ts", "tsconfig.json"],
};
// Must match examples/openclaw-plugin/install-manifest.json (npm only installs package deps, not these .ts files).
@@ -58,7 +60,7 @@ const FALLBACK_CURRENT = {
id: "openviking",
kind: "context-engine",
slot: "contextEngine",
- minOpenclawVersion: "2026.4.24",
+ minOpenclawVersion: "2026.4.8",
required: ["index.ts", "config.ts", "package.json", "openclaw.plugin.json"],
optional: [
"context-engine.ts",
@@ -90,21 +92,31 @@ let resolvedPluginSlot = "";
let resolvedFilesRequired = [];
let resolvedFilesOptional = [];
let resolvedNpmOmitDev = true;
+let resolvedNpmBuild = false;
+let resolvedNpmBuildMinOpenclawVersion = DEFAULT_NPM_BUILD_MIN_OPENCLAW_VERSION;
+let resolvedNpmBuildScript = "build";
+let resolvedNpmPruneAfterBuild = true;
let resolvedMinOpenclawVersion = "";
let resolvedMinOpenvikingVersion = "";
let resolvedPluginReleaseId = "";
+let detectedOpenClawVersion = "";
-let installYes = process.env.OPENVIKING_INSTALL_YES === "1";
+let nonInteractive = false;
let langZh = false;
let workdirExplicit = false;
let upgradePluginOnly = false;
let rollbackLastUpgrade = false;
let showCurrentVersion = false;
+let uninstallPlugin = false;
const selectedMode = "remote";
-let remoteBaseUrl = "http://127.0.0.1:1933";
-let remoteApiKey = "";
-let remoteAgentPrefix = "";
+const baseUrlFromEnv = !!process.env.OPENVIKING_BASE_URL;
+let remoteBaseUrl = (process.env.OPENVIKING_BASE_URL || "http://127.0.0.1:1933").trim();
+let remoteApiKey = (process.env.OPENVIKING_API_KEY || "").trim();
+let remoteAgentPrefix = (process.env.OPENVIKING_AGENT_PREFIX || "").trim();
+let remoteAccountId = (process.env.OPENVIKING_ACCOUNT_ID || "").trim();
+let remoteUserId = (process.env.OPENVIKING_USER_ID || "").trim();
+let baseUrlExplicit = baseUrlFromEnv;
let upgradeRuntimeConfig = null;
let installedUpgradeState = null;
let upgradeAudit = null;
@@ -113,8 +125,11 @@ const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "-y" || arg === "--yes") {
- installYes = true;
- continue;
+ err(tr(
+ "-y/--yes has been removed. Use --base-url <URL> [--api-key <KEY>] for non-interactive mode.",
+ "-y/--yes 已移除。使用 --base-url <URL> [--api-key <KEY>] 进入非交互模式。",
+ ));
+ process.exit(1);
}
if (arg === "--zh") {
langZh = true;
@@ -132,6 +147,10 @@ for (let i = 0; i < argv.length; i++) {
rollbackLastUpgrade = true;
continue;
}
+ if (arg === "--uninstall" || arg === "--remove") {
+ uninstallPlugin = true;
+ continue;
+ }
if (arg === "--workdir") {
const workdir = argv[i + 1]?.trim();
if (!workdir) {
@@ -178,12 +197,71 @@ for (let i = 0; i < argv.length; i++) {
i += 1;
continue;
}
+ if (arg === "--base-url") {
+ const val = argv[i + 1]?.trim();
+ if (!val) { console.error("--base-url requires a URL"); process.exit(1); }
+ remoteBaseUrl = val;
+ baseUrlExplicit = true;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--base-url=")) {
+ remoteBaseUrl = arg.slice("--base-url=".length).trim();
+ baseUrlExplicit = true;
+ continue;
+ }
+ if (arg === "--api-key") {
+ const val = argv[i + 1]?.trim();
+ if (!val) { console.error("--api-key requires a value"); process.exit(1); }
+ remoteApiKey = val;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--api-key=")) {
+ remoteApiKey = arg.slice("--api-key=".length).trim();
+ continue;
+ }
+ if (arg === "--agent-prefix") {
+ const val = argv[i + 1]?.trim();
+ if (!val) { console.error("--agent-prefix requires a value"); process.exit(1); }
+ remoteAgentPrefix = val;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--agent-prefix=")) {
+ remoteAgentPrefix = arg.slice("--agent-prefix=".length).trim();
+ continue;
+ }
+ if (arg === "--account-id") {
+ const val = argv[i + 1]?.trim();
+ if (!val) { console.error("--account-id requires a value"); process.exit(1); }
+ remoteAccountId = val;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--account-id=")) {
+ remoteAccountId = arg.slice("--account-id=".length).trim();
+ continue;
+ }
+ if (arg === "--user-id") {
+ const val = argv[i + 1]?.trim();
+ if (!val) { console.error("--user-id requires a value"); process.exit(1); }
+ remoteUserId = val;
+ i += 1;
+ continue;
+ }
+ if (arg.startsWith("--user-id=")) {
+ remoteUserId = arg.slice("--user-id=".length).trim();
+ continue;
+ }
if (arg === "-h" || arg === "--help") {
printHelp();
process.exit(0);
}
}
+nonInteractive = baseUrlExplicit;
+
function setOpenClawDir(dir) {
OPENCLAW_DIR = dir;
}
@@ -200,7 +278,12 @@ function printHelp() {
console.log(" Upgrade only the plugin to the requested --plugin-version; keeps existing plugin runtime config");
console.log(" --rollback, --rollback-last-upgrade");
console.log(" Roll back the last plugin upgrade using the saved audit/backup files");
- console.log(" -y, --yes Non-interactive (use defaults)");
+ console.log(" --uninstall, --remove Uninstall OpenViking plugin from OpenClaw (backup config, remove plugin entries)");
+ console.log(" --base-url=URL OpenViking server URL (default: $OPENVIKING_BASE_URL or http://127.0.0.1:1933)");
+ console.log(" --api-key=KEY OpenViking API key (default: $OPENVIKING_API_KEY)");
+ console.log(" --agent-prefix=PREFIX Agent routing prefix (default: $OPENVIKING_AGENT_PREFIX)");
+ console.log(" --account-id=ID Account ID for root API key (default: $OPENVIKING_ACCOUNT_ID)");
+ console.log(" --user-id=ID User ID for root API key (default: $OPENVIKING_USER_ID)");
console.log(" --zh Chinese prompts");
console.log(" -h, --help This help");
console.log("");
@@ -336,6 +419,27 @@ function isValidAgentPrefixInput(value) {
return !trimmed || /^[a-zA-Z0-9_-]+$/.test(trimmed);
}
+function parseJsonObjectFromOutput(output) {
+ const text = String(output || "").trim();
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ // OpenClaw may print plugin registration logs before --json output.
+ }
+ for (let index = text.lastIndexOf("{"); index >= 0; index = text.lastIndexOf("{", index - 1)) {
+ try {
+ const parsed = JSON.parse(text.slice(index).trim());
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return parsed;
+ }
+ } catch {
+ // Keep scanning earlier braces until the outer JSON object is found.
+ }
+ }
+ return null;
+}
+
async function questionAgentPrefix(defaultValue = "") {
while (true) {
const answer = (await question(
@@ -375,7 +479,7 @@ async function selectWorkdir() {
setOpenClawDir(instances[0]);
return;
}
- if (installYes) return;
+ if (nonInteractive) return;
console.log("");
bold(tr("Found multiple OpenClaw instances:", "发现多个 OpenClaw 实例:"));
@@ -395,7 +499,7 @@ async function selectWorkdir() {
}
async function collectRemoteConfig() {
- if (installYes) return;
+ if (nonInteractive) return;
remoteBaseUrl = await question(tr("OpenViking server URL", "OpenViking 服务器地址"), remoteBaseUrl);
remoteApiKey = await question(tr("API Key (optional)", "API Key(可选)"), remoteApiKey);
remoteAgentPrefix = await questionAgentPrefix(remoteAgentPrefix);
@@ -440,6 +544,51 @@ function versionGte(v1, v2) {
return a3 >= b3;
}
+function parseOpenClawPolicyVersion(value) {
+ const parts = String(value || "")
+ .match(/\d+/g)
+ ?.map((part) => Number.parseInt(part, 10) || 0) || [];
+ if (parts.length === 0) return [0, 0, 0];
+ if (parts[0] >= 2000) {
+ return [parts[0], parts[1] || 0, parts[2] || 0];
+ }
+ return [OPENCLAW_SHORT_VERSION_YEAR, parts[0] || 0, parts[1] || 0];
+}
+
+function openClawPolicyVersionGte(v1, v2) {
+ const a = parseOpenClawPolicyVersion(v1);
+ const b = parseOpenClawPolicyVersion(v2);
+ for (let i = 0; i < 3; i++) {
+ if (a[i] !== b[i]) return a[i] > b[i];
+ }
+ return true;
+}
+
+function applyOpenClawBuildPolicy(openClawVersion) {
+ if (!resolvedNpmBuild || !resolvedNpmBuildMinOpenclawVersion) {
+ return;
+ }
+ if (!openClawVersion || openClawVersion === "0.0.0") {
+ warn(tr(
+ "Could not determine OpenClaw version; keeping plugin source build enabled.",
+ "无法确定 OpenClaw 版本,保持插件源码构建开启。",
+ ));
+ return;
+ }
+ if (openClawPolicyVersionGte(openClawVersion, resolvedNpmBuildMinOpenclawVersion)) {
+ info(tr(
+ `OpenClaw ${openClawVersion} requires plugin source build (>= ${resolvedNpmBuildMinOpenclawVersion})`,
+ `OpenClaw ${openClawVersion} 需要插件源码构建(>= ${resolvedNpmBuildMinOpenclawVersion})`,
+ ));
+ return;
+ }
+ resolvedNpmBuild = false;
+ info(tr(
+ `OpenClaw ${openClawVersion} is below ${resolvedNpmBuildMinOpenclawVersion}; skipping plugin source build`,
+ `OpenClaw ${openClawVersion} 低于 ${resolvedNpmBuildMinOpenclawVersion},跳过插件源码构建`,
+ ));
+}
+
function isSemverLike(value) {
return /^v?\d+(\.\d+){1,2}$/.test(value);
}
@@ -457,16 +606,29 @@ if (upgradePluginOnly && rollbackLastUpgrade) {
process.exit(1);
}
+if (uninstallPlugin && (upgradePluginOnly || rollbackLastUpgrade)) {
+ console.error("--uninstall cannot be used with --upgrade-plugin or --rollback");
+ process.exit(1);
+}
+
// Detect OpenClaw version
async function detectOpenClawVersion() {
+ if (detectedOpenClawVersion) {
+ return detectedOpenClawVersion;
+ }
try {
const result = await runCapture("openclaw", ["--version"], { shell: IS_WIN });
- if (result.code === 0 && result.out) {
- const match = result.out.match(/\d+\.\d+(\.\d+)?/);
- if (match) return match[0];
+ const output = `${result.out || ""}\n${result.err || ""}`;
+ if (result.code === 0 && output) {
+ const match = output.match(/\d+\.\d+(\.\d+)?/);
+ if (match) {
+ detectedOpenClawVersion = match[0];
+ return detectedOpenClawVersion;
+ }
}
} catch {}
- return "0.0.0";
+ detectedOpenClawVersion = "0.0.0";
+ return detectedOpenClawVersion;
}
// Try to fetch a URL, return response text or null
@@ -615,6 +777,12 @@ async function resolvePluginConfig() {
info(tr(`Resolving plugin configuration for version: ${PLUGIN_VERSION}`, `正在解析插件配置,版本: ${PLUGIN_VERSION}`));
+ resolvedNpmOmitDev = true;
+ resolvedNpmBuild = false;
+ resolvedNpmBuildMinOpenclawVersion = DEFAULT_NPM_BUILD_MIN_OPENCLAW_VERSION;
+ resolvedNpmBuildScript = "build";
+ resolvedNpmPruneAfterBuild = true;
+
let pluginDir = "";
let manifestData = null;
@@ -656,7 +824,19 @@ async function resolvePluginConfig() {
resolvedMinOpenclawVersion = manifestData.compatibility?.minOpenclawVersion || "";
resolvedMinOpenvikingVersion = manifestData.compatibility?.minOpenvikingVersion || "";
resolvedPluginReleaseId = manifestData.pluginVersion || manifestData.release?.id || "";
- resolvedNpmOmitDev = manifestData.npm?.omitDev !== false;
+ const npmConfig = manifestData.npm && typeof manifestData.npm === "object"
+ ? manifestData.npm
+ : {};
+ resolvedNpmOmitDev = npmConfig.omitDev !== false;
+ resolvedNpmBuild = npmConfig.build === true || npmConfig.buildFromSource === true;
+ resolvedNpmBuildMinOpenclawVersion =
+ typeof npmConfig.buildMinOpenclawVersion === "string" && npmConfig.buildMinOpenclawVersion.trim()
+ ? npmConfig.buildMinOpenclawVersion.trim()
+ : DEFAULT_NPM_BUILD_MIN_OPENCLAW_VERSION;
+ resolvedNpmBuildScript = typeof npmConfig.buildScript === "string" && npmConfig.buildScript.trim()
+ ? npmConfig.buildScript.trim()
+ : "build";
+ resolvedNpmPruneAfterBuild = npmConfig.pruneAfterBuild !== false;
resolvedFilesRequired = manifestData.files?.required || [];
resolvedFilesOptional = manifestData.files?.optional || [];
} else {
@@ -691,6 +871,10 @@ async function resolvePluginConfig() {
resolvedFilesRequired = fallback.required;
resolvedFilesOptional = fallback.optional;
resolvedNpmOmitDev = true;
+ resolvedNpmBuild = false;
+ resolvedNpmBuildMinOpenclawVersion = DEFAULT_NPM_BUILD_MIN_OPENCLAW_VERSION;
+ resolvedNpmBuildScript = "build";
+ resolvedNpmPruneAfterBuild = true;
// If no compatVer from package.json, try main branch manifest
if (!compatVer && PLUGIN_VERSION !== "main") {
@@ -725,6 +909,7 @@ async function checkOpenClawCompatibility() {
const ocVersion = await detectOpenClawVersion();
info(tr(`Detected OpenClaw version: ${ocVersion}`, `检测到 OpenClaw 版本: ${ocVersion}`));
+ applyOpenClawBuildPolicy(ocVersion);
// If no minimum version required, pass
if (!resolvedMinOpenclawVersion) {
@@ -737,7 +922,7 @@ async function checkOpenClawCompatibility() {
}
// Check compatibility
- if (!versionGte(ocVersion, resolvedMinOpenclawVersion)) {
+ if (!openClawPolicyVersionGte(ocVersion, resolvedMinOpenclawVersion)) {
err(tr(
`OpenClaw ${ocVersion} does not support this plugin (requires >= ${resolvedMinOpenclawVersion})`,
`OpenClaw ${ocVersion} 不支持此插件(需要 >= ${resolvedMinOpenclawVersion})`
@@ -900,8 +1085,9 @@ function extractRuntimeConfigFromPluginEntry(entryConfig) {
if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) {
runtime.apiKey = entryConfig.apiKey;
}
- if (typeof entryConfig.agent_prefix === "string" && entryConfig.agent_prefix.trim()) {
- runtime.agent_prefix = entryConfig.agent_prefix.trim();
+ const prefix = entryConfig.agent_prefix || entryConfig.agentId;
+ if (typeof prefix === "string" && prefix.trim()) {
+ runtime.agent_prefix = prefix.trim();
}
return runtime;
}
@@ -1295,6 +1481,103 @@ async function downloadPluginFile(destDir, fileName, url, required, index, total
process.exit(1);
}
+function runtimeOutputCandidatesForEntry(entry) {
+ const normalized = String(entry || "").replace(/\\/g, "/").replace(/^\.\//, "");
+ if (!normalized.endsWith(".ts")) {
+ return [];
+ }
+ const withoutExt = normalized.slice(0, -3);
+ return [
+ `dist/${withoutExt}.js`,
+ `dist/${withoutExt}.mjs`,
+ `dist/${withoutExt}.cjs`,
+ `${withoutExt}.js`,
+ `${withoutExt}.mjs`,
+ `${withoutExt}.cjs`,
+ ];
+}
+
+async function assertBuiltRuntimeOutputs(destDir) {
+ let pkg = null;
+ try {
+ pkg = JSON.parse(await readFile(join(destDir, "package.json"), "utf8"));
+ } catch {
+ return;
+ }
+
+ const entries = [];
+ const extensions = pkg?.openclaw?.extensions;
+ if (Array.isArray(extensions)) {
+ for (const entry of extensions) {
+ if (typeof entry === "string") entries.push(entry);
+ }
+ }
+ if (typeof pkg?.openclaw?.setupEntry === "string") {
+ entries.push(pkg.openclaw.setupEntry);
+ }
+
+ const missing = [];
+ for (const entry of entries) {
+ const candidates = runtimeOutputCandidatesForEntry(entry);
+ if (candidates.length === 0) continue;
+ const found = candidates.some((candidate) => existsSync(join(destDir, ...candidate.split("/"))));
+ if (!found) {
+ missing.push(`${entry} (expected one of: ${candidates.join(", ")})`);
+ }
+ }
+
+ if (missing.length === 0) {
+ return;
+ }
+
+ err(tr(
+ `Plugin build did not create required runtime output:\n - ${missing.join("\n - ")}`,
+ `插件构建未生成必需的运行时产物:\n - ${missing.join("\n - ")}`,
+ ));
+ process.exit(1);
+}
+
+async function installPluginNpmDependencies(destDir) {
+ if (!resolvedNpmBuild) {
+ info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
+ const npmArgs = resolvedNpmOmitDev
+ ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
+ : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
+ await run("npm", npmArgs, { cwd: destDir, silent: false });
+ return;
+ }
+
+ info(tr(
+ "Installing plugin npm dependencies for source build...",
+ "正在安装插件源码构建所需的 npm 依赖...",
+ ));
+ await run("npm", [
+ "install",
+ "--include=dev",
+ "--no-audit",
+ "--no-fund",
+ "--registry",
+ NPM_REGISTRY,
+ ], { cwd: destDir, silent: false });
+
+ info(tr(
+ `Building plugin runtime output with npm run ${resolvedNpmBuildScript}...`,
+ `正在执行 npm run ${resolvedNpmBuildScript} 构建插件运行时产物...`,
+ ));
+ await run("npm", ["run", resolvedNpmBuildScript], { cwd: destDir, silent: false });
+ await assertBuiltRuntimeOutputs(destDir);
+
+ if (resolvedNpmOmitDev && resolvedNpmPruneAfterBuild) {
+ info(tr("Pruning plugin dev dependencies...", "正在裁剪插件开发依赖..."));
+ await run("npm", [
+ "prune",
+ "--omit=dev",
+ "--no-audit",
+ "--no-fund",
+ ], { cwd: destDir, silent: false });
+ }
+}
+
async function downloadPlugin(destDir) {
const ghRaw = `https://raw.githubusercontent.com/${REPO}/${PLUGIN_VERSION}`;
const pluginDir = resolvedPluginDir;
@@ -1321,12 +1604,7 @@ async function downloadPlugin(destDir) {
await downloadPluginFile(destDir, name, url, false, i, total);
}
- // npm install
- info(tr("Installing plugin npm dependencies...", "正在安装插件 npm 依赖..."));
- const npmArgs = resolvedNpmOmitDev
- ? ["install", "--omit=dev", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY]
- : ["install", "--no-audit", "--no-fund", "--registry", NPM_REGISTRY];
- await run("npm", npmArgs, { cwd: destDir, silent: false });
+ await installPluginNpmDependencies(destDir);
info(tr(`Plugin deployed: ${PLUGIN_DEST}`, `插件部署完成: ${PLUGIN_DEST}`));
}
@@ -1432,6 +1710,64 @@ async function scrubStaleOpenClawPluginRegistration() {
await rename(tmp, configPath);
}
+async function cleanupConflictingPluginVariants() {
+ const configPath = getOpenClawConfigPath();
+ if (!existsSync(configPath)) return;
+ let cfg;
+ try {
+ cfg = JSON.parse(await readFile(configPath, "utf8"));
+ } catch { return; }
+ if (!cfg.plugins) return;
+ const p = cfg.plugins;
+ let changed = false;
+ for (const variant of PLUGIN_VARIANTS) {
+ if (variant.id === resolvedPluginId) continue;
+ if (p.entries && Object.prototype.hasOwnProperty.call(p.entries, variant.id)) {
+ info(tr(`Removing conflicting plugin variant: ${variant.id}`, `正在移除冲突的插件变体: ${variant.id}`));
+ delete p.entries[variant.id];
+ changed = true;
+ }
+ if (Array.isArray(p.allow)) {
+ const next = p.allow.filter((id) => id !== variant.id);
+ if (next.length !== p.allow.length) {
+ p.allow = next;
+ changed = true;
+ }
+ }
+ if (p.installs && Object.prototype.hasOwnProperty.call(p.installs, variant.id)) {
+ delete p.installs[variant.id];
+ changed = true;
+ }
+ if (p.slots && p.slots[variant.slot] === variant.id) {
+ p.slots[variant.slot] = variant.slotFallback || "none";
+ changed = true;
+ }
+ if (p.load && Array.isArray(p.load.paths)) {
+ const norm = (s) => String(s).replace(/\\/g, "/");
+ const extNeedle = `/extensions/${variant.id}`;
+ const next = p.load.paths.filter((path) => {
+ if (typeof path !== "string") return true;
+ return !norm(path).includes(extNeedle);
+ });
+ if (next.length !== p.load.paths.length) {
+ p.load.paths = next;
+ changed = true;
+ }
+ }
+ const variantDir = join(OPENCLAW_DIR, "extensions", variant.id);
+ if (existsSync(variantDir)) {
+ info(tr(`Removing conflicting plugin directory: ${variantDir}`, `正在移除冲突的插件目录: ${variantDir}`));
+ await rm(variantDir, { recursive: true, force: true });
+ }
+ }
+ if (!changed) return;
+ const out = JSON.stringify(cfg, null, 2) + "\n";
+ const tmp = `${configPath}.ov-install-tmp.${process.pid}`;
+ await writeFile(tmp, out, "utf8");
+ await rename(tmp, configPath);
+ info(tr("Conflicting plugin variants cleaned up", "冲突的插件变体已清理"));
+}
+
async function configureOpenClawPlugin({
preserveExistingConfig = false,
runtimeConfig = null,
@@ -1443,6 +1779,7 @@ async function configureOpenClawPlugin({
const pluginSlot = resolvedPluginSlot;
const ocEnv = getOpenClawEnv();
+ const needWorkdirFlag = OPENCLAW_DIR !== DEFAULT_OPENCLAW_DIR;
const oc = async (args) => {
const result = await runCapture("openclaw", args, { env: ocEnv, shell: IS_WIN });
@@ -1453,55 +1790,280 @@ async function configureOpenClawPlugin({
return result;
};
+ // Direct file manipulation for config (reliable across all OpenClaw versions and --workdir scenarios).
+ // OpenClaw CLI's --workdir / OPENCLAW_STATE_DIR support is inconsistent, so we read/write openclaw.json directly.
+ const configPath = getOpenClawConfigPath();
+ const readCfg = async () => {
+ if (!existsSync(configPath)) return {};
+ try { return JSON.parse(await readFile(configPath, "utf8")); } catch { return {}; }
+ };
+ const writeCfg = async (cfg) => {
+ const out = JSON.stringify(cfg, null, 2) + "\n";
+ const tmp = `${configPath}.ov-install-tmp.${process.pid}`;
+ await writeFile(tmp, out, "utf8");
+ await rename(tmp, configPath);
+ };
+ const ensurePluginRegistered = async (cfg) => {
+ if (!cfg.plugins) cfg.plugins = {};
+ const p = cfg.plugins;
+ if (!p.entries) p.entries = {};
+ if (!p.entries[pluginId]) p.entries[pluginId] = {};
+ p.entries[pluginId].enabled = true;
+ if (!p.entries[pluginId].config) p.entries[pluginId].config = {};
+ if (!Array.isArray(p.allow)) p.allow = [];
+ if (!p.allow.includes(pluginId)) p.allow.push(pluginId);
+ return cfg;
+ };
+
+ await cleanupConflictingPluginVariants();
+
if (!preserveExistingConfig) {
await scrubStaleOpenClawPluginRegistration();
}
- // Enable plugin (files already deployed to extensions dir by deployPlugin)
- await oc(["plugins", "enable", pluginId]);
- if (claimSlot) {
- await oc(["config", "set", `plugins.slots.${pluginSlot}`, pluginId]);
+ // Enable plugin: try CLI first (default path), fall back to direct file for --workdir
+ if (!needWorkdirFlag) {
+ try {
+ await oc(["plugins", "enable", pluginId]);
+ } catch (_e) {
+ info(tr("plugins enable via CLI failed, registering directly", "CLI plugins enable 失败,直接注册"));
+ const cfg = await readCfg();
+ await ensurePluginRegistered(cfg);
+ await writeCfg(cfg);
+ }
} else {
- warn(
- tr(
- `Skipped claiming plugins.slots.${pluginSlot}; it is currently owned by another plugin.`,
- `已跳过设置 plugins.slots.${pluginSlot},当前该 slot 由其他插件占用。`,
- ),
- );
+ info(tr("Using direct config write for non-default workdir", "非默认目录,使用直接配置写入"));
+ const cfg = await readCfg();
+ await ensurePluginRegistered(cfg);
+ await writeCfg(cfg);
}
if (preserveExistingConfig) {
+ if (claimSlot) {
+ const cfg = await readCfg();
+ if (!cfg.plugins) cfg.plugins = {};
+ if (!cfg.plugins.slots) cfg.plugins.slots = {};
+ cfg.plugins.slots[pluginSlot] = pluginId;
+ await writeCfg(cfg);
+ }
info(
tr(
`Preserved existing plugin runtime config for ${pluginId}`,
`已保留 ${pluginId} 的现有插件运行时配置`,
),
);
- return;
+ return { runtimeConfigOk: true };
}
+ const writeConfigDirect = async (pluginConfig, slotValue) => {
+ const cfg = await readCfg();
+ await ensurePluginRegistered(cfg);
+ Object.assign(cfg.plugins.entries[pluginId].config, pluginConfig);
+ if (slotValue) {
+ if (!cfg.plugins.slots) cfg.plugins.slots = {};
+ cfg.plugins.slots[pluginSlot] = slotValue;
+ }
+ await writeCfg(cfg);
+ };
+
+ // Legacy (memory) plugins: direct JSON write
+ if (resolvedPluginKind === "memory") {
+ const effectiveRuntimeConfig = runtimeConfig || {
+ baseUrl: remoteBaseUrl,
+ apiKey: remoteApiKey,
+ agent_prefix: remoteAgentPrefix,
+ };
+
+ let allowedPropsLegacy = null;
+ try {
+ const manifestPath = join(PLUGIN_DEST, "openclaw.plugin.json");
+ if (existsSync(manifestPath)) {
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ const schema = manifest?.configSchema;
+ if (schema?.properties && typeof schema.properties === "object") {
+ allowedPropsLegacy = new Set(Object.keys(schema.properties));
+ }
+ }
+ } catch { /* ignore parse errors */ }
+
+ const agentVal = effectiveRuntimeConfig.agent_prefix || "";
+ const candidates = {
+ mode: "remote",
+ baseUrl: effectiveRuntimeConfig.baseUrl || remoteBaseUrl,
+ targetUri: "viking://user/memories",
+ autoRecall: true,
+ autoCapture: true,
+ apiKey: effectiveRuntimeConfig.apiKey || undefined,
+ agentId: agentVal || undefined,
+ };
+
+ const pluginConfig = {};
+ for (const [key, val] of Object.entries(candidates)) {
+ if (val === undefined) continue;
+ if (allowedPropsLegacy && !allowedPropsLegacy.has(key)) continue;
+ pluginConfig[key] = val;
+ }
+ if (!pluginConfig.baseUrl) pluginConfig.baseUrl = effectiveRuntimeConfig.baseUrl || remoteBaseUrl;
+
+ await writeConfigDirect(pluginConfig, claimSlot ? pluginId : null);
+ info(tr("OpenClaw plugin configured (legacy mode, remote)", "OpenClaw 插件配置完成(旧版模式,远程连接)"));
+ return { runtimeConfigOk: true };
+ }
+
+ // Current (context-engine) plugins: delegate to `openclaw openviking setup --json`
+ // This reuses the same validation logic (health check, version compat, root key
+ // detection, slot protection, ensureInstallRecord) from commands/setup.ts
const effectiveRuntimeConfig = runtimeConfig || {
baseUrl: remoteBaseUrl,
apiKey: remoteApiKey,
agent_prefix: remoteAgentPrefix,
+ accountId: remoteAccountId,
+ userId: remoteUserId,
};
- await oc(["config", "set", `plugins.entries.${pluginId}.config.baseUrl`, effectiveRuntimeConfig.baseUrl || remoteBaseUrl]);
- if (effectiveRuntimeConfig.apiKey) {
- await oc(["config", "set", `plugins.entries.${pluginId}.config.apiKey`, effectiveRuntimeConfig.apiKey]);
+ // Detect if the installed plugin supports `setup --json` by checking the deployed setup.ts
+ let setupJsonSupported = false;
+ try {
+ const setupTsPath = join(PLUGIN_DEST, "commands", "setup.ts");
+ if (existsSync(setupTsPath)) {
+ const setupSrc = await readFile(setupTsPath, "utf8");
+ setupJsonSupported = setupSrc.includes('"--json"') || setupSrc.includes("'--json'");
+ }
+ } catch { /* ignore read errors */ }
+
+ let setupResult = null;
+ if (setupJsonSupported) {
+ const setupArgs = ["openviking", "setup"];
+ setupArgs.push("--base-url", effectiveRuntimeConfig.baseUrl || remoteBaseUrl);
+ setupArgs.push("--json");
+ if (effectiveRuntimeConfig.apiKey) {
+ setupArgs.push("--api-key", effectiveRuntimeConfig.apiKey);
+ }
+ if (effectiveRuntimeConfig.agent_prefix) {
+ setupArgs.push("--agent-prefix", effectiveRuntimeConfig.agent_prefix);
+ }
+ if (effectiveRuntimeConfig.accountId) {
+ setupArgs.push("--account-id", effectiveRuntimeConfig.accountId);
+ }
+ if (effectiveRuntimeConfig.userId) {
+ setupArgs.push("--user-id", effectiveRuntimeConfig.userId);
+ }
+ if (claimSlot) {
+ setupArgs.push("--force-slot");
+ }
+ if (nonInteractive) {
+ setupArgs.push("--allow-offline");
+ }
+
+ info(tr(
+ "Delegating configuration to: openclaw openviking setup --json",
+ "委托配置给: openclaw openviking setup --json",
+ ));
+
+ setupResult = await runCapture("openclaw", setupArgs, { env: ocEnv, shell: IS_WIN });
+ } else {
+ info(tr(
+ "Installed plugin does not support setup --json, using direct config write",
+ "已安装的插件不支持 setup --json,使用直接配置写入",
+ ));
}
- if (effectiveRuntimeConfig.agent_prefix) {
- await oc(["config", "set", `plugins.entries.${pluginId}.config.agent_prefix`, effectiveRuntimeConfig.agent_prefix]);
+
+ let parsed = null;
+ if (setupResult) {
+ parsed = parseJsonObjectFromOutput(`${setupResult.out || ""}\n${setupResult.err || ""}`);
}
- // Legacy (memory) plugins need explicit targetUri/autoRecall/autoCapture (new version has defaults in config.ts)
- if (resolvedPluginKind === "memory") {
- await oc(["config", "set", `plugins.entries.${pluginId}.config.targetUri`, "viking://user/memories"]);
- await oc(["config", "set", `plugins.entries.${pluginId}.config.autoRecall`, "true", "--json"]);
- await oc(["config", "set", `plugins.entries.${pluginId}.config.autoCapture`, "true", "--json"]);
+ if (parsed) {
+ if (parsed.success) {
+ info(tr("OpenClaw plugin configured via setup", "OpenClaw 插件通过 setup 配置完成"));
+ if (parsed.health?.ok) {
+ info(tr(
+ `Server health: OK${parsed.health.version ? ` (version: ${parsed.health.version})` : ""}`,
+ `服务端健康: OK${parsed.health.version ? `(版本: ${parsed.health.version})` : ""}`,
+ ));
+ }
+ if (parsed.health?.compatibility === "server_too_old") {
+ warn(tr(
+ "Server version may be too old for this plugin version",
+ "服务端版本可能低于此插件版本要求",
+ ));
+ }
+ if (parsed.slot?.activated) {
+ info(tr(`contextEngine slot activated`, `contextEngine slot 已激活`));
+ }
+ } else {
+ // Setup returned success: false
+ if (parsed.action === "slot_blocked") {
+ warn(tr(
+ `Config saved but contextEngine slot is owned by "${parsed.slot?.previousOwner}". Use --force-slot to override.`,
+ `配置已保存,但 contextEngine slot 被 "${parsed.slot?.previousOwner}" 占用。使用 --force-slot 覆盖。`,
+ ));
+ } else {
+ err(tr(
+ `Setup failed: ${parsed.error || "unknown error"}`,
+ `配置失败: ${parsed.error || "未知错误"}`,
+ ));
+ return {
+ runtimeConfigOk: false,
+ error: parsed.error || parsed.action || "unknown error",
+ };
+ }
+ }
+ } else if (setupResult && setupResult.code !== 0) {
+ warn(tr(
+ `openclaw openviking setup exited with code ${setupResult.code}. Falling back to direct JSON config write.`,
+ `openclaw openviking setup 退出码 ${setupResult.code},回退到直接写入 JSON 配置。`,
+ ));
+ }
+
+ if (!parsed) {
+ // Direct write: only used when the installed plugin doesn't support `setup --json` (old version).
+ // Read the deployed configSchema to determine which fields are allowed, avoiding
+ // "additionalProperties" validation failures when writing new fields to old schemas.
+ let allowedProps = null;
+ try {
+ const manifestPath = join(PLUGIN_DEST, "openclaw.plugin.json");
+ if (existsSync(manifestPath)) {
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ const schema = manifest?.configSchema;
+ if (schema?.properties && typeof schema.properties === "object") {
+ allowedProps = new Set(Object.keys(schema.properties));
+ }
+ }
+ } catch { /* ignore parse errors, write all fields */ }
+
+ const agentVal = effectiveRuntimeConfig.agent_prefix || "";
+ const useAgentPrefix = !allowedProps || allowedProps.has("agent_prefix");
+ const candidates = {
+ mode: "remote",
+ baseUrl: effectiveRuntimeConfig.baseUrl || remoteBaseUrl,
+ apiKey: effectiveRuntimeConfig.apiKey || "",
+ accountId: effectiveRuntimeConfig.accountId || undefined,
+ userId: effectiveRuntimeConfig.userId || undefined,
+ };
+ if (useAgentPrefix) {
+ candidates.agent_prefix = agentVal;
+ } else {
+ candidates.agentId = agentVal;
+ }
+
+ const pluginConfig = {};
+ for (const [key, val] of Object.entries(candidates)) {
+ if (val === undefined) continue;
+ if (allowedProps && !allowedProps.has(key)) continue;
+ pluginConfig[key] = val;
+ }
+ if (!pluginConfig.baseUrl) pluginConfig.baseUrl = effectiveRuntimeConfig.baseUrl || remoteBaseUrl;
+ if (!("apiKey" in pluginConfig)) pluginConfig.apiKey = effectiveRuntimeConfig.apiKey || "";
+
+ await writeConfigDirect(pluginConfig, claimSlot ? pluginId : null);
+ info(tr(
+ `OpenClaw plugin configured (direct write): baseUrl=${pluginConfig.baseUrl}, apiKey=${pluginConfig.apiKey ? "***" : "(empty)"}`,
+ `OpenClaw 插件配置完成(直接写入): baseUrl=${pluginConfig.baseUrl}, apiKey=${pluginConfig.apiKey ? "***" : "(空)"}`,
+ ));
}
- info(tr("OpenClaw plugin configured", "OpenClaw 插件配置完成"));
+ return { runtimeConfigOk: true };
}
async function writeOpenvikingEnv() {
@@ -1559,6 +2121,125 @@ function getExistingEnvFiles() {
return existsSync(envPath) ? { shellPath: envPath } : null;
}
+async function performUninstall() {
+ info(tr("Mode: uninstall plugin", "模式: 卸载插件"));
+ info(tr(`Target: ${OPENCLAW_DIR}`, `目标实例: ${OPENCLAW_DIR}`));
+
+ const configPath = getOpenClawConfigPath();
+ if (!existsSync(configPath)) {
+ info(tr(
+ "No openclaw.json found. Nothing to uninstall.",
+ "未找到 openclaw.json,无需卸载。",
+ ));
+ return;
+ }
+
+ const installedState = await detectInstalledPluginState();
+ if (installedState.generation === "none") {
+ info(tr(
+ "No OpenViking plugin entries found in openclaw.json. Nothing to uninstall.",
+ "openclaw.json 中未找到 OpenViking 插件配置,无需卸载。",
+ ));
+ return;
+ }
+
+ info(tr(
+ `Detected installed plugin: ${formatInstalledStateLabel(installedState)}`,
+ `检测到已安装插件: ${formatInstalledStateLabel(installedState)}`,
+ ));
+
+ if (!nonInteractive) {
+ const answer = await question(
+ tr("Confirm uninstall? (y/N)", "确认卸载?(y/N)"),
+ "N",
+ );
+ if (answer.toLowerCase() !== "y" && answer.toLowerCase() !== "yes") {
+ info(tr("Cancelled.", "已取消。"));
+ return;
+ }
+ }
+
+ // Step 1: Stop gateway
+ info(tr("Step 1: Stopping OpenClaw gateway...", "步骤 1: 停止 OpenClaw gateway..."));
+ await stopOpenClawGatewayForUpgrade();
+
+ // Step 2: Backup config
+ info(tr("Step 2: Backing up configuration...", "步骤 2: 备份配置..."));
+ const configBackupPath = await backupOpenClawConfig(configPath);
+ info(tr(`Config backed up to: ${configBackupPath}`, `配置已备份至: ${configBackupPath}`));
+
+ // Step 3: Clean plugin config from openclaw.json
+ info(tr("Step 3: Cleaning plugin configuration...", "步骤 3: 清理插件配置..."));
+ await cleanupInstalledPluginConfig(installedState);
+
+ // Step 4: Backup and remove plugin directories
+ info(tr("Step 4: Backing up plugin directories...", "步骤 4: 备份插件目录..."));
+ const pluginBackups = [];
+ for (const detection of installedState.detections) {
+ const backupDir = await backupPluginDirectory(detection.variant);
+ if (backupDir) {
+ pluginBackups.push({ pluginId: detection.variant.id, backupDir });
+ }
+ }
+
+ // Step 5: Remove env files
+ info(tr("Step 5: Removing environment files...", "步骤 5: 移除环境文件..."));
+ const envFilesToRemove = IS_WIN
+ ? [
+ join(OPENCLAW_DIR, "openviking.env.bat"),
+ join(OPENCLAW_DIR, "openviking.env.ps1"),
+ ]
+ : [join(OPENCLAW_DIR, "openviking.env")];
+ let removedEnvCount = 0;
+ for (const f of envFilesToRemove) {
+ if (existsSync(f)) {
+ try {
+ await rm(f);
+ removedEnvCount++;
+ info(tr(`Removed: ${f}`, `已移除: ${f}`));
+ } catch { /* ignore */ }
+ }
+ }
+ if (removedEnvCount === 0) {
+ info(tr("No environment files found.", "未找到环境文件。"));
+ }
+
+ // Step 6: Write uninstall audit
+ const auditDir = getUpgradeAuditDir();
+ await mkdir(auditDir, { recursive: true });
+ const auditData = {
+ operation: "uninstall",
+ createdAt: new Date().toISOString(),
+ fromVersion: formatInstalledStateLabel(installedState),
+ configBackupPath,
+ pluginBackups,
+ };
+ await writeUpgradeAuditFile(auditData);
+
+ // Done
+ console.log("");
+ bold("═══════════════════════════════════════════════════════════");
+ bold(` ${tr("Uninstall complete!", "卸载完成!")}`);
+ bold("═══════════════════════════════════════════════════════════");
+ console.log("");
+
+ info(tr("OpenViking server/runtime is preserved (not uninstalled).", "OpenViking 服务端/运行时已保留(未卸载)。"));
+ console.log("");
+
+ info(tr("To restore the plugin configuration:", "如需恢复插件配置:"));
+ console.log(` 1) ${tr("Stop gateway:", "停止 gateway:")} openclaw gateway stop`);
+ console.log(` 2) ${tr("Restore config:", "恢复配置:")} ${IS_WIN ? "copy" : "cp"} "${configBackupPath}" "${configPath}"`);
+ for (const pb of pluginBackups) {
+ const liveDir = join(OPENCLAW_DIR, "extensions", pb.pluginId);
+ console.log(` 3) ${tr("Restore plugin:", "恢复插件:")} ${IS_WIN ? "move" : "mv"} "${pb.backupDir}" "${liveDir}"`);
+ }
+ console.log("");
+
+ info(tr("To reinstall:", "重新安装:"));
+ console.log(" ov-install");
+ console.log("");
+}
+
async function main() {
console.log("");
bold(tr("🦣 OpenClaw OpenViking plugin installer", "🦣 OpenClaw OpenViking 插件安装"));
@@ -1569,6 +2250,10 @@ async function main() {
await printCurrentVersionInfo();
return;
}
+ if (uninstallPlugin) {
+ await performUninstall();
+ return;
+ }
if (rollbackLastUpgrade) {
info(tr("Mode: rollback last plugin upgrade", "模式: 回滚最近一次插件升级"));
if (pluginVersionExplicit) {
@@ -1602,7 +2287,7 @@ async function main() {
await deployPluginFromRemote();
- await configureOpenClawPlugin(
+ const configResult = await configureOpenClawPlugin(
upgradePluginOnly
? {
runtimeConfig: upgradeRuntimeConfig,
@@ -1610,15 +2295,23 @@ async function main() {
}
: { preserveExistingConfig: false },
);
- await writeInstallStateFile({
- operation: upgradePluginOnly ? "upgrade" : "install",
- fromVersion: upgradeAudit?.fromVersion || "",
- configBackupPath: upgradeAudit?.configBackupPath || "",
- pluginBackups: upgradeAudit?.pluginBackups || [],
- });
- if (upgradeAudit) {
- upgradeAudit.completedAt = new Date().toISOString();
- await writeUpgradeAuditFile(upgradeAudit);
+ const runtimeConfigOk = configResult?.runtimeConfigOk !== false;
+ const runtimeConfigError = configResult?.error || "";
+
+ // Only mark the install as completed (state file + upgrade audit) when the
+ // runtime config was actually applied. Plugin files are already on disk
+ // either way, so subsequent runs can pick up from here.
+ if (runtimeConfigOk) {
+ await writeInstallStateFile({
+ operation: upgradePluginOnly ? "upgrade" : "install",
+ fromVersion: upgradeAudit?.fromVersion || "",
+ configBackupPath: upgradeAudit?.configBackupPath || "",
+ pluginBackups: upgradeAudit?.pluginBackups || [],
+ });
+ if (upgradeAudit) {
+ upgradeAudit.completedAt = new Date().toISOString();
+ await writeUpgradeAuditFile(upgradeAudit);
+ }
}
let envFiles = getExistingEnvFiles();
if (!upgradePluginOnly) {
@@ -1628,18 +2321,33 @@ async function main() {
}
console.log("");
- bold("═══════════════════════════════════════════════════════════");
- bold(` ${tr("Installation complete!", "安装完成!")}`);
- bold("═══════════════════════════════════════════════════════════");
- console.log("");
+ if (runtimeConfigOk) {
+ bold("═══════════════════════════════════════════════════════════");
+ bold(` ${tr("Installation complete!", "安装完成!")}`);
+ bold("═══════════════════════════════════════════════════════════");
+ console.log("");
- if (upgradeAudit) {
- info(tr(`Upgrade path recorded: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`, `已记录升级路径: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`));
- info(tr(`Rollback config backup: ${upgradeAudit.configBackupPath}`, `回滚配置备份: ${upgradeAudit.configBackupPath}`));
- for (const pluginBackup of upgradeAudit.pluginBackups || []) {
- info(tr(`Rollback plugin backup: ${pluginBackup.backupDir}`, `回滚插件备份: ${pluginBackup.backupDir}`));
+ if (upgradeAudit) {
+ info(tr(`Upgrade path recorded: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`, `已记录升级路径: ${upgradeAudit.fromVersion} -> ${upgradeAudit.toVersion}`));
+ info(tr(`Rollback config backup: ${upgradeAudit.configBackupPath}`, `回滚配置备份: ${upgradeAudit.configBackupPath}`));
+ for (const pluginBackup of upgradeAudit.pluginBackups || []) {
+ info(tr(`Rollback plugin backup: ${pluginBackup.backupDir}`, `回滚插件备份: ${pluginBackup.backupDir}`));
+ }
+ info(tr(`Rollback audit file: ${getUpgradeAuditPath()}`, `回滚审计文件: ${getUpgradeAuditPath()}`));
+ console.log("");
}
- info(tr(`Rollback audit file: ${getUpgradeAuditPath()}`, `回滚审计文件: ${getUpgradeAuditPath()}`));
+ } else {
+ bold("═══════════════════════════════════════════════════════════");
+ bold(` ${tr(
+ "Plugin files installed, but runtime configuration was NOT applied",
+ "插件文件已安装,但运行时配置未生效",
+ )}`);
+ bold(` ${tr(`Reason: ${runtimeConfigError}`, `原因: ${runtimeConfigError}`)}`);
+ bold(` ${tr(
+ "Re-run: openclaw openviking setup --reconfigure",
+ "重新运行: openclaw openviking setup --reconfigure",
+ )}`);
+ bold("═══════════════════════════════════════════════════════════");
console.log("");
}
diff --git a/examples/openclaw-plugin/setup-helper/package.json b/examples/openclaw-plugin/setup-helper/package.json
index 81e040fcc..afd3d30a7 100644
--- a/examples/openclaw-plugin/setup-helper/package.json
+++ b/examples/openclaw-plugin/setup-helper/package.json
@@ -1,6 +1,6 @@
{
"name": "openclaw-openviking-setup-helper",
- "version": "0.2.16-dev.4",
+ "version": "0.3.0-beta.25",
"description": "Setup helper for installing OpenViking memory plugin into OpenClaw",
"type": "module",
"bin": {
diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
index d4f9e732f..63fe99502 100644
--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
@@ -1,126 +1,665 @@
---
-name: openviking-memory
-description: OpenViking long-term memory plugin guide. Once installed, the plugin automatically remembers important facts from conversations and recalls relevant context before responding.
+name: install-openviking-memory
+description: >
+ Install and configure the OpenViking long-term memory plugin for OpenClaw via natural conversation.
+ Once installed, the plugin automatically captures important facts from chats and recalls relevant
+ context before each reply (auto-capture + auto-recall, cross-session). Covers prerequisites check,
+ plugin install through OpenClaw's plugin manager first, with ov-install only as a backup path,
+ wizard-based configuration, slot activation,
+ gateway restart, verification, plus multi-tenant root-key support, multi-instance, and uninstall.
+ Trigger when the user says any of: "install OpenViking", "set up memory", "configure memory plugin",
+ "add long-term memory", "connect to OpenViking server", "RAG", "semantic memory",
+ "帮我装 OpenViking", "配置记忆插件", "安装记忆功能", "接入 OpenViking", "我有一台 OpenViking 服务器".
+ The user does NOT need to know any CLI commands — the agent runs everything and only asks for a few values.
+ This skill assumes the OpenViking server is already running. If the server is not ready, the skill
+ tells the user to contact their admin or set it up via the OpenViking docs — it does NOT install the server.
+version: 2.0.0
+metadata:
+ openclaw:
+ requires:
+ bins:
+ - node
+ - openclaw
+ emoji: "🦣"
+ homepage: "https://github.com/volcengine/OpenViking"
+tags:
+ - install
+ - setup
+ - memory
+ - openviking
+ - rag
+ - long-term-memory
---
-# OpenViking Memory Guide
+# Install OpenViking Memory — Agent Installation & Reference Skill
+
+You are about to help a user install and configure the OpenViking memory plugin for OpenClaw.
+The user does NOT know how to use a terminal. You will collect a few values through natural conversation, then run **all** commands yourself using your shell tool.
+
+**Read this entire document before starting. Follow every step in order. Do NOT skip steps.**
+
+This skill is split into two halves:
+
+- **Part 1 (STEP 0–10): Natural-language installation walkthrough.** Use this on first install or reconfigure.
+- **Part 2: Reference.** Tools, config schema, multi-tenant, multi-instance, daily ops, uninstall, error recovery. Read on demand.
+
+> **Server scope.** This skill **does not** install the OpenViking server itself. It assumes the server is already running locally on `127.0.0.1:1933` or on another machine. If the user has no server, see "Server not ready" handling in STEP 5.
+
+---
+
+# Part 1 — Natural-Language Installation Walkthrough
+
+## STEP 0: Detect Language
+
+If the user's first message contains Chinese characters, respond in **Chinese** throughout.
+Otherwise respond in **English**.
+All user-facing messages below have (CN)/(EN) variants — use the matching one.
+
+Do NOT show this step to the user.
+
+---
+
+## STEP 1: Detect Operating System (silently)
+
+Run this command and remember the result. Do NOT show it to the user.
+
+```bash
+uname -s 2>/dev/null || echo WINDOWS
+```
+
+- Output contains `Darwin` → `OS=mac`
+- Output contains `Linux` → `OS=linux`
+- Output is `WINDOWS` or the command fails → `OS=windows`
+
+---
+
+## STEP 2: Check Prerequisites (silently)
+
+Run silently:
+
+```bash
+node -v
+openclaw --version
+```
+
+**If `node` is missing:**
+
+> (CN) 你的系统没有安装 Node.js。OpenClaw 和 OpenViking 插件需要 Node.js >= 22。请先安装 Node.js,然后再回来找我。
+> (EN) Node.js is not installed. OpenClaw and the OpenViking plugin require Node.js >= 22. Please install Node.js first, then come back.
+
+**Stop. Do NOT continue.**
+
+**If `openclaw` is missing:**
+
+> (CN) 你的系统没有安装 OpenClaw。请先安装 OpenClaw(>= 2026.4.8),然后再回来找我。
+> (EN) OpenClaw is not installed. Please install OpenClaw (>= 2026.4.8) first, then come back.
+
+**Stop. Do NOT continue.**
+
+If both exist, proceed to STEP 3 silently.
+
+---
+
+## STEP 3: Greet and Ask for 3 Values
+
+Send this message:
+
+> (CN) 好,我来帮你接入 OpenViking 长期记忆。装好之后,我会自动记住对话里的重要信息,下次聊也能回忆起来。
+>
+> 我需要 3 条信息,不知道的可以问你的管理员:
+> 1. **OpenViking 服务地址** —— 例如 `https://ov.example.com` 或 `http://192.168.1.100:1933`,本机服务可以直接说"本机"
+> 2. **API Key** —— 用来鉴权;服务没开认证可以说"没有"
+> 3. **Agent 标识前缀**(可选) —— 用于区分多个 agent 的记忆命名空间,留空就用默认
+>
+> 先告诉我服务地址吧?
+
+> (EN) I'll set up OpenViking long-term memory for you. Once configured, I'll automatically remember important info from our chats and recall it later.
+>
+> I need 3 things (ask your admin if unsure):
+> 1. **OpenViking server URL** — e.g. `https://ov.example.com` or `http://192.168.1.100:1933`. For a local server, just say "local".
+> 2. **API Key** — for auth. Say "none" if the server has no auth.
+> 3. **Agent prefix** (optional) — used to namespace memories across agents. Leave blank for default.
+>
+> What's the server URL?
+
+---
+
+## STEP 4: Collect Values
+
+Collect 3 values through natural conversation. Be flexible: if the user gives several at once, parse them all. If they correct something, accept the new value.
+
+### 4a. `BASE_URL` (REQUIRED)
+
+- "local" / "本机" / "localhost" → use `http://127.0.0.1:1933`.
+- `ov.example.com` without protocol → prepend `https://`.
+- Strip trailing `/`, `/health`, or `/api`.
+- After normalization must start with `http://` or `https://`.
+- If the user says they don't know, ask them to check with the admin or look at how the server was started. **Do NOT make up a URL.**
+
+### 4b. `API_KEY` (OPTIONAL)
+
+> (CN) API Key 是什么?服务没开认证就直接说"没有"。
+> (EN) What's the API Key? Say "none" if the server has no auth.
+
+- "no" / "none" / "没有" / "空" / empty → `API_KEY=""` (you will skip the flag later).
+- Otherwise store as-is.
+
+### 4c. `AGENT_PREFIX` (OPTIONAL)
+
+> (CN) 想给这个 agent 一个记忆前缀吗?留空就用默认。只能用字母、数字、`_`、`-`。
+> (EN) Want to set an agent prefix? Leave blank for the default. Letters, digits, `_`, `-` only.
+
+- Empty / "default" / "默认" → leave unset (plugin defaults to `""`).
+- Otherwise validate against `/^[A-Za-z0-9_-]+$/`. If invalid, ask again.
+
+### 4d. (Conditional) Multi-Tenant Root-Key Fields
+
+Only ask for these if STEP 7 detects a root key (`Root API key detected. Missing: --account-id, --user-id`). Don't ask up front.
+
+- `ACCOUNT_ID`
+- `USER_ID`
+
+See **Reference: Multi-Tenant** for what these mean.
+
+---
+
+## STEP 5: Pre-flight Connectivity Check (silently)
+
+Tell the user briefly:
+
+> (CN) 我先测一下能不能连上服务……
+> (EN) Let me test the connection to your server...
+
+Run:
+
+**If OS=windows:**
+
+```powershell
+try { (Invoke-WebRequest -Uri "BASE_URL/health" -TimeoutSec 10 -UseBasicParsing -ErrorAction Stop).StatusCode } catch { $_.Exception.Response.StatusCode.value__ }
+```
+
+**If OS=mac or OS=linux:**
+
+```bash
+curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "BASE_URL/health"
+```
+
+Replace `BASE_URL` with the actual value.
+
+| Status | Meaning | Action |
+|---|---|---|
+| `200` | Server reachable, no auth on `/health` | Proceed to STEP 6. |
+| `401` / `403` | Server reachable but `/health` requires auth | Proceed to STEP 6 — the wizard's key probe will sort it out. |
+| `000` / timeout / connection refused | Server unreachable | **Server-not-ready handling** below. |
+| Anything else | Unexpected | Show status code to the user, go back to STEP 4a. |
+
+### Server-not-ready handling
+
+This skill **does not install or operate the OpenViking server**. If the user's server is unreachable, present the situation honestly and offer two paths:
+
+> (CN) ❌ 我连不上 `BASE_URL`。可能是:
+> 1) 服务还没启动 —— 请联系你的 OpenViking 服务管理员把它起起来;如果是你自己负责,请参考 OpenViking 官方文档(`https://github.com/volcengine/OpenViking`)的 server 启动指引。
+> 2) 地址不对 —— 你可以重新告诉我正确的地址。
+> 3) 网络不通(防火墙 / VPN / 内网)—— 你确认一下网络。
+>
+> 也可以选择"先把配置写下来",等服务起来就自动生效,要这么办吗?
+
+> (EN) ❌ Cannot reach `BASE_URL`. Likely cause:
+> 1) **Server isn't running** — please ask your OpenViking admin to start it. If you own the server, follow the OpenViking official docs (`https://github.com/volcengine/OpenViking`) to start it. **This skill does not install or run the server.**
+> 2) **Wrong URL** — give me the correct URL.
+> 3) **Network blocked** (firewall / VPN / private network) — please verify connectivity.
+>
+> Or I can save the config now (`--allow-offline`) so it will activate automatically once the server is up. Want me to do that?
+
+If the user fixes the URL → back to STEP 4a.
+If the user wants `--allow-offline` → remember `ALLOW_OFFLINE=true` and continue to STEP 6.
+If the user gives up / cannot fix → stop here. Do NOT continue with a broken state.
+
+---
+
+## STEP 6: Install the Plugin
+
+The plugin can be installed two ways. **Always try Path A first.** Use Path B only as a backup when Path A fails because ClawHub is unavailable, rate-limited, or authentication blocks anonymous install. For version conflicts, dependency errors, or other non-registry failures, stop and show the user the error instead of switching paths silently.
+
+### Path A — Primary: `openclaw plugins install` (uses ClawHub)
+
+Tell the user:
+
+> (CN) 现在开始装插件……
+> (EN) Installing the plugin now...
+
+Run:
+
+```bash
+openclaw plugins install @openclaw/openviking
+```
+
+Trigger fallback to Path B only if the output contains any of these strings:
+
+- `429`
+- `rate limit` / `rate-limited` / `Too Many Requests`
+- `not logged in` / `please log in` / `please login` / `unauthorized` / `401` / `403` together with `clawhub`
+- `ETIMEDOUT` / `ECONNRESET` on a `clawhub`-related host
+- generic message indicating the registry refused an anonymous client
+
+Before falling back, also try the explicit registry prefix once:
+
+```bash
+openclaw plugins install clawhub:@openclaw/openviking
+```
+
+If the install **succeeds**, jump to STEP 7.
+
+If both attempts fail with one of the fallback-eligible errors above, go to Path B. If the failure is a version conflict, missing dependency, package validation error, or another non-registry error, stop and show the last 30 lines to the user.
+
+### Path B — Backup: `ov-install` (bypasses ClawHub)
+
+Tell the user:
+
+> (CN) ClawHub 现在好像被限流、不可用,或者当前账号不能安装。我改用备用路径,直接从 GitHub 下载插件源码安装。
+> (EN) ClawHub looks rate-limited, unavailable, or blocked for this account. I'll use the backup path and install the plugin source directly from GitHub.
+
+Run the installer with `npx` (no global install needed):
+
+```bash
+npx -y openclaw-openviking-setup-helper@latest --base-url BASE_URL [--api-key API_KEY] [--agent-prefix AGENT_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID]
+```
+
+Build the flag list according to what the user gave you:
+
+- Always pass `--base-url BASE_URL`.
+- Pass `--api-key API_KEY` only if `API_KEY` is non-empty.
+- Pass `--agent-prefix AGENT_PREFIX` only if the user gave one.
+- `--account-id` / `--user-id` only if the root-key path requires them.
+
+`ov-install` will, in one shot:
+1. Download plugin sources from `raw.githubusercontent.com` into the OpenClaw `extensions/` dir.
+2. Run `npm install --omit=dev` inside the staging dir.
+3. Register the plugin in `openclaw.json` (via `openclaw plugins enable` or direct write).
+4. Run `openclaw openviking setup --json --base-url … [--api-key …] --force-slot` for the user.
+5. Fall back to direct config write if `setup --json` fails.
+
+This means **STEP 7 is effectively done by `ov-install`**. After `ov-install` exits 0, jump straight to **STEP 9** (gateway restart) and **STEP 10** (verify).
+
+If `ov-install` exits non-zero, capture the last 30 lines of its output, show them to the user, and stop. Don't retry blindly.
+
+---
+
+## STEP 7: Configure (only on Path A — Path B did this for you)
+
+Run the setup wizard non-interactively. Build flags from collected values:
+
+```bash
+openclaw openviking setup --base-url BASE_URL --json [--api-key API_KEY] [--agent-prefix AGENT_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID] [--allow-offline] [--force-slot]
+```
+
+Rules:
+
+- `--base-url BASE_URL` is **required** under `--json`. Without it, the wizard prints `--json requires --base-url for non-interactive mode`.
+- `--api-key` only if `API_KEY` is non-empty.
+- `--agent-prefix` only if the user gave one. Use **`--agent-prefix`**, not `--agent-id` (deprecated and removed).
+- `--account-id` / `--user-id` only after STEP 7 root-key detection (see below).
+- `--allow-offline` only if the user explicitly approved it in STEP 5.
+- `--force-slot` **never** in the first attempt. Add only after the user confirms (see slot_blocked handling below).
+
+### Parse the JSON output
+
+The wizard prints a single JSON object:
+
+```json
+{
+ "success": true | false,
+ "action": "configured" | "existing" | "error" | "slot_blocked",
+ "config": { "mode": "remote", "baseUrl": "...", "apiKey": "...", "agent_prefix": "...", "accountId": "...", "userId": "..." },
+ "health": { "ok": true, "status": 200 },
+ "keyProbe": { "keyType": "user_key" | "root_key" | "none", "ok": true },
+ "slot": { "ok": true, "owner": "openviking" },
+ "error": "..."
+}
+```
+
+### Decision matrix
+
+| Condition | Action |
+|---|---|
+| `success: true` and `action: "configured"` or `"existing"` | Done. Proceed to STEP 9. |
+| `success: false` and `action: "slot_blocked"` | **Slot conflict — see below.** |
+| `success: false` and `error` contains `"Server unreachable"` | Connectivity broke between STEP 5 and STEP 7. Offer `--allow-offline`; if accepted, retry. Otherwise back to STEP 4a. |
+| `success: false` and `error` contains `"Root API key detected"` and `"Missing: --account-id, --user-id"` | **Root-key path — see below.** |
+| `success: false` and `error` contains `"Invalid API key"` / `keyProbe.keyType: "none"` with `ok: false` | API key wrong. Back to STEP 4b. |
+| `success: false` and any other `action: "error"` | Show `error` to the user, stop. Do NOT pretend success. |
+
+### Slot conflict (`slot_blocked`)
+
+The error text looks like:
+
+> `contextEngine slot is owned by "<other-plugin>". Config was saved but slot was NOT changed. Use --force-slot to replace.`
+
+**Do NOT silently use `--force-slot`.** Ask the user:
+
+> (CN) 你的 OpenClaw 当前 contextEngine 槽被 `<other-plugin>` 占着。如果用 OpenViking 替换它,`<other-plugin>` 就不再生效。要替换吗?
+> (EN) Your `contextEngine` slot is currently owned by `<other-plugin>`. Activating OpenViking will disable it. Replace?
+
+If the user agrees, retry the same setup command with `--force-slot` appended. If they decline, tell them config has been saved but the slot is unchanged, and stop.
+
+### Root-key path
+
+The error text looks like:
+
+> `Root API key detected. Missing: --account-id, --user-id. Provide both to enable multi-tenant scoping.`
+
+Ask the user:
+
+> (CN) 你给的是 root 级 API Key,需要再补两个值才能用:账户 ID(accountId)和用户 ID(userId)。这两个一般是 OpenViking 服务管理员配的,不知道就问他们。
+> (EN) Your API key is a root key, which needs two more values: `accountId` and `userId`. Both come from your OpenViking server admin — ask them if unsure.
+
+After collecting, retry the setup command with `--account-id` and `--user-id` appended.
+
+---
+
+## STEP 8: (Reserved — done inside STEP 7 or by `ov-install`)
+
+The setup wizard already wrote `plugins.entries.openviking.config.*` and (if successful) set `plugins.slots.contextEngine = "openviking"`. There is no separate STEP 8 — go to STEP 9.
+
+---
+
+## STEP 9: Restart the Gateway
+
+```bash
+openclaw gateway restart
+```
+
+If it fails, try once more with:
+
+```bash
+openclaw gateway --force
+```
+
+If both fail:
+
+> (CN) Gateway 没能自动重启。请你手动跑一下 `openclaw gateway restart`。重启完告诉我,我来验证。
+> (EN) Gateway didn't restart cleanly. Please run `openclaw gateway restart` manually, then tell me when it's done so I can verify.
+
+Wait ~3 seconds before STEP 10.
+
+---
+
+## STEP 10: Verify
+
+```bash
+openclaw openviking status --json
+```
+
+Expected output:
+
+```json
+{
+ "configured": true,
+ "slotActive": true,
+ "health": { "ok": true },
+ "config": { "baseUrl": "...", "agent_prefix": "..." }
+}
+```
+
+### Decision
+
+- `configured: true` **and** `slotActive: true` **and** `health.ok: true` → **success.** Send the success message below.
+- `configured: true` but `slotActive: false` → if you previously skipped `--force-slot`, ask the user about replacing now and retry STEP 7 with `--force-slot`. Otherwise it's a gateway restart issue — back to STEP 9.
+- `configured: true` but `health.ok: false` → server became unreachable. Tell the user; the config will start working as soon as the server is back.
+- `configured: false` → setup didn't actually persist. Show full status JSON to the user and stop.
+
+### Success message
+
+> (CN) 🎉 全部搞定!OpenViking 长期记忆已经接好了。
+>
+> 工作方式:
+> - **每一轮**:你的对话会被自动归档到 OpenViking session 里
+> - **`/compact` 时**:归档消息会被抽取成长期记忆,写到 `~/.openviking/data/` 下
+> - **后续会话**:每次回复前我都会自动搜一下相关记忆并带进上下文
+>
+> 想验证一下吗?跟我聊几句包含可记忆事实的话(例如"我的邮箱是 [email protected]"),然后调一下 `/compact`,再开新对话问"我的邮箱是?",应该就能召回了。
+
+> (EN) 🎉 All set! OpenViking long-term memory is connected.
+>
+> How it works:
+> - **Every turn**: our messages are auto-archived into an OpenViking session
+> - **On `/compact`**: archived messages are extracted into long-term memories under `~/.openviking/data/`
+> - **Future sessions**: relevant memories are auto-retrieved and injected before my replies
+>
+> Want to verify? Tell me a few facts (e.g. "my email is [email protected]"), run `/compact`, then start a new chat and ask "what's my email?" — it should recall.
+
+---
+
+# Part 2 — Reference
## How It Works
-- **Auto-Capture**: At `afterTurn` (end of one user turn run), automatically extracts memories from user/assistant messages
- - `semantic` mode: captures all qualifying user text, relying on OpenViking's extraction pipeline to filter
- - `keyword` mode: only captures text matching trigger words (e.g. "remember", "preference", etc.)
-- **Auto-Recall**: In `assemble()`, automatically searches for relevant memories and prepends them to the current user message context
+The context-engine pipeline has three distinct stages — keep them apart, especially when telling users when memories actually appear in `~/.openviking/data/`:
+
+- **Archive / capture (context-engine `afterTurn`)**: at the end of a user turn, the plugin commits user/assistant messages to the OpenViking session via `POST /api/v1/sessions/.../messages`. This is **archive only** — no memory extraction yet. You'll see session message counts grow on the server, but no new files under `viking://user/.../memories/`.
+- **Memory extraction (on `/compact`)**: memory extraction runs when the user invokes OpenClaw's `/compact` command. The server-side extraction pipeline reads the archived session and writes new memories. The plugin's `after_compaction` hook is currently reserved; the extraction itself is driven by the server. **No `/compact`, no new memory files.**
+ - `captureMode: "semantic"` (default): server extraction pipeline filters all qualifying text.
+ - `captureMode: "keyword"`: only text matching trigger words (e.g. "remember", "preference") is considered.
+- **Auto-Recall (context-engine `assemble()`)**: before prompt context is assembled, the plugin queries OpenViking for relevant memories and injects them into context. Recall works even when there are no extracted memories yet — you just won't see anything come back.
+
+**Practical implication for testing**: if you write down a fact and immediately try to recall it without `/compact`, the plugin will only retrieve it as recent session context (archived messages), not as a long-term memory. To verify long-term memory cross-session, you must run `/compact` first.
## Available Tools
-### memory_recall — Search Memories
+These are the plugin tools the agent can call once installed.
-Searches long-term memories in OpenViking, returns relevant results.
+### `memory_recall` — Search Memories
| Parameter | Required | Description |
-|-----------|----------|-------------|
+|---|---|---|
| `query` | Yes | Search query text |
| `limit` | No | Maximum number of results (defaults to plugin config) |
-| `scoreThreshold` | No | Minimum relevance score 0-1 (defaults to plugin config) |
+| `scoreThreshold` | No | Minimum relevance score 0–1 (defaults to plugin config) |
| `targetUri` | No | Search scope URI (defaults to plugin config) |
-Example: User asks "What programming language did I say I like?"
-
-### memory_store — Manual Store
+Example: user asks "What programming language did I say I like?"
-Writes text to an OpenViking session and runs memory extraction.
+### `memory_store` — Manual Store
| Parameter | Required | Description |
-|-----------|----------|-------------|
+|---|---|---|
| `text` | Yes | Information text to store |
| `role` | No | Session role (default `user`) |
| `sessionId` | No | Existing OpenViking session ID |
-Example: User says "Remember my email is [email protected]"
-
-### memory_forget — Delete Memories
+Example: user says "Remember my email is [email protected]".
-Delete by exact URI, or search and delete.
+### `memory_forget` — Delete Memories
| Parameter | Required | Description |
-|-----------|----------|-------------|
+|---|---|---|
| `uri` | No | Exact memory URI (direct delete) |
| `query` | No | Search query (find then delete) |
| `targetUri` | No | Search scope URI |
| `limit` | No | Search limit (default 5) |
| `scoreThreshold` | No | Minimum relevance score |
-Example: User says "Forget my phone number"
+Example: user says "Forget my phone number".
-## Configuration
+## Configuration Schema
-The plugin connects to an OpenViking HTTP server. Start OpenViking first and keep it running:
+These are the keys under `plugins.entries.openviking.config` in `openclaw.json`. The setup wizard / `ov-install` sets the first few; the rest are tunables.
+
+| Field | Default | Description |
+|---|---|---|
+| `mode` | `"remote"` (forced by plugin) | Always remote in this skill. Don't set manually. |
+| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL. |
+| `apiKey` | — | API key. Optional if server has no auth. |
+| `agent_prefix` | `""` | Prefix for routing memories per agent. Letters / digits / `_` / `-`. |
+| `accountId` | — | Required when `apiKey` is a root key. |
+| `userId` | — | Required when `apiKey` is a root key. |
+| `targetUri` | `viking://user/memories` | Default search scope URI. |
+| `timeoutMs` | (plugin default) | HTTP timeout for OpenViking calls. |
+| `autoCapture` | `true` | Auto-archive turn messages to OpenViking session at `afterTurn` (extraction itself runs on `/compact`, not here). |
+| `captureMode` | `"semantic"` | Filter mode used by the server-side extraction pipeline: `semantic` or `keyword`. |
+| `captureMaxLength` | `24000` | Max text length per archived turn. |
+| `autoRecall` | `true` | Auto-recall and inject memories before reply. |
+| `recallLimit` | `6` | Max memories injected per recall. |
+| `recallScoreThreshold` | `0.15` | Min relevance score to inject. |
+| `recallMaxInjectedChars` | (plugin default) | Hard cap on injected character count. |
+| `recallPreferAbstract` | (plugin default) | Prefer abstract memories over raw. |
+| `recallTokenBudget` | (plugin default) | Token budget for injected memories. |
+| `isolateUserScopeByAgent` | (plugin default) | Multi-tenant scoping toggle. |
+| `isolateAgentScopeByUser` | (plugin default) | Multi-tenant scoping toggle. |
+| `agentScopeMode` | (plugin default) | Agent scope strategy. |
+| `bypassSessionPatterns` | — | Glob patterns for sessions skipped by capture. |
+| `ingestReplyAssist` | (plugin default) | Reply-assist ingestion toggle. |
+| `emitStandardDiagnostics` | (plugin default) | Verbose diagnostic logs. |
+| `logFindRequests` | (plugin default) | Log retrieval requests. |
+
+To change a value:
```bash
-openviking-server init
-openviking-server doctor
-openviking-server
+openclaw config set plugins.entries.openviking.config.<field> <value>
+openclaw gateway restart
```
-The default local plugin URL is `http://127.0.0.1:1933`. Check it with:
+## Multi-Tenant (Root API Keys)
+
+Some OpenViking deployments use a single **root** API key shared across tenants. In that case the plugin needs both `accountId` and `userId` so it can scope memories correctly. The setup wizard detects this automatically and returns:
+
+```
+Root API key detected. Missing: --account-id, --user-id
+```
+
+When you see this:
+
+1. Ask the user for both values (they come from the OpenViking admin).
+2. Retry STEP 7 with both flags:
```bash
-curl http://127.0.0.1:1933/health
+openclaw openviking setup --base-url BASE_URL --api-key API_KEY --account-id ACCOUNT_ID --user-id USER_ID --json
```
-| Field | Default | Description |
-|-------|---------|-------------|
-| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL |
-| `apiKey` | — | OpenViking API Key (optional) |
-| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. Interactive setup accepts only letters, digits, `_`, and `-`. If no agent ID is available, the plugin uses `main` |
-| `targetUri` | `viking://user/memories` | Default search scope |
-| `autoCapture` | `true` | Automatically capture memories |
-| `captureMode` | `semantic` | Capture mode: `semantic` / `keyword` |
-| `captureMaxLength` | `24000` | Maximum text length per capture |
-| `autoRecall` | `true` | Automatically recall and inject context |
-| `recallLimit` | `6` | Maximum memories injected during auto-recall |
-| `recallScoreThreshold` | `0.01` | Minimum relevance score for recall |
+A **user key** (issued per tenant) does not need these flags.
-## Daily Operations
+## Multi-Instance (`--workdir` / `OPENCLAW_STATE_DIR`)
+
+If the user runs multiple OpenClaw instances (e.g. testing several agents in parallel), each has its own state dir.
+
+To target a non-default instance:
+
+```bash
+npx -y openclaw-openviking-setup-helper@latest --workdir ~/.openclaw-second --base-url ... --api-key ...
+```
+`ov-install` writes a helper env file when the state dir is non-default:
+
+- Unix: `~/.openclaw/openviking.env` containing `export OPENCLAW_STATE_DIR='...'`
+- Windows: `~/.openclaw/openviking.env.bat` and `.ps1` setting the same variable
+
+Source it before running `openclaw` commands so they hit the correct state:
+
+**Unix:**
```bash
-# Start OpenViking server
-openviking-server
+source ~/.openclaw/openviking.env
+openclaw status
+```
-# Start or restart OpenClaw gateway
-openclaw gateway
+**Windows (PowerShell):**
+```powershell
+. "$HOME/.openclaw/openviking.env.ps1"
+openclaw status
+```
-# Check status
+Or pass `--workdir` directly to each `openclaw` invocation (note: not all `openclaw` subcommands honor `--workdir` consistently — when in doubt, prefer the env var).
+
+## Daily Operations
+
+```bash
+# Start or restart OpenClaw gateway after config changes
+openclaw gateway restart
+
+# Check overall status
openclaw status
+openclaw openviking status --json
+
+# Read current OpenViking slot
openclaw config get plugins.slots.contextEngine
-# Disable memory
+# Disable OpenViking memory (keep config, deactivate slot)
openclaw config set plugins.slots.contextEngine legacy
+openclaw gateway restart
-# Enable memory
+# Re-enable
openclaw config set plugins.slots.contextEngine openviking
+openclaw gateway restart
```
-Restart the gateway after changing the slot.
+## Uninstall
-## Multi-Instance Support
-
-If you have multiple OpenClaw instances, use `--workdir` to target a specific one:
+### Preferred: via OpenClaw plugin manager
```bash
-# Setup helper
-npx ./examples/openclaw-plugin/setup-helper --workdir ~/.openclaw-openclaw-second
+openclaw plugins uninstall openviking
+openclaw config set plugins.slots.contextEngine legacy
+openclaw gateway restart
+```
-# Manual config (prefix openclaw commands)
-OPENCLAW_STATE_DIR=~/.openclaw-openclaw-second openclaw config set ...
+### If installed through backup `ov-install`
+
+```bash
+npx -y openclaw-openviking-setup-helper@latest --uninstall
```
-## Troubleshooting
+This will:
+
+1. Stop the OpenClaw gateway.
+2. Back up `openclaw.json`.
+3. Remove all OpenViking plugin config from `openclaw.json` (`plugins.entries.openviking`, `plugins.allow`, `plugins.installs.openviking`, `plugins.slots.contextEngine`).
+4. Move the plugin directory to `disabled-extensions/` as backup.
+5. Remove the helper env files (`openviking.env`, `.bat`, `.ps1`).
+
+Add `--base-url dummy` for fully non-interactive mode (skips the confirmation prompt).
+
+### Manual
+
+```bash
+openclaw gateway stop
+openclaw config set plugins.slots.contextEngine legacy
+# Then edit ~/.openclaw/openclaw.json and remove openviking from
+# plugins.entries
+# plugins.allow
+# plugins.installs
+openclaw gateway restart
+```
-| Symptom | Cause | Fix |
-|---------|-------|-----|
-| `extracted 0 memories` | Wrong API Key or model name | Check server-side VLM and embedding configuration |
-| Cannot connect to OpenViking | `baseUrl` is wrong or service is down | Verify `baseUrl` and test connectivity |
-| Plugin not loaded | Slot not configured | Check `openclaw status` output |
-| Inaccurate recall | recallScoreThreshold too low | Increase threshold or adjust recallLimit |
+## Error Recovery Reference
+
+Match against actual stderr / JSON `error` strings.
+
+| Symptom (exact string) | Likely cause | Fix |
+|---|---|---|
+| `command not found: openclaw` | OpenClaw not installed | Stop. Ask user to install OpenClaw >= 2026.4.8. |
+| `command not found: node` / `'node' is not recognized` | Node missing | Stop. Ask user to install Node.js >= 22. |
+| `429` / `rate limit` / `Too Many Requests` from `plugins install` | ClawHub throttle | Switch to backup Path B (`ov-install`). |
+| `not logged in` / `please log in` from `plugins install` | Anonymous user hit limit | Switch to backup Path B (`ov-install`). |
+| `ECONNREFUSED` / `connection refused` on `BASE_URL/health` | Server not running | Server-not-ready handling in STEP 5. |
+| `ETIMEDOUT` on `BASE_URL/health` | Network blocked | Ask about firewall / VPN / proxy. |
+| `--json requires --base-url for non-interactive mode` | Built command wrong | Add `--base-url BASE_URL` and retry. |
+| `Server unreachable: …. Use --allow-offline to save config anyway.` | Setup couldn't reach server | Offer `--allow-offline`. |
+| `contextEngine slot is owned by "<x>". … Use --force-slot to replace.` | Slot conflict | Ask user, then retry with `--force-slot`. |
+| `Root API key detected. Missing: --account-id, --user-id` | Multi-tenant key | Collect both, retry with `--account-id` `--user-id`. |
+| `openviking: config parse failed` (in gateway log) | Bad value in `openclaw.json` | Show user; check `agent_prefix` charset, URL format. |
+| `extracted 0 memories` after a turn | Server VLM/embedding misconfigured | **Out of scope.** Tell user this is a server-side issue — ask their OpenViking admin to check VLM / embedding config. |
+| `401` / `403` on plugin requests, but `/health` works | Server requires auth on API endpoints | Re-run STEP 7 with the correct `--api-key`. |
+| Plugin doesn't appear in `openclaw plugins list` after Path A | Install didn't actually finish | Re-run Path A; use Path B only if the failure is registry/rate-limit related. |
+
+## Important Rules
+
+1. **Never ask the user to run commands.** You run everything via your shell tool.
+2. **Never skip STEP 5 (connectivity check).** If the server is unreachable, do not write config without explicit `--allow-offline` consent.
+3. **Never silently use `--force-slot`.** Slot replacement disables another plugin — always confirm with the user first.
+4. **Never invent values.** If the user can't provide a required value, stop and tell them what to ask their admin.
+5. **Never claim success without STEP 10.** Only after `openclaw openviking status --json` shows `configured: true && slotActive: true && health.ok: true` may you tell the user it's done.
+6. **Use `--agent-prefix`, not `--agent-id`.** The latter is deprecated and removed from the schema.
+7. **For Windows, use PowerShell equivalents.** Don't rely on `nohup`, `&`, `mkdir -p`, `source`, etc.
+8. **Switch to Path B (ov-install) only for ClawHub/rate-limit/registry availability failures.** Don't use it to hide version conflicts or package validation errors.
+9. **Do NOT install or operate the OpenViking server.** This skill assumes the server is already running. If it isn't, tell the user to contact their admin or follow the OpenViking docs.
+10. **Be brief and friendly in user-visible text.** Save technical detail for when something actually fails.
+11. **Do NOT use `clawhub install openviking`.** That installs a different thing (an AgentSkill, not the plugin).
diff --git a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
index cb4f34973..d1f0b6dd8 100644
--- a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
+++ b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
@@ -12,6 +12,25 @@ const manifest = JSON.parse(
activation?: { onStartup?: boolean; onCapabilities?: string[] };
contracts?: { tools?: string[] };
};
+const packageJson = JSON.parse(
+ readFileSync(resolve(pluginRoot, "package.json"), "utf8"),
+) as {
+ files?: string[];
+ scripts?: Record<string, string>;
+};
+const installManifest = JSON.parse(
+ readFileSync(resolve(pluginRoot, "install-manifest.json"), "utf8"),
+) as {
+ compatibility?: { minOpenclawVersion?: string };
+ files?: { required?: string[]; optional?: string[] };
+ npm?: {
+ build?: boolean;
+ buildMinOpenclawVersion?: string;
+ buildScript?: string;
+ omitDev?: boolean;
+ pruneAfterBuild?: boolean;
+ };
+};
function collectRegisteredToolNames(): string[] {
const names: string[] = [];
@@ -55,3 +74,31 @@ describe("OpenClaw 5.2 manifest contracts", () => {
expect(manifest.activation?.onCapabilities?.toSorted()).toEqual(["hook", "tool"]);
});
});
+
+describe("OpenClaw 5.5 package runtime contract", () => {
+ it("builds and publishes compiled runtime output for TypeScript entries", () => {
+ expect(packageJson.scripts?.build).toBe("tsc -p tsconfig.build.json");
+ expect(packageJson.scripts?.prepack).toBe("npm run build");
+ expect(packageJson.files).toContain("dist/");
+ expect(packageJson.files).toContain("install-manifest.json");
+ });
+
+ it("lets ov-install build runtime output from downloaded source", () => {
+ expect(installManifest.npm).toMatchObject({
+ build: true,
+ buildMinOpenclawVersion: "2026.5.3",
+ buildScript: "build",
+ omitDev: true,
+ pruneAfterBuild: true,
+ });
+ expect(installManifest.files?.required).toEqual(expect.arrayContaining([
+ "index.ts",
+ "commands/setup.ts",
+ "tsconfig.json",
+ "tsconfig.build.json",
+ "package.json",
+ "openclaw.plugin.json",
+ ]));
+ expect(installManifest.compatibility?.minOpenclawVersion).toBe("2026.4.8");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts b/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts
new file mode 100644
index 000000000..e30e897d8
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it, vi } from "vitest";
+
+import contextEnginePlugin from "../../index.js";
+
+function withOpenVikingEnv<T>(
+ values: Partial<Record<"OPENVIKING_API_KEY" | "OPENVIKING_BASE_URL", string | undefined>>,
+ fn: () => T,
+): T {
+ const previous = {
+ OPENVIKING_API_KEY: process.env.OPENVIKING_API_KEY,
+ OPENVIKING_BASE_URL: process.env.OPENVIKING_BASE_URL,
+ };
+ try {
+ for (const [key, value] of Object.entries(values)) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ return fn();
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ }
+}
+
+function createPluginApi(pluginConfig: Record<string, unknown>) {
+ return {
+ pluginConfig,
+ logger: {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ },
+ registerTool: vi.fn(),
+ registerCommand: vi.fn(),
+ registerService: vi.fn(),
+ registerContextEngine: vi.fn(),
+ on: vi.fn(),
+ };
+}
+
+describe("plugin registration", () => {
+ it("keeps runtime enabled for default no-key trusted deployments", () => {
+ withOpenVikingEnv(
+ {
+ OPENVIKING_API_KEY: undefined,
+ OPENVIKING_BASE_URL: undefined,
+ },
+ () => {
+ const api = createPluginApi({});
+
+ contextEnginePlugin.register(api as any);
+
+ expect(api.registerTool).toHaveBeenCalled();
+ expect(api.registerContextEngine).toHaveBeenCalledWith("openviking", expect.any(Function));
+ expect(api.registerService).toHaveBeenCalledWith(expect.objectContaining({ id: "openviking" }));
+ expect(api.logger.warn).not.toHaveBeenCalledWith(
+ expect.stringContaining("tools and context-engine are disabled"),
+ );
+ },
+ );
+ });
+
+ it("keeps runtime enabled when only OPENVIKING_BASE_URL is configured", () => {
+ withOpenVikingEnv(
+ {
+ OPENVIKING_API_KEY: undefined,
+ OPENVIKING_BASE_URL: "http://127.0.0.1:1933",
+ },
+ () => {
+ const api = createPluginApi({});
+
+ contextEnginePlugin.register(api as any);
+
+ expect(api.registerTool).toHaveBeenCalled();
+ expect(api.registerContextEngine).toHaveBeenCalledWith("openviking", expect.any(Function));
+ },
+ );
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/setup-cli.test.ts b/examples/openclaw-plugin/tests/ut/setup-cli.test.ts
new file mode 100644
index 000000000..e78c2f365
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/setup-cli.test.ts
@@ -0,0 +1,303 @@
+import { describe, expect, it, beforeEach, afterEach } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import * as os from "node:os";
+import { fileURLToPath } from "node:url";
+
+import { __test__ } from "../../commands/setup.js";
+
+const {
+ parseVersionTuple,
+ compareVersions,
+ checkVersionCompatibility,
+ isLegacyLocalMode,
+ activateContextEngineSlot,
+ isContextEngineSlotActive,
+ ensureInstallRecord,
+ findPluginPackageRoot,
+ setExitCodeOnFailure,
+} = __test__;
+
+const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
+let tmpDir: string;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "ov-setup-test-"));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function writeTmpConfig(data: Record<string, unknown>): string {
+ const p = path.join(tmpDir, "openclaw.json");
+ fs.writeFileSync(p, JSON.stringify(data, null, 2), "utf-8");
+ return p;
+}
+
+function readTmpConfig(configPath: string): Record<string, unknown> {
+ return JSON.parse(fs.readFileSync(configPath, "utf-8"));
+}
+
+// ---------------------------------------------------------------------------
+// parseVersionTuple
+// ---------------------------------------------------------------------------
+describe("parseVersionTuple", () => {
+ it("parses semver string", () => {
+ expect(parseVersionTuple("1.2.3")).toEqual([1, 2, 3]);
+ });
+
+ it("strips leading v", () => {
+ expect(parseVersionTuple("v0.5.0")).toEqual([0, 5, 0]);
+ });
+
+ it("strips pre-release suffix", () => {
+ expect(parseVersionTuple("0.5.0-beta.1")).toEqual([0, 5, 0]);
+ });
+
+ it("handles two-part version", () => {
+ expect(parseVersionTuple("2026.4")).toEqual([2026, 4]);
+ });
+
+ it("returns null for non-numeric input", () => {
+ expect(parseVersionTuple("latest")).toBeNull();
+ });
+
+ it("treats empty string as [0] (Number('') === 0)", () => {
+ expect(parseVersionTuple("")).toEqual([0]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// compareVersions
+// ---------------------------------------------------------------------------
+describe("compareVersions", () => {
+ it("equal versions return 0", () => {
+ expect(compareVersions([1, 2, 3], [1, 2, 3])).toBe(0);
+ });
+
+ it("greater major returns positive", () => {
+ expect(compareVersions([2, 0, 0], [1, 9, 9])).toBeGreaterThan(0);
+ });
+
+ it("lesser minor returns negative", () => {
+ expect(compareVersions([1, 0, 0], [1, 1, 0])).toBeLessThan(0);
+ });
+
+ it("handles different length tuples", () => {
+ expect(compareVersions([1, 2], [1, 2, 0])).toBe(0);
+ expect(compareVersions([1, 2], [1, 2, 1])).toBeLessThan(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// checkVersionCompatibility
+// ---------------------------------------------------------------------------
+describe("checkVersionCompatibility", () => {
+ it('returns "compatible" for in-range version', () => {
+ expect(checkVersionCompatibility("0.5.0")).toBe("compatible");
+ });
+
+ it('returns "unknown" for empty version', () => {
+ expect(checkVersionCompatibility("")).toBe("unknown");
+ });
+
+ it('returns "unknown" for non-parseable version', () => {
+ expect(checkVersionCompatibility("not-a-version")).toBe("unknown");
+ });
+
+ it('returns "server_too_old" below the manifest minimum version', () => {
+ expect(checkVersionCompatibility("0.1.0")).toBe("server_too_old");
+ });
+});
+
+describe("setup runtime package metadata", () => {
+ it("resolves the package root from source and compiled command locations", () => {
+ expect(findPluginPackageRoot(path.join(pluginRoot, "commands"))).toBe(pluginRoot);
+ expect(findPluginPackageRoot(path.join(pluginRoot, "dist", "commands"))).toBe(pluginRoot);
+ });
+});
+
+describe("setup command exit status", () => {
+ it("marks failed setup results as process failures", () => {
+ const previousExitCode = process.exitCode;
+ try {
+ process.exitCode = undefined;
+ setExitCodeOnFailure({ success: false });
+ expect(process.exitCode).toBe(1);
+ } finally {
+ process.exitCode = previousExitCode;
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isLegacyLocalMode
+// ---------------------------------------------------------------------------
+describe("isLegacyLocalMode", () => {
+ it("returns true for mode=local", () => {
+ expect(isLegacyLocalMode({ mode: "local" })).toBe(true);
+ });
+
+ it("returns true when mode is missing", () => {
+ expect(isLegacyLocalMode({})).toBe(true);
+ });
+
+ it("returns false for mode=remote", () => {
+ expect(isLegacyLocalMode({ mode: "remote" })).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// activateContextEngineSlot + isContextEngineSlotActive
+// ---------------------------------------------------------------------------
+describe("activateContextEngineSlot", () => {
+ it("activates slot on fresh config", () => {
+ const p = writeTmpConfig({});
+ const result = activateContextEngineSlot(p);
+ expect(result.activated).toBe(true);
+ expect(result.replaced).toBe(false);
+ expect(isContextEngineSlotActive(p)).toBe(true);
+ });
+
+ it("no-ops when slot already set to openviking", () => {
+ const p = writeTmpConfig({
+ plugins: { slots: { contextEngine: "openviking" } },
+ });
+ const result = activateContextEngineSlot(p);
+ expect(result.activated).toBe(false);
+ expect(result.replaced).toBe(false);
+ });
+
+ it("refuses to overwrite another plugin without force", () => {
+ const p = writeTmpConfig({
+ plugins: { slots: { contextEngine: "other-plugin" } },
+ });
+ const result = activateContextEngineSlot(p);
+ expect(result.activated).toBe(false);
+ expect(result.previousOwner).toBe("other-plugin");
+ expect(result.replaced).toBe(false);
+ const cfg = readTmpConfig(p);
+ expect((cfg.plugins as Record<string, unknown>).slots).toEqual({
+ contextEngine: "other-plugin",
+ });
+ });
+
+ it("overwrites another plugin with force=true", () => {
+ const p = writeTmpConfig({
+ plugins: { slots: { contextEngine: "other-plugin" } },
+ });
+ const result = activateContextEngineSlot(p, true);
+ expect(result.activated).toBe(true);
+ expect(result.previousOwner).toBe("other-plugin");
+ expect(result.replaced).toBe(true);
+ expect(isContextEngineSlotActive(p)).toBe(true);
+ });
+
+ it("creates config file when it does not exist", () => {
+ const p = path.join(tmpDir, "nonexistent.json");
+ const result = activateContextEngineSlot(p);
+ expect(result.activated).toBe(true);
+ expect(fs.existsSync(p)).toBe(true);
+ });
+});
+
+describe("isContextEngineSlotActive", () => {
+ it("returns false for empty config", () => {
+ const p = writeTmpConfig({});
+ expect(isContextEngineSlotActive(p)).toBe(false);
+ });
+
+ it("returns false for nonexistent file", () => {
+ const p = path.join(tmpDir, "missing.json");
+ expect(isContextEngineSlotActive(p)).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// ensureInstallRecord
+// ---------------------------------------------------------------------------
+describe("ensureInstallRecord", () => {
+ it("creates allow entries when missing", () => {
+ const plugins: Record<string, unknown> = {};
+ ensureInstallRecord(plugins);
+ expect(plugins.installs).toBeUndefined();
+ expect(plugins.allow).toEqual(["openviking"]);
+ });
+
+ it("preserves unrelated installs and allow entries", () => {
+ const plugins: Record<string, unknown> = {
+ installs: { mem0: { source: "npm", spec: "@mem0/openclaw-mem0" } },
+ allow: ["mem0"],
+ };
+ ensureInstallRecord(plugins);
+ expect((plugins.installs as Record<string, unknown>).mem0).toEqual({
+ source: "npm",
+ spec: "@mem0/openclaw-mem0",
+ });
+ expect((plugins.installs as Record<string, unknown>).openviking).toBeUndefined();
+ expect(plugins.allow).toEqual(["mem0", "openviking"]);
+ });
+
+ it("removes stale openviking install records and does not duplicate allow entries", () => {
+ const plugins: Record<string, unknown> = {
+ installs: { openviking: { npm: "@openclaw/openviking" } },
+ allow: ["openviking"],
+ };
+ ensureInstallRecord(plugins);
+ expect((plugins.installs as Record<string, unknown>).openviking).toBeUndefined();
+ expect((plugins.allow as string[]).filter((x) => x === "openviking")).toHaveLength(1);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Slot protection: non-interactive default behavior
+// (activateContextEngineSlot with force=false should NOT overwrite)
+// ---------------------------------------------------------------------------
+describe("activateContextEngineSlot — non-interactive default (force=false)", () => {
+ it("activates slot on empty config (no conflict)", () => {
+ const p = writeTmpConfig({});
+ const result = activateContextEngineSlot(p, false);
+ expect(result.activated).toBe(true);
+ expect(result.replaced).toBe(false);
+ expect(isContextEngineSlotActive(p)).toBe(true);
+ });
+
+ it("blocks when slot is owned by another plugin", () => {
+ const p = writeTmpConfig({
+ plugins: { slots: { contextEngine: "mem0" } },
+ });
+ const result = activateContextEngineSlot(p, false);
+ expect(result.activated).toBe(false);
+ expect(result.previousOwner).toBe("mem0");
+ expect(result.replaced).toBe(false);
+ const cfg = readTmpConfig(p);
+ expect((cfg.plugins as Record<string, unknown>).slots).toEqual({
+ contextEngine: "mem0",
+ });
+ });
+
+ it("replaces when force=true is passed", () => {
+ const p = writeTmpConfig({
+ plugins: { slots: { contextEngine: "mem0" } },
+ });
+ const result = activateContextEngineSlot(p, true);
+ expect(result.activated).toBe(true);
+ expect(result.previousOwner).toBe("mem0");
+ expect(result.replaced).toBe(true);
+ expect(isContextEngineSlotActive(p)).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// checkVersionCompatibility edge cases
+// ---------------------------------------------------------------------------
+describe("checkVersionCompatibility — edge cases", () => {
+ it("pre-release suffix is stripped before comparison", () => {
+ expect(checkVersionCompatibility("0.5.0-beta.1")).toBe("compatible");
+ });
+
+ it("handles large year-based version numbers", () => {
+ expect(checkVersionCompatibility("2026.4.33")).toBe("compatible");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/text-utils.test.ts b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
index 4dc93431c..ddf1ed333 100644
--- a/examples/openclaw-plugin/tests/ut/text-utils.test.ts
+++ b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
@@ -154,18 +154,25 @@ describe("extractNewTurnTexts", () => {
expect(texts[0]).toContain("[user]: hello");
});
- it("preserves toolUse content from assistant", () => {
+ it("preserves assistant text and associates toolUse with toolResult", () => {
const messages = [
{
role: "assistant",
content: [
{ type: "text", text: "Let me search" },
- { type: "toolUse", name: "grep", input: { pattern: "TODO" } },
+ { type: "toolUse", id: "call_1", name: "grep", input: { pattern: "TODO" } },
],
},
+ {
+ role: "toolResult",
+ toolName: "grep",
+ toolCallId: "call_1",
+ content: [{ type: "text", text: "found 3 matches" }],
+ },
];
const { texts } = extractNewTurnTexts(messages, 0);
- expect(texts.some((t) => t.includes("[toolUse: grep]"))).toBe(true);
+ expect(texts.some((t) => t.includes("[assistant]: Let me search"))).toBe(true);
+ expect(texts.some((t) => t.includes("[grep result]"))).toBe(true);
expect(texts.some((t) => t.includes("TODO"))).toBe(true);
});
diff --git a/examples/openclaw-plugin/text-utils.ts b/examples/openclaw-plugin/text-utils.ts
index 7babeb904..b83fe340a 100644
--- a/examples/openclaw-plugin/text-utils.ts
+++ b/examples/openclaw-plugin/text-utils.ts
@@ -19,7 +19,7 @@ const SENDER_METADATA_BLOCK_RE = /Sender\s*\([^)]*\)\s*:\s*```[\s\S]*?```/gi;
const FENCED_JSON_BLOCK_RE = /```json\s*([\s\S]*?)```/gi;
const METADATA_JSON_KEY_RE =
/"(session|sessionid|sessionkey|conversationid|channel|sender|userid|agentid|timestamp|timezone)"\s*:/gi;
-const LEADING_TIMESTAMP_PREFIX_RE = /^\s*(?!\[\[)\[(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*\s+)?(?:\d{4}[-/]\d{2}[-/]\d{2}|\d{2}[-/]\d{2}[-/]\d{2,4})(?:\s+\d{1,2}:\d{2}(?::\d{2})?(?:\s*[A-Z]{1,5}(?:[+-]\d{1,2})?)?)?\s*\]\s*/i;
+const LEADING_TIMESTAMP_PREFIX_RE = /^\s*(?!\[\[)\[(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*\s+)?(?:\d{4}[-/]\d{2}[-/]\d{2}|\d{2}[-/]\d{2}[-/]\d{2,4})(?:[T\s]\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{1,2}(?::\d{2})?)?(?:\s*[A-Z]{1,5}(?:[+-]\d{1,2})?)?)?\s*\]\s*/i;
const COMPACTED_SYSTEM_MSG_RE = /^System:\s*\[.*?\]\s*Compacted\s*(.+)$/i;
const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;
@@ -69,6 +69,7 @@ export function sanitizeUserTextForCapture(text: string): string {
looksLikeMetadataJsonBlock(String(inner ?? "")) ? " " : full,
)
.replace(LEADING_TIMESTAMP_PREFIX_RE, "")
+ .replace(SUBAGENT_CONTEXT_RE, "")
.replace(/\u0000/g, "")
.replace(/\s+/g, " ")
.trim();
@@ -495,3 +496,29 @@ export function extractLatestUserText(messages: unknown[] | undefined): string {
}
return "";
}
+
+/**
+ * Backward-compatible wrapper around extractNewTurnMessages.
+ * Returns flat text strings in the legacy `[role]: text` format.
+ * @deprecated Use extractNewTurnMessages for structured output.
+ */
+export function extractNewTurnTexts(
+ messages: unknown[],
+ startIndex: number,
+): { texts: string[]; newCount: number } {
+ const { messages: extracted, newCount } = extractNewTurnMessages(messages, startIndex);
+ const texts: string[] = [];
+ for (const msg of extracted) {
+ for (const part of msg.parts) {
+ if (part.type === "text") {
+ texts.push(`[${msg.role}]: ${part.text}`);
+ } else if (part.type === "tool") {
+ if (part.toolInput && Object.keys(part.toolInput).length > 0) {
+ texts.push(`[toolUse: ${part.toolName}] ${JSON.stringify(part.toolInput)}`);
+ }
+ texts.push(`[${part.toolName} result]: ${part.toolOutput}`);
+ }
+ }
+ }
+ return { texts, newCount };
+}
diff --git a/examples/openclaw-plugin/tsconfig.build.json b/examples/openclaw-plugin/tsconfig.build.json
new file mode 100644
index 000000000..4b52ba731
--- /dev/null
+++ b/examples/openclaw-plugin/tsconfig.build.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "outDir": "dist",
+ "rootDir": "."
+ },
+ "exclude": [
+ "dist",
+ "node_modules",
+ "tests",
+ "__tests__",
+ "vitest.config.ts"
+ ]
+}
diff --git a/examples/openclaw-plugin/tsconfig.json b/examples/openclaw-plugin/tsconfig.json
index 158c20095..0e7ce7866 100644
--- a/examples/openclaw-plugin/tsconfig.json
+++ b/examples/openclaw-plugin/tsconfig.json
@@ -8,5 +8,5 @@
"skipLibCheck": true,
"types": ["node"]
},
- "include": ["*.ts"]
+ "include": ["*.ts", "commands/**/*.ts"]
}