Skip to content

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

refactor(openclaw-plugin): route setup CLI network probes through the probe service (#4731)

now-ing70027e68a06b
diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.ts
index b9d64f7b8..7279cc696 100644
--- a/examples/openclaw-plugin/commands/setup.ts
+++ b/examples/openclaw-plugin/commands/setup.ts
@@ -6,9 +6,13 @@ import { fileURLToPath } from "node:url";
import { getEnv } from "../runtime-utils.js";
import {
cleanOpenVikingRequestHeaders,
- resolveOpenVikingRequestHeaders,
type OpenVikingRequestHeaders,
} from "../request-headers.js";
+import {
+ createSetupNetworkProbes,
+ type SetupApiKeyProbeResult,
+ type SetupHealthResult,
+} from "../services/setup/probe-service.js";
const HOME = os.homedir();
const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");
@@ -269,14 +273,7 @@ function ask(rl: readline.Interface, prompt: string, defaultValue = ""): Promise
type VersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";
-type HealthResult = {
- ok: boolean;
- version: string;
- error: string;
- compatibility: VersionCompatibility;
- pluginVersion: string;
- compatRange: string;
-};
+type HealthResult = SetupHealthResult;
function parseVersionTuple(v: string): number[] | null {
const cleaned = v.replace(/^v/i, "").split("-")[0];
@@ -317,132 +314,13 @@ function formatCompatRange(): string {
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,
- configuredHeaders?: OpenVikingRequestHeaders,
-): 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 configuredRequestHeaders = resolveOpenVikingRequestHeaders({ headers: configuredHeaders });
- const headers: Record<string, string> = {};
- headers["X-API-Key"] = apiKey;
- Object.assign(headers, configuredRequestHeaders);
- 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__",
- ...configuredRequestHeaders,
- };
- 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);
- }
-}
+type ApiKeyProbeResult = SetupApiKeyProbeResult;
-async function checkServiceHealth(
- baseUrl: string,
- apiKey?: string,
- configuredHeaders?: OpenVikingRequestHeaders,
-): Promise<HealthResult> {
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 10_000);
- try {
- const configuredRequestHeaders = resolveOpenVikingRequestHeaders({ headers: configuredHeaders });
- const headers: Record<string, string> = {};
- if (apiKey) {
- headers["X-API-Key"] = apiKey;
- }
- Object.assign(headers, configuredRequestHeaders);
- const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/health`, {
- headers,
- signal: controller.signal,
- });
- if (response.ok) {
- try {
- const data = await response.json() as Record<string, unknown>;
- 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: "", compatibility: "unknown", pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
- }
- }
- 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), compatibility: "unknown", pluginVersion: PLUGIN_VERSION, compatRange: formatCompatRange() };
- } finally {
- clearTimeout(timeoutId);
- }
-}
+const setupProbes = createSetupNetworkProbes({
+ pluginVersion: PLUGIN_VERSION,
+ compatRange: formatCompatRange(),
+ checkVersionCompatibility,
+});
function readOpenClawConfig(configPath: string): Record<string, unknown> {
if (!fs.existsSync(configPath)) return {};
@@ -813,7 +691,7 @@ async function runRemoteCheck(
const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;
const headers = nonEmptyOpenVikingRequestHeaders(existing.headers);
console.log(tr(zh, `Testing connectivity to ${baseUrl}...`, `正在测试连接 ${baseUrl}...`));
- const health = await checkServiceHealth(baseUrl, apiKey, headers);
+ const health = await setupProbes.checkServiceHealth(baseUrl, apiKey, headers);
if (health.ok) {
const ver = health.version ? ` (version: ${health.version})` : "";
console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
@@ -847,7 +725,7 @@ async function setupNonInteractive(
}
// Phase 1: validate connectivity and key type BEFORE writing config
- const health = await checkServiceHealth(baseUrl, apiKey);
+ const health = await setupProbes.checkServiceHealth(baseUrl, apiKey);
if (!health.ok && !allowOffline) {
return {
@@ -860,7 +738,7 @@ async function setupNonInteractive(
};
}
- const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;
+ const keyProbe = health.ok ? await setupProbes.probeApiKeyType(baseUrl, apiKey) : undefined;
if (keyProbe?.keyType === "root_key" && (!accountId || !userId)) {
const missing: string[] = [];
@@ -996,8 +874,8 @@ async function getStatus(configPath: string): Promise<StatusResult> {
const baseUrl = String(existing.baseUrl ?? DEFAULT_REMOTE_URL);
const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;
const headers = nonEmptyOpenVikingRequestHeaders(existing.headers);
- const health = await checkServiceHealth(baseUrl, apiKey, headers);
- const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey, headers) : undefined;
+ const health = await setupProbes.checkServiceHealth(baseUrl, apiKey, headers);
+ const keyProbe = health.ok ? await setupProbes.probeApiKeyType(baseUrl, apiKey, headers) : undefined;
const peerPrefix = resolveExistingPeerPrefix(existing);
return {
@@ -1119,7 +997,7 @@ async function setupRemote(
if (apiKey) {
console.log(tr(zh, " Detecting API key type...", " 正在检测 API Key 类型..."));
- const probe = await probeApiKeyType(baseUrl, apiKey, headers);
+ const probe = await setupProbes.probeApiKeyType(baseUrl, apiKey, headers);
if (probe.keyType === "root_key") {
console.log(tr(zh,
" ⚠ Root API key detected. accountId and userId are required.",
@@ -1140,7 +1018,7 @@ async function setupRemote(
console.log("");
console.log(tr(zh, `Testing connectivity to ${baseUrl}...`, `正在测试连接 ${baseUrl}...`));
- const health = await checkServiceHealth(baseUrl, apiKey || undefined, headers);
+ const health = await setupProbes.checkServiceHealth(baseUrl, apiKey || undefined, headers);
if (health.ok) {
const ver = health.version ? ` (version: ${health.version})` : "";
console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
@@ -1204,7 +1082,6 @@ export const __test__ = {
checkVersionCompatibility,
parseVersionTuple,
compareVersions,
- probeApiKeyType,
ensureInstallRecord,
findPluginPackageRoot,
readCompatRangeFromManifest,