Skip to content

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

fix(openclaw-plugin): support config headers (#3044)

Carateffee1a11b1ba3de5
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 386135ad1..6c87aaf1a 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -41,6 +41,7 @@ function userSessionUri(sessionId: string): string {
export type OpenVikingClientOptions = {
transport?: HttpTransport;
+ headers?: Record<string, string>;
resourcePackager?: ResourcePackager;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
@@ -254,6 +255,7 @@ async function cleanupUploadTempPath(path?: string): Promise<void> {
export class OpenVikingClient {
private readonly transport: HttpTransport;
+ private readonly configuredHeaders: Record<string, string>;
private readonly now: () => number;
private readonly sleep: (ms: number) => Promise<void>;
private readonly resourcePackager: ResourcePackager;
@@ -277,6 +279,7 @@ export class OpenVikingClient {
? optionsOrLegacyUserScope
: (legacyOptions ?? {});
this.transport = options.transport ?? defaultHttpTransport;
+ this.configuredHeaders = options.headers ?? {};
this.now = options.now ?? Date.now;
this.sleep = options.sleep ?? sleep;
this.resourcePackager = options.resourcePackager ?? defaultResourcePackager;
@@ -357,6 +360,11 @@ export class OpenVikingClient {
if (actorPeerHeader) {
headers.set("X-OpenViking-Actor-Peer", actorPeerHeader);
}
+ for (const [key, value] of Object.entries(this.configuredHeaders)) {
+ if (key && typeof value === "string" && value.trim()) {
+ headers.set(key, value);
+ }
+ }
if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.ts
index 732da3721..576c642a5 100644
--- a/examples/openclaw-plugin/commands/setup.ts
+++ b/examples/openclaw-plugin/commands/setup.ts
@@ -4,6 +4,11 @@ import * as path from "node:path";
import * as readline from "node:readline";
import { fileURLToPath } from "node:url";
import { getEnv } from "../runtime-utils.js";
+import {
+ cleanOpenVikingRequestHeaders,
+ resolveOpenVikingRequestHeaders,
+ type OpenVikingRequestHeaders,
+} from "../request-headers.js";
const HOME = os.homedir();
const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");
@@ -58,6 +63,7 @@ const PLUGIN_VERSION = readPluginVersion();
const { min: COMPATIBLE_SERVER_MIN, max: COMPATIBLE_SERVER_MAX } = readCompatRangeFromManifest();
const CONFIG_KEYS_TO_PRESERVE = [
"targetUri",
+ "headers",
"timeoutMs",
"autoCapture",
"captureMode",
@@ -107,6 +113,11 @@ function maskKey(key: string): string {
return `${key.slice(0, 4)}...${key.slice(-4)}`;
}
+function nonEmptyOpenVikingRequestHeaders(value: unknown): OpenVikingRequestHeaders | undefined {
+ const headers = cleanOpenVikingRequestHeaders(value);
+ return Object.keys(headers).length > 0 ? headers : undefined;
+}
+
function isValidPeerPrefixInput(value: string): boolean {
const trimmed = value.trim();
return !trimmed || /^[a-zA-Z0-9_-]+$/.test(trimmed);
@@ -301,14 +312,21 @@ type ApiKeyProbeResult = {
detail: string;
};
-async function probeApiKeyType(baseUrl: string, apiKey?: string): Promise<ApiKeyProbeResult> {
+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 headers: Record<string, string> = { "X-API-Key": apiKey };
+ 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,
@@ -347,6 +365,7 @@ async function probeApiKeyType(baseUrl: string, apiKey?: string): Promise<ApiKey
"X-API-Key": apiKey,
"X-OpenViking-Account": "__probe__",
"X-OpenViking-User": "__probe__",
+ ...configuredRequestHeaders,
};
const probe2 = await fetch(sessionsUrl, {
headers: probeHeaders,
@@ -376,12 +395,20 @@ async function probeApiKeyType(baseUrl: string, apiKey?: string): Promise<ApiKey
}
}
-async function checkServiceHealth(baseUrl: string, apiKey?: string): Promise<HealthResult> {
+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;
+ if (apiKey) {
+ headers["X-API-Key"] = apiKey;
+ }
+ Object.assign(headers, configuredRequestHeaders);
const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/health`, {
headers,
signal: controller.signal,
@@ -772,8 +799,9 @@ async function runRemoteCheck(
): Promise<void> {
const baseUrl = String(existing.baseUrl ?? DEFAULT_REMOTE_URL);
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);
+ const health = await checkServiceHealth(baseUrl, apiKey, headers);
if (health.ok) {
const ver = health.version ? ` (version: ${health.version})` : "";
console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
@@ -955,8 +983,9 @@ async function getStatus(configPath: string): Promise<StatusResult> {
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 headers = nonEmptyOpenVikingRequestHeaders(existing.headers);
+ const health = await checkServiceHealth(baseUrl, apiKey, headers);
+ const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey, headers) : undefined;
const peerPrefix = resolveExistingPeerPrefix(existing);
return {
@@ -1068,6 +1097,7 @@ async function setupRemote(
const defaultApiKey = existing?.apiKey ? String(existing.apiKey) : "";
const defaultPeerRole = resolveExistingPeerRole(existing);
const defaultPeerPrefix = resolveExistingPeerPrefix(existing);
+ const headers = nonEmptyOpenVikingRequestHeaders(existing?.headers);
const baseUrl = await q(tr(zh, "OpenViking server URL", "OpenViking 服务器地址"), defaultUrl);
const apiKey = await q(tr(zh, "API Key (optional)", "API Key(可选)"), defaultApiKey);
@@ -1077,7 +1107,7 @@ async function setupRemote(
if (apiKey) {
console.log(tr(zh, " Detecting API key type...", " 正在检测 API Key 类型..."));
- const probe = await probeApiKeyType(baseUrl, apiKey);
+ const probe = await probeApiKeyType(baseUrl, apiKey, headers);
if (probe.keyType === "root_key") {
console.log(tr(zh,
" ⚠ Root API key detected. accountId and userId are required.",
@@ -1098,7 +1128,7 @@ async function setupRemote(
console.log("");
console.log(tr(zh, `Testing connectivity to ${baseUrl}...`, `正在测试连接 ${baseUrl}...`));
- const health = await checkServiceHealth(baseUrl, apiKey || undefined);
+ const health = await checkServiceHealth(baseUrl, apiKey || undefined, headers);
if (health.ok) {
const ver = health.version ? ` (version: ${health.version})` : "";
console.log(` ✓ ${tr(zh, `Connected successfully${ver}`, `连接成功${ver}`)}`);
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index dbbc03182..1f86c9d2a 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -8,6 +8,8 @@ export type MemoryOpenVikingConfig = {
peer_role?: "none" | "assistant" | "person";
peer_prefix?: string;
apiKey?: string;
+ /** Optional HTTP headers merged into every OpenViking request. */
+ headers?: Record<string, string>;
/** Advanced option. Only needed when explicitly sending tenant identity headers. With a user key the server derives identity from the key. */
accountId?: string;
/** Advanced option. Only needed when explicitly sending tenant identity headers. */
@@ -288,6 +290,24 @@ function toRecord(value: unknown): Record<string, unknown> {
: {};
}
+function toStringRecord(value: unknown, label: string): Record<string, string> {
+ if (value === undefined || value === null) {
+ return {};
+ }
+ if (typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`${label} must be an object`);
+ }
+ const record = value as Record<string, unknown>;
+ const out: Record<string, string> = {};
+ for (const [key, val] of Object.entries(record)) {
+ if (typeof val !== "string") {
+ throw new Error(`${label}.${key} must be a string`);
+ }
+ out[key] = val;
+ }
+ return out;
+}
+
function expandToolSelectors(value: unknown, fallback: string[], label: string): OpenVikingToolName[] {
const entries = toStringArray(value, fallback);
const seen = new Set<OpenVikingToolName>();
@@ -385,6 +405,7 @@ export const memoryOpenVikingConfigSchema = {
"peer_prefix",
"serverAuthMode",
"apiKey",
+ "headers",
"accountId",
"userId",
"targetUri",
@@ -488,6 +509,7 @@ export const memoryOpenVikingConfigSchema = {
peer_role: peerRole,
peer_prefix: peerPrefix,
apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",
+ headers: toStringRecord(cfg.headers, "openviking config headers"),
accountId,
userId,
targetUri: typeof cfg.targetUri === "string" ? cfg.targetUri : DEFAULT_TARGET_URI,
@@ -658,6 +680,11 @@ export const memoryOpenVikingConfigSchema = {
placeholder: "${OPENVIKING_API_KEY}",
help: "Optional API key for OpenViking server",
},
+ headers: {
+ label: "Headers",
+ advanced: true,
+ help: "Optional HTTP headers merged into every OpenViking request.",
+ },
accountId: {
label: "Account ID",
placeholder: "(derived from API key)",
diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.json
index 23a8c6969..70bff3805 100644
--- a/examples/openclaw-plugin/install-manifest.json
+++ b/examples/openclaw-plugin/install-manifest.json
@@ -20,6 +20,7 @@
"tool-call-id.ts",
"session-transcript-repair.ts",
"runtime-utils.ts",
+ "request-headers.ts",
"recall-trace.ts",
"query-config.ts",
"adapters/",
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index e91181bd4..b5723f853 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -98,6 +98,11 @@
"placeholder": "${OPENVIKING_API_KEY}",
"help": "Optional API key for OpenViking server"
},
+ "headers": {
+ "label": "Headers",
+ "advanced": true,
+ "help": "Optional HTTP headers merged into every OpenViking request."
+ },
"accountId": {
"label": "Account ID",
"placeholder": "(derived from API key)",
@@ -287,6 +292,12 @@
"apiKey": {
"type": "string"
},
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
"accountId": {
"type": "string"
},
diff --git a/examples/openclaw-plugin/plugin/openviking-client-runtime.ts b/examples/openclaw-plugin/plugin/openviking-client-runtime.ts
index c3cd4df3f..5ebbed654 100644
--- a/examples/openclaw-plugin/plugin/openviking-client-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-client-runtime.ts
@@ -1,5 +1,6 @@
import { OpenVikingClient } from "../client.js";
import type { HttpTransport } from "../adapters/http-transport.js";
+import { resolveOpenVikingRequestHeaders } from "../request-headers.js";
type Logger = {
info: (message: string) => void;
@@ -13,6 +14,7 @@ type ClientRuntimeConfig = {
timeoutMs: number;
accountId?: string;
userId?: string;
+ headers?: Record<string, string>;
logFindRequests: boolean;
};
@@ -61,7 +63,12 @@ export function createOpenVikingClientRuntime(options: {
cfg.accountId,
cfg.userId,
routingDebugLog,
- { transport: options.transport },
+ {
+ transport: options.transport,
+ headers: resolveOpenVikingRequestHeaders({
+ headers: cfg.headers,
+ }),
+ },
),
);
diff --git a/examples/openclaw-plugin/request-headers.ts b/examples/openclaw-plugin/request-headers.ts
new file mode 100644
index 000000000..ac3a4c646
--- /dev/null
+++ b/examples/openclaw-plugin/request-headers.ts
@@ -0,0 +1,29 @@
+export type OpenVikingRequestHeaders = Record<string, string>;
+
+export type ResolveOpenVikingRequestHeadersOptions = {
+ headers?: unknown;
+};
+
+export function resolveOpenVikingRequestHeaders(
+ options: ResolveOpenVikingRequestHeadersOptions = {},
+): OpenVikingRequestHeaders {
+ return cleanOpenVikingRequestHeaders(options.headers);
+}
+
+export function cleanOpenVikingRequestHeaders(headers: unknown): OpenVikingRequestHeaders {
+ if (headers === undefined || headers === null) {
+ return {};
+ }
+ if (typeof headers !== "object" || Array.isArray(headers)) {
+ throw new Error("openviking request headers must be an object");
+ }
+
+ const out: OpenVikingRequestHeaders = {};
+ for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {
+ if (typeof value !== "string") {
+ throw new Error(`openviking request header ${key} must be a string`);
+ }
+ out[key] = value;
+ }
+ return out;
+}
diff --git a/examples/openclaw-plugin/services/setup/probe-service.ts b/examples/openclaw-plugin/services/setup/probe-service.ts
index 88c18b77d..d7eebaa32 100644
--- a/examples/openclaw-plugin/services/setup/probe-service.ts
+++ b/examples/openclaw-plugin/services/setup/probe-service.ts
@@ -1,3 +1,8 @@
+import {
+ resolveOpenVikingRequestHeaders,
+ type OpenVikingRequestHeaders,
+} from "../../request-headers.js";
+
export type SetupNetworkTransport = (url: string, init: RequestInit) => Promise<Response>;
export type SetupVersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";
@@ -27,8 +32,16 @@ export type SetupNetworkProbeOptions = {
};
export type SetupNetworkProbes = {
- probeApiKeyType: (baseUrl: string, apiKey?: string) => Promise<SetupApiKeyProbeResult>;
- checkServiceHealth: (baseUrl: string, apiKey?: string) => Promise<SetupHealthResult>;
+ probeApiKeyType: (
+ baseUrl: string,
+ apiKey?: string,
+ headers?: OpenVikingRequestHeaders,
+ ) => Promise<SetupApiKeyProbeResult>;
+ checkServiceHealth: (
+ baseUrl: string,
+ apiKey?: string,
+ headers?: OpenVikingRequestHeaders,
+ ) => Promise<SetupHealthResult>;
};
export const defaultSetupNetworkTransport: SetupNetworkTransport = (url, init) => fetch(url, init);
@@ -41,7 +54,11 @@ export function createSetupNetworkProbes({
timeoutMs = 10_000,
}: SetupNetworkProbeOptions): SetupNetworkProbes {
return {
- async probeApiKeyType(baseUrl: string, apiKey?: string): Promise<SetupApiKeyProbeResult> {
+ async probeApiKeyType(
+ baseUrl: string,
+ apiKey?: string,
+ configuredHeaders?: OpenVikingRequestHeaders,
+ ): Promise<SetupApiKeyProbeResult> {
if (!apiKey) {
return { keyType: "no_key", needsAccountId: false, needsUserId: false, detail: "No API key configured" };
}
@@ -50,7 +67,10 @@ export function createSetupNetworkProbes({
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const sessionsUrl = `${baseUrl.replace(/\/+$/, "")}/api/v1/sessions?limit=1`;
try {
- const headers: Record<string, string> = { "X-API-Key": apiKey };
+ const configuredRequestHeaders = resolveOpenVikingRequestHeaders({ headers: configuredHeaders });
+ const headers: Record<string, string> = {};
+ headers["X-API-Key"] = apiKey;
+ Object.assign(headers, configuredRequestHeaders);
const response = await transport(sessionsUrl, {
headers,
signal: controller.signal,
@@ -82,6 +102,7 @@ export function createSetupNetworkProbes({
"X-API-Key": apiKey,
"X-OpenViking-Account": "__probe__",
"X-OpenViking-User": "__probe__",
+ ...configuredRequestHeaders,
};
const probe2 = await transport(sessionsUrl, {
headers: probeHeaders,
@@ -111,12 +132,20 @@ export function createSetupNetworkProbes({
}
},
- async checkServiceHealth(baseUrl: string, apiKey?: string): Promise<SetupHealthResult> {
+ async checkServiceHealth(
+ baseUrl: string,
+ apiKey?: string,
+ configuredHeaders?: OpenVikingRequestHeaders,
+ ): Promise<SetupHealthResult> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
+ const configuredRequestHeaders = resolveOpenVikingRequestHeaders({ headers: configuredHeaders });
const headers: Record<string, string> = {};
- if (apiKey) headers["X-API-Key"] = apiKey;
+ if (apiKey) {
+ headers["X-API-Key"] = apiKey;
+ }
+ Object.assign(headers, configuredRequestHeaders);
const response = await transport(`${baseUrl.replace(/\/+$/, "")}/health`, {
headers,
signal: controller.signal,
diff --git a/examples/openclaw-plugin/services/setup/setup-flow.ts b/examples/openclaw-plugin/services/setup/setup-flow.ts
index dec9efb17..7aa467a34 100644
--- a/examples/openclaw-plugin/services/setup/setup-flow.ts
+++ b/examples/openclaw-plugin/services/setup/setup-flow.ts
@@ -6,6 +6,10 @@ import {
type SetupIO,
type SlotActivationResult,
} from "./config-writer.js";
+import {
+ cleanOpenVikingRequestHeaders,
+ type OpenVikingRequestHeaders,
+} from "../../request-headers.js";
export type { SetupIO, SlotActivationResult };
@@ -38,6 +42,7 @@ export type SetupResult = {
peer_prefix?: string;
accountId?: string;
userId?: string;
+ headers?: OpenVikingRequestHeaders;
recallTargetTypes?: string[];
};
health?: HealthResult;
@@ -65,6 +70,7 @@ export type StatusResult = {
export type SetupParams = {
baseUrl: string;
apiKey?: string;
+ headers?: OpenVikingRequestHeaders;
peerRole?: "none" | "assistant" | "person";
peerPrefix?: string;
accountId?: string;
@@ -78,6 +84,7 @@ export type InteractiveRemoteConfigParams = {
existing?: Record<string, unknown> | null;
baseUrl: string;
apiKey?: string;
+ headers?: OpenVikingRequestHeaders;
peerRole?: "none" | "assistant" | "person";
peerPrefix?: string;
accountId?: string;
@@ -100,8 +107,16 @@ export type OpenVikingSetupService = {
export type OpenVikingSetupServiceDependencies = {
io: SetupIO;
defaultRemoteUrl?: string;
- checkServiceHealth: (baseUrl: string, apiKey?: string) => Promise<HealthResult>;
- probeApiKeyType: (baseUrl: string, apiKey?: string) => Promise<ApiKeyProbeResult>;
+ checkServiceHealth: (
+ baseUrl: string,
+ apiKey?: string,
+ headers?: OpenVikingRequestHeaders,
+ ) => Promise<HealthResult>;
+ probeApiKeyType: (
+ baseUrl: string,
+ apiKey?: string,
+ headers?: OpenVikingRequestHeaders,
+ ) => Promise<ApiKeyProbeResult>;
};
export function maskKey(key: string): string {
@@ -114,10 +129,38 @@ export function isLegacyLocalMode(existing: Record<string, unknown>): boolean {
return mode !== "remote";
}
+function nonEmptyOpenVikingRequestHeaders(value: unknown): OpenVikingRequestHeaders | undefined {
+ const headers = cleanOpenVikingRequestHeaders(value);
+ return Object.keys(headers).length > 0 ? headers : undefined;
+}
+
+function callHealthProbe(
+ checkServiceHealth: OpenVikingSetupServiceDependencies["checkServiceHealth"],
+ baseUrl: string,
+ apiKey: string | undefined,
+ headers: OpenVikingRequestHeaders | undefined,
+): Promise<HealthResult> {
+ return headers
+ ? checkServiceHealth(baseUrl, apiKey, headers)
+ : checkServiceHealth(baseUrl, apiKey);
+}
+
+function callApiKeyProbe(
+ probeApiKeyType: OpenVikingSetupServiceDependencies["probeApiKeyType"],
+ baseUrl: string,
+ apiKey: string | undefined,
+ headers: OpenVikingRequestHeaders | undefined,
+): Promise<ApiKeyProbeResult> {
+ return headers
+ ? probeApiKeyType(baseUrl, apiKey, headers)
+ : probeApiKeyType(baseUrl, apiKey);
+}
+
export function buildInteractiveRemotePluginConfig({
existing,
baseUrl,
apiKey,
+ headers,
peerRole,
peerPrefix,
accountId,
@@ -138,6 +181,11 @@ export function buildInteractiveRemotePluginConfig({
else delete pluginCfg.accountId;
if (userId) pluginCfg.userId = userId;
else delete pluginCfg.userId;
+ if (headers !== undefined) {
+ const cleanHeaders = nonEmptyOpenVikingRequestHeaders(headers);
+ if (cleanHeaders) pluginCfg.headers = cleanHeaders;
+ else delete pluginCfg.headers;
+ }
delete pluginCfg.configPath;
delete pluginCfg.port;
return pluginCfg;
@@ -153,8 +201,9 @@ export function createOpenVikingSetupService({
async setupNonInteractive(configPath: string, params: SetupParams): Promise<SetupResult> {
try {
const { baseUrl, apiKey, peerRole, peerPrefix, accountId, userId, recallTargetTypes, allowOffline, forceSlot } = params;
+ const headers = nonEmptyOpenVikingRequestHeaders(params.headers);
- const health = await checkServiceHealth(baseUrl, apiKey);
+ const health = await callHealthProbe(checkServiceHealth, baseUrl, apiKey, headers);
if (!health.ok && !allowOffline) {
return {
@@ -167,7 +216,7 @@ export function createOpenVikingSetupService({
};
}
- const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;
+ const keyProbe = health.ok ? await callApiKeyProbe(probeApiKeyType, baseUrl, apiKey, headers) : undefined;
if (keyProbe?.keyType === "root_key" && (!accountId || !userId)) {
const missing: string[] = [];
@@ -190,6 +239,7 @@ export function createOpenVikingSetupService({
const pluginCfg: Record<string, unknown> = { mode: "remote", baseUrl };
if (apiKey) pluginCfg.apiKey = apiKey;
+ if (headers && Object.keys(headers).length > 0) pluginCfg.headers = headers;
if (peerRole) pluginCfg.peer_role = peerRole;
if (peerPrefix) pluginCfg.peer_prefix = peerPrefix;
if (accountId) pluginCfg.accountId = accountId;
@@ -203,6 +253,7 @@ export function createOpenVikingSetupService({
mode: "remote",
baseUrl,
...(apiKey ? { apiKey: maskKey(apiKey) } : {}),
+ ...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
...(peerRole ? { peer_role: peerRole } : {}),
...(peerPrefix ? { peer_prefix: peerPrefix } : {}),
...(accountId ? { accountId } : {}),
@@ -253,7 +304,8 @@ export function createOpenVikingSetupService({
async useExistingRemoteConfig(configPath: string, existing: Record<string, unknown>): Promise<SetupResult> {
const baseUrl = String(existing.baseUrl ?? defaultRemoteUrl);
const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;
- const health = await checkServiceHealth(baseUrl, apiKey);
+ const headers = nonEmptyOpenVikingRequestHeaders(existing.headers);
+ const health = await callHealthProbe(checkServiceHealth, baseUrl, apiKey, headers);
const slot = activateContextEngineSlot(configPath, false, io);
return {
success: true,
@@ -262,6 +314,7 @@ export function createOpenVikingSetupService({
mode: String(existing.mode ?? "remote"),
baseUrl,
...(apiKey ? { apiKey: maskKey(apiKey) } : {}),
+ ...(headers ? { headers } : {}),
...(existing.peer_role ? { peer_role: String(existing.peer_role) as "none" | "assistant" | "person" } : {}),
...(existing.peer_prefix ? { peer_prefix: String(existing.peer_prefix) } : {}),
...(existing.accountId ? { accountId: String(existing.accountId) } : {}),
@@ -283,8 +336,9 @@ export function createOpenVikingSetupService({
const baseUrl = String(existing.baseUrl ?? defaultRemoteUrl);
const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;
- const health = await checkServiceHealth(baseUrl, apiKey);
- const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;
+ const headers = nonEmptyOpenVikingRequestHeaders(existing.headers);
+ const health = await callHealthProbe(checkServiceHealth, baseUrl, apiKey, headers);
+ const keyProbe = health.ok ? await callApiKeyProbe(probeApiKeyType, baseUrl, apiKey, headers) : undefined;
return {
configured: true,
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 3b485b429..90fccb3b5 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -410,6 +410,50 @@ describe("OpenVikingClient tenant headers (advanced accountId / userId overrides
expect(headers.get("X-OpenViking-User")).toBe("user-456");
});
+ it("applies configured headers after explicit API and tenant headers", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "sk-explicit", "agent", 5000,
+ "acct-explicit", "user-explicit", undefined, false, true,
+ {
+ transport,
+ headers: {
+ "X-API-Key": "sk-from-config",
+ "X-OpenViking-Account": "acct-from-config",
+ "X-OpenViking-User": "user-from-config",
+ openviking: "i18n-instance",
+ token: "root-token",
+ },
+ },
+ );
+ await client.healthCheck();
+
+ const [, init] = transport.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-API-Key")).toBe("sk-from-config");
+ expect(headers.get("X-OpenViking-Account")).toBe("acct-from-config");
+ expect(headers.get("X-OpenViking-User")).toBe("user-from-config");
+ expect(headers.get("openviking")).toBe("i18n-instance");
+ expect(headers.get("token")).toBe("root-token");
+ });
+
+ it("can use explicit configured headers as the only API key source", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "", "", undefined, false, true,
+ { transport, headers: { "X-API-Key": "sk-from-config", token: "root-token" } },
+ );
+ await client.healthCheck();
+
+ const [, init] = transport.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-API-Key")).toBe("sk-from-config");
+ expect(headers.get("token")).toBe("root-token");
+ });
+
it("does not synthesize tenant headers when apiKey is missing", async () => {
const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index b67613351..8fcf0b4a7 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -40,6 +40,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.traceRecallIncludeContentByDefault).toBe(false);
expect(cfg.traceRecallIncludeRawUserPreview).toBe(false);
expect(cfg.recallTargetTypes).toEqual(["user", "agent"]);
+ expect(cfg.headers).toEqual({});
expect(cfg.enableAddResourceTool).toBe(false);
expect(cfg.enabledTools).toContain("ov_search");
expect(cfg.enabledTools).toContain("ov_read");
@@ -180,6 +181,30 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
).toThrow("unknown keys");
});
+ it("parses string-valued configured headers", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ headers: {
+ openviking: "i18n-instance",
+ token: "root-token",
+ },
+ });
+
+ expect(cfg.headers).toEqual({
+ openviking: "i18n-instance",
+ token: "root-token",
+ });
+ });
+
+ it("throws on non-string configured header values", () => {
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({
+ headers: {
+ openviking: 123,
+ },
+ }),
+ ).toThrow("openviking config headers.openviking must be a string");
+ });
+
it("throws on unknown agentExperience keys", () => {
expect(() =>
memoryOpenVikingConfigSchema.parse({
diff --git a/examples/openclaw-plugin/tests/ut/request-headers.test.ts b/examples/openclaw-plugin/tests/ut/request-headers.test.ts
new file mode 100644
index 000000000..28cb75732
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/request-headers.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ cleanOpenVikingRequestHeaders,
+ resolveOpenVikingRequestHeaders,
+} from "../../request-headers.js";
+
+describe("OpenViking request headers", () => {
+ it("preserves string-valued headers exactly", () => {
+ expect(cleanOpenVikingRequestHeaders({
+ openviking: " i18n-instance ",
+ empty: "",
+ })).toEqual({
+ openviking: " i18n-instance ",
+ empty: "",
+ });
+ });
+
+ it("resolves configured OpenViking routing headers", () => {
+ expect(resolveOpenVikingRequestHeaders({
+ headers: {
+ openviking: "i18n_bi_claw_1781078526__bi_claw_openviking",
+ region: "SG",
+ },
+ })).toEqual({
+ openviking: "i18n_bi_claw_1781078526__bi_claw_openviking",
+ region: "SG",
+ });
+ });
+
+ it("does not synthesize auth headers", () => {
+ expect(resolveOpenVikingRequestHeaders()).toEqual({});
+ });
+
+ it("keeps explicitly configured auth-like headers when provided", () => {
+ expect(resolveOpenVikingRequestHeaders({
+ headers: {
+ token: "explicit-token",
+ "X-API-Key": "explicit-key",
+ },
+ })).toEqual({
+ token: "explicit-token",
+ "X-API-Key": "explicit-key",
+ });
+ });
+
+ it("rejects non-string header values", () => {
+ expect(() => resolveOpenVikingRequestHeaders({
+ headers: { openviking: 123 },
+ })).toThrow("openviking request header openviking must be a string");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts b/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts
index deb2f1769..68a1cda2d 100644
--- a/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts
+++ b/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts
@@ -69,6 +69,42 @@ describe("setup probe service", () => {
});
});
+ it("merges configured headers into health and API-key probe requests", async () => {
+ const transport = vi.fn<SetupNetworkTransport>().mockResolvedValue(
+ response(200, { result: { version: "2026.6.1" } }),
+ );
+ const probes = createSetupNetworkProbes({
+ pluginVersion: "2026.6.5",
+ compatRange: ">= 2026.6.0",
+ checkVersionCompatibility: () => "compatible",
+ transport,
+ });
+ const headers = {
+ openviking: "i18n-instance",
+ token: "root-token",
+ region: "SG",
+ "X-API-Key": "from-config",
+ };
+
+ await probes.checkServiceHealth("http://127.0.0.1:1933", "sk-explicit", headers);
+ await probes.probeApiKeyType("http://127.0.0.1:1933", "sk-explicit", headers);
+
+ const healthHeaders = (transport.mock.calls[0]![1] as RequestInit).headers as Record<string, string>;
+ const probeHeaders = (transport.mock.calls[1]![1] as RequestInit).headers as Record<string, string>;
+ expect(healthHeaders).toMatchObject({
+ openviking: "i18n-instance",
+ token: "root-token",
+ region: "SG",
+ "X-API-Key": "from-config",
+ });
+ expect(probeHeaders).toMatchObject({
+ openviking: "i18n-instance",
+ token: "root-token",
+ region: "SG",
+ "X-API-Key": "from-config",
+ });
+ });
+
it("does not hit the network when no API key is configured", async () => {
const transport = vi.fn<SetupNetworkTransport>();
const probes = createSetupNetworkProbes({