Skip to content

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

feat(openclaw-plugin): align agent routing and reduce default log noise; fix(system/status): align resolved user id (#1054)

LinQiang391df632107f543
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 1ea0a1b1c..aba3e488b 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -142,12 +142,42 @@ export class OpenVikingClient {
private readonly apiKey: string,
private readonly defaultAgentId: string,
private readonly timeoutMs: number,
+ /** When set (or defaulted), sent so ROOT key can access tenant-scoped APIs. */
+ private readonly accountId: string = "",
+ private readonly userId: string = "",
+ /** When set, logs routing for find + session writes (tenant headers + paths; never apiKey). */
+ private readonly routingDebugLog?: (message: string) => void,
) {}
getDefaultAgentId(): string {
return this.defaultAgentId;
}
+ private async emitRoutingDebug(
+ label: string,
+ detail: Record<string, unknown>,
+ agentId?: string,
+ ): Promise<void> {
+ if (!this.routingDebugLog) {
+ return;
+ }
+ const effectiveAgentId = agentId ?? this.defaultAgentId;
+ const identity = await this.getRuntimeIdentity(agentId);
+ this.routingDebugLog(
+ `openviking: ${label} ` +
+ JSON.stringify({
+ ...detail,
+ X_OpenViking_Agent: effectiveAgentId,
+ X_OpenViking_Account: this.accountId.trim() || "default",
+ X_OpenViking_User: this.userId.trim() || "default",
+ resolved_user_id: identity.userId,
+ session_vfs_hint: detail.sessionId
+ ? `viking://session/${identity.userId}/${String(detail.sessionId)}`
+ : undefined,
+ }),
+ );
+ }
+
private async request<T>(path: string, init: RequestInit = {}, agentId?: string): Promise<T> {
const effectiveAgentId = agentId ?? this.defaultAgentId;
const controller = new AbortController();
@@ -157,6 +187,8 @@ export class OpenVikingClient {
if (this.apiKey) {
headers.set("X-API-Key", this.apiKey);
}
+ headers.set("X-OpenViking-Account", this.accountId.trim() || "default");
+ headers.set("X-OpenViking-User", this.userId.trim() || "default");
if (effectiveAgentId) {
headers.set("X-OpenViking-Agent", effectiveAgentId);
}
@@ -311,6 +343,25 @@ export class OpenVikingClient {
limit: options.limit,
score_threshold: options.scoreThreshold,
};
+ const effectiveAgentId = agentId ?? this.defaultAgentId;
+ const identity = await this.getRuntimeIdentity(agentId);
+ this.routingDebugLog?.(
+ `openviking: find POST ${this.baseUrl}/api/v1/search/find ` +
+ JSON.stringify({
+ X_OpenViking_Agent: effectiveAgentId,
+ X_OpenViking_Account: this.accountId.trim() || "default",
+ X_OpenViking_User: this.userId.trim() || "default",
+ resolved_user_id: identity.userId,
+ target_uri: normalizedTargetUri,
+ target_uri_input: options.targetUri,
+ query:
+ query.length > 4000
+ ? `${query.slice(0, 4000)}…(+${query.length - 4000} more chars)`
+ : query,
+ limit: body.limit,
+ score_threshold: body.score_threshold ?? null,
+ }),
+ );
return this.request<FindResult>("/api/v1/search/find", {
method: "POST",
body: JSON.stringify(body),
@@ -326,6 +377,16 @@ export class OpenVikingClient {
}
async addSessionMessage(sessionId: string, role: string, content: string, agentId?: string): Promise<void> {
+ await this.emitRoutingDebug(
+ "session message POST",
+ {
+ path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
+ sessionId,
+ role,
+ contentChars: content.length,
+ },
+ agentId,
+ );
await this.request<{ session_id: string }>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
{
@@ -368,6 +429,15 @@ export class OpenVikingClient {
sessionId: string,
options?: { wait?: boolean; timeoutMs?: number; agentId?: string },
): Promise<CommitSessionResult> {
+ await this.emitRoutingDebug(
+ "session commit POST (archive + memory extraction)",
+ {
+ path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
+ sessionId,
+ wait: options?.wait ?? false,
+ },
+ options?.agentId,
+ );
const result = await this.request<CommitSessionResult>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
{ method: "POST", body: JSON.stringify({}) },
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index 6a02fca23..a25037bdc 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -32,6 +32,8 @@ export type MemoryOpenVikingConfig = {
* standard-diagnostics file writes) for assemble/afterTurn. Set false to disable.
*/
emitStandardDiagnostics?: boolean;
+ /** When true, log tenant routing for semantic find and session writes (messages/commit) to the plugin logger. */
+ logFindRequests?: boolean;
};
const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
@@ -84,6 +86,16 @@ function toNumber(value: unknown, fallback: number): number {
return fallback;
}
+/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */
+function envFlag(name: string): boolean {
+ const v = process.env[name];
+ if (v == null || v === "") {
+ return false;
+ }
+ const t = String(v).trim().toLowerCase();
+ return t === "1" || t === "true" || t === "yes";
+}
+
function assertAllowedKeys(value: Record<string, unknown>, allowed: string[], label: string) {
const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
if (unknown.length === 0) {
@@ -131,6 +143,7 @@ export const memoryOpenVikingConfigSchema = {
"ingestReplyAssistMinSpeakerTurns",
"ingestReplyAssistMinChars",
"emitStandardDiagnostics",
+ "logFindRequests",
],
"openviking config",
);
@@ -219,6 +232,10 @@ export const memoryOpenVikingConfigSchema = {
typeof cfg.emitStandardDiagnostics === "boolean"
? cfg.emitStandardDiagnostics
: DEFAULT_EMIT_STANDARD_DIAGNOSTICS,
+ logFindRequests:
+ cfg.logFindRequests === true ||
+ envFlag("OPENVIKING_LOG_ROUTING") ||
+ envFlag("OPENVIKING_DEBUG"),
};
},
uiHints: {
@@ -245,7 +262,7 @@ export const memoryOpenVikingConfigSchema = {
agentId: {
label: "Agent ID",
placeholder: "auto-generated",
- help: "Identifies this agent to OpenViking (sent as X-OpenViking-Agent header). Defaults to \"default\" if not set.",
+ help: 'OpenViking X-OpenViking-Agent: non-default values combine with OpenClaw ctx.agentId as "<config>_<sessionAgent>" (then sanitized to [a-zA-Z0-9_-]). Use "default" to send only ctx.agentId.',
},
apiKey: {
label: "OpenViking API Key",
@@ -338,6 +355,13 @@ export const memoryOpenVikingConfigSchema = {
advanced: true,
help: "When enabled, emit structured openviking: diag {...} lines for assemble and afterTurn. Disable to reduce log noise.",
},
+ logFindRequests: {
+ label: "Log find requests",
+ help:
+ "Log tenant routing: POST /api/v1/search/find (query, target_uri) and session POST .../messages + .../commit (sessionId, X-OpenViking-*). Never logs apiKey. " +
+ "Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1 (no JSON edit). When on, local-mode OpenViking subprocess stderr is also logged at info.",
+ advanced: true,
+ },
},
};
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index a81390945..9311daad4 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import type { OpenVikingClient, OVMessage } from "./client.js";
import type { MemoryOpenVikingConfig } from "./config.js";
import {
@@ -60,8 +61,15 @@ type ContextEngine = {
isHeartbeat?: boolean;
tokenBudget?: number;
runtimeContext?: Record<string, unknown>;
+ sessionKey?: string;
}) => Promise<void>;
- assemble: (params: { sessionId: string; messages: AgentMessage[]; tokenBudget?: number }) => Promise<AssembleResult>;
+ assemble: (params: {
+ sessionId: string;
+ sessionKey?: string;
+ messages: AgentMessage[];
+ tokenBudget?: number;
+ runtimeContext?: Record<string, unknown>;
+ }) => Promise<AssembleResult>;
compact: (params: {
sessionId: string;
sessionFile: string;
@@ -149,6 +157,54 @@ function validTokenBudget(raw: unknown): number | undefined {
return undefined;
}
+/** OpenClaw session UUID (path-safe on Windows). */
+const OPENVIKING_OV_SESSION_UUID =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const WINDOWS_BAD_SESSION_SEGMENT = /[:<>"\\/|?\u0000-\u001f]/;
+
+/**
+ * Map OpenClaw session identity to an OpenViking session_id that is safe as a single
+ * AGFS path segment on Windows (no `:` etc.). Prefer UUID sessionId when present;
+ * otherwise derive a stable sha256 from sessionKey.
+ */
+export function openClawSessionToOvStorageId(
+ sessionId: string | undefined,
+ sessionKey: string | undefined,
+): string {
+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";
+ const key = typeof sessionKey === "string" ? sessionKey.trim() : "";
+
+ if (sid && OPENVIKING_OV_SESSION_UUID.test(sid)) {
+ return sid.toLowerCase();
+ }
+ if (key) {
+ return createHash("sha256").update(key, "utf8").digest("hex");
+ }
+ if (sid) {
+ if (WINDOWS_BAD_SESSION_SEGMENT.test(sid)) {
+ return createHash("sha256").update(`openclaw-session:${sid}`, "utf8").digest("hex");
+ }
+ return sid;
+ }
+ throw new Error("openviking: need sessionId or sessionKey for OV session path");
+}
+
+/** Normalize a hook/tool session ref (uuid, sessionKey, or already-safe id) for OV storage. */
+export function openClawSessionRefToOvStorageId(ref: string): string {
+ const t = ref.trim();
+ if (!t) {
+ throw new Error("openviking: empty session ref");
+ }
+ if (OPENVIKING_OV_SESSION_UUID.test(t)) {
+ return t.toLowerCase();
+ }
+ if (WINDOWS_BAD_SESSION_SEGMENT.test(t)) {
+ return createHash("sha256").update(t, "utf8").digest("hex");
+ }
+ return t;
+}
+
/**
* Convert an OpenViking stored message (parts-based format) into one or more
* OpenClaw AgentMessages (content-blocks format).
@@ -337,32 +393,58 @@ function warnOrInfo(logger: Logger, message: string): void {
logger.info(message);
}
-function formatMessagesForLog(label: string, messages: AgentMessage[]): string {
- const lines: string[] = [`===== ${label} (${messages.length} msgs) =====`];
- for (let i = 0; i < messages.length; i++) {
- const msg = messages[i] as Record<string, unknown>;
- const role = msg.role ?? "?";
- const raw = msg.content;
- let text: string;
- if (typeof raw === "string") {
- text = raw;
- } else if (Array.isArray(raw)) {
- text = (raw as Record<string, unknown>[])
- .map((b) => {
- if (b.type === "text") return b.text;
- if (b.type === "toolUse") return `[toolUse: ${b.name}]`;
- if (b.type === "toolResult") return `[toolResult]`;
- return `[${b.type}]`;
- })
- .join("\n");
- } else {
- text = JSON.stringify(raw, null, 2);
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+const PHASE2_POLL_INTERVAL_MS = 800;
+const PHASE2_POLL_MAX_MS = 120_000;
+
+/**
+ * After wait=false commit, Phase2 runs on the server. Poll task until completed/failed/timeout
+ * so logs show memories_extracted (otherwise it looks like "nothing was saved").
+ */
+async function pollPhase2ExtractionOutcome(
+ getClient: () => Promise<OpenVikingClient>,
+ taskId: string,
+ agentId: string,
+ logger: Logger,
+ sessionLabel: string,
+): Promise<void> {
+ const deadline = Date.now() + PHASE2_POLL_MAX_MS;
+ try {
+ const client = await getClient();
+ while (Date.now() < deadline) {
+ await sleep(PHASE2_POLL_INTERVAL_MS);
+ const task = await client.getTask(taskId, agentId).catch((e) => {
+ logger.warn(`openviking: phase2 getTask failed task_id=${taskId}: ${String(e)}`);
+ return null;
+ });
+ if (!task) {
+ return;
+ }
+ const { status } = task;
+ if (status === "completed") {
+ logger.info(
+ `openviking: phase2 completed task_id=${taskId} session=${sessionLabel} ` +
+ `result=${toJsonLog(task.result ?? {})}`,
+ );
+ return;
+ }
+ if (status === "failed") {
+ logger.warn(
+ `openviking: phase2 failed task_id=${taskId} session=${sessionLabel} error=${task.error ?? "unknown"}`,
+ );
+ return;
+ }
}
- lines.push(`--- [${i}] ${role} ---`);
- lines.push(String(text));
+ logger.warn(
+ `openviking: phase2 poll timeout (${PHASE2_POLL_MAX_MS / 1000}s) task_id=${taskId} session=${sessionLabel} — ` +
+ `check GET /api/v1/tasks/${taskId}`,
+ );
+ } catch (e) {
+ logger.warn(`openviking: phase2 poll exception task_id=${taskId}: ${String(e)}`);
}
- lines.push(`===== /${label} =====`);
- return lines.join("\n");
}
export function createMemoryOpenVikingContextEngine(params: {
@@ -372,7 +454,14 @@ export function createMemoryOpenVikingContextEngine(params: {
cfg: Required<MemoryOpenVikingConfig>;
logger: Logger;
getClient: () => Promise<OpenVikingClient>;
- resolveAgentId: (sessionId: string) => string;
+ /** Extra args help match hook-populated routing when OpenClaw provides sessionKey / OV session id. */
+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;
+ rememberSessionAgentId?: (ctx: {
+ agentId?: string;
+ sessionId?: string;
+ sessionKey?: string;
+ ovSessionId?: string;
+ }) => void;
}): ContextEngineWithCommit {
const {
id,
@@ -382,6 +471,7 @@ export function createMemoryOpenVikingContextEngine(params: {
logger,
getClient,
resolveAgentId,
+ rememberSessionAgentId,
} = params;
const diagEnabled = cfg.emitStandardDiagnostics;
@@ -391,8 +481,14 @@ export function createMemoryOpenVikingContextEngine(params: {
async function doCommitOVSession(sessionId: string): Promise<boolean> {
try {
const client = await getClient();
- const agentId = resolveAgentId(sessionId);
- const commitResult = await client.commitSession(sessionId, { wait: true, agentId });
+ const ovId = openClawSessionRefToOvStorageId(sessionId);
+ rememberSessionAgentId?.({
+ sessionId,
+ sessionKey: sessionId,
+ ovSessionId: ovId,
+ });
+ const agentId = resolveAgentId(sessionId, sessionId, ovId);
+ const commitResult = await client.commitSession(ovId, { wait: true, agentId });
const memCount = totalExtractedMemories(commitResult.memories_extracted);
if (commitResult.status === "failed") {
warnOrInfo(logger, `openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}`);
@@ -403,7 +499,7 @@ export function createMemoryOpenVikingContextEngine(params: {
return false;
}
logger.info(
- `openviking: committed OV session=${sessionId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}`,
+ `openviking: committed OV session=${sessionId} ovId=${ovId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}`,
);
return true;
} catch (err) {
@@ -412,6 +508,35 @@ export function createMemoryOpenVikingContextEngine(params: {
}
}
+ function extractSessionKey(runtimeContext: Record<string, unknown> | undefined): string | undefined {
+ if (!runtimeContext) {
+ return undefined;
+ }
+ const key = runtimeContext.sessionKey;
+ return typeof key === "string" && key.trim() ? key.trim() : undefined;
+ }
+
+ function extractAssembleSessionKey(params: {
+ sessionKey?: string;
+ runtimeContext?: Record<string, unknown>;
+ }): string | undefined {
+ const direct = typeof params.sessionKey === "string" ? params.sessionKey.trim() : "";
+ if (direct) {
+ return direct;
+ }
+ return extractSessionKey(params.runtimeContext);
+ }
+
+ function extractRuntimeAgentId(
+ runtimeContext: Record<string, unknown> | undefined,
+ ): string | undefined {
+ if (!runtimeContext) {
+ return undefined;
+ }
+ const agentId = runtimeContext.agentId;
+ return typeof agentId === "string" && agentId.trim() ? agentId.trim() : undefined;
+ }
+
return {
info: {
id,
@@ -435,21 +560,30 @@ export function createMemoryOpenVikingContextEngine(params: {
async assemble(assembleParams): Promise<AssembleResult> {
const { messages } = assembleParams;
const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;
+ const sessionKey = extractAssembleSessionKey(assembleParams);
const originalTokens = roughEstimate(messages);
- logger.info(`openviking: assemble input msgs=${messages.length} ~${originalTokens} tokens, budget=${validTokenBudget(assembleParams.tokenBudget) ?? 128_000}`);
-
- const OVSessionId = assembleParams.sessionId;
+
+ const OVSessionId = openClawSessionToOvStorageId(assembleParams.sessionId, sessionKey);
+ rememberSessionAgentId?.({
+ sessionId: assembleParams.sessionId,
+ sessionKey,
+ agentId: extractRuntimeAgentId(assembleParams.runtimeContext),
+ ovSessionId: OVSessionId,
+ });
diag("assemble_entry", OVSessionId, {
messagesCount: messages.length,
inputTokenEstimate: originalTokens,
tokenBudget,
+ sessionKey: sessionKey ?? null,
messages: messageDigest(messages),
});
try {
const client = await getClient();
- const agentId = resolveAgentId(OVSessionId);
+ const routingRef =
+ assembleParams.sessionId ?? sessionKey ?? OVSessionId;
+ const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);
const ctx = await client.getSessionContext(
OVSessionId,
tokenBudget,
@@ -459,12 +593,8 @@ export function createMemoryOpenVikingContextEngine(params: {
const hasArchives = !!ctx?.latest_archive_id;
const activeCount = ctx?.messages?.length ?? 0;
const preAbstracts = ctx?.pre_archive_abstracts ?? [];
- logger.info(
- `openviking: assemble OV ctx hasArchives=${hasArchives} latestId=${ctx?.latest_archive_id ?? "none"} preAbstracts=${preAbstracts.length} active=${activeCount}`,
- );
if (!ctx || (!hasArchives && activeCount === 0)) {
- logger.info("openviking: assemble passthrough (no OV data)");
diag("assemble_result", OVSessionId, {
passthrough: true, reason: "no_ov_data",
archiveCount: 0, activeCount: 0,
@@ -477,7 +607,6 @@ export function createMemoryOpenVikingContextEngine(params: {
}
if (!hasArchives && ctx.messages.length < messages.length) {
- logger.info(`openviking: assemble passthrough (OV msgs=${ctx.messages.length} < input msgs=${messages.length})`);
diag("assemble_result", OVSessionId, {
passthrough: true, reason: "ov_msgs_fewer_than_input",
archiveCount: 0, activeCount,
@@ -519,7 +648,6 @@ export function createMemoryOpenVikingContextEngine(params: {
const sanitized = sanitizeToolUseResultPairing(assembled as never[]) as AgentMessage[];
if (sanitized.length === 0 && messages.length > 0) {
- logger.info("openviking: assemble passthrough (sanitized=0, falling back to original)");
diag("assemble_result", OVSessionId, {
passthrough: true, reason: "sanitized_empty",
archiveCount: preAbstracts.length + (ctx.latest_archive_id ? 1 : 0),
@@ -534,7 +662,6 @@ export function createMemoryOpenVikingContextEngine(params: {
const assembledTokens = roughEstimate(sanitized);
const archiveCount = preAbstracts.length + (ctx.latest_archive_id ? 1 : 0);
- logger.info(`openviking: assemble result msgs=${sanitized.length} ~${assembledTokens} tokens (ovEstimate=${ctx.estimatedTokens}), archives=${archiveCount}, active=${activeCount}`);
const tokensSaved = originalTokens - assembledTokens;
const savingPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;
@@ -571,13 +698,29 @@ export function createMemoryOpenVikingContextEngine(params: {
return;
}
- const OVSessionId = afterTurnParams.sessionId;
try {
- const agentId = resolveAgentId(OVSessionId);
+ const sessionKey =
+ (typeof afterTurnParams.sessionKey === "string" && afterTurnParams.sessionKey.trim()) ||
+ extractSessionKey(afterTurnParams.runtimeContext);
+ const OVSessionId = openClawSessionToOvStorageId(
+ afterTurnParams.sessionId,
+ sessionKey,
+ );
+ const runtimeAgentId = extractRuntimeAgentId(afterTurnParams.runtimeContext);
+ if (runtimeAgentId) {
+ rememberSessionAgentId?.({
+ agentId: runtimeAgentId,
+ sessionId: afterTurnParams.sessionId,
+ sessionKey,
+ ovSessionId: OVSessionId,
+ });
+ }
+ const routingRef =
+ afterTurnParams.sessionId ?? sessionKey ?? OVSessionId;
+ const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);
const messages = afterTurnParams.messages ?? [];
if (messages.length === 0) {
- logger.info("openviking: afterTurn skipped (messages=0)");
diag("afterTurn_skip", OVSessionId, {
reason: "no_messages",
totalMessages: 0,
@@ -594,7 +737,6 @@ export function createMemoryOpenVikingContextEngine(params: {
const { texts: newTexts, newCount } = extractNewTurnTexts(messages, start);
if (newTexts.length === 0) {
- logger.info("openviking: afterTurn skipped (no new user/assistant messages)");
diag("afterTurn_skip", OVSessionId, {
reason: "no_new_turn_messages",
totalMessages: messages.length,
@@ -624,11 +766,7 @@ export function createMemoryOpenVikingContextEngine(params: {
if (sanitized) {
await client.addSessionMessage(OVSessionId, "user", sanitized, agentId);
- logger.info(
- `openviking: afterTurn stored ${newCount} msgs in session=${OVSessionId} (${sanitized.length} chars)`,
- );
} else {
- logger.info("openviking: afterTurn skipped store (sanitized text empty)");
diag("afterTurn_skip", OVSessionId, {
reason: "sanitized_empty",
});
@@ -639,9 +777,6 @@ export function createMemoryOpenVikingContextEngine(params: {
const pendingTokens = session.pending_tokens ?? 0;
if (pendingTokens < cfg.commitTokenThreshold) {
- logger.info(
- `openviking: pending_tokens=${pendingTokens}/${cfg.commitTokenThreshold} in session=${OVSessionId}, deferring commit`,
- );
diag("afterTurn_skip", OVSessionId, {
reason: "below_threshold",
pendingTokens,
@@ -650,14 +785,14 @@ export function createMemoryOpenVikingContextEngine(params: {
return;
}
- logger.info(
- `openviking: committing session=${OVSessionId} (wait=false), pendingTokens=${pendingTokens}, threshold=${cfg.commitTokenThreshold}`,
- );
const commitResult = await client.commitSession(OVSessionId, { wait: false, agentId });
+ const commitExtra = cfg.logFindRequests
+ ? ` ${toJsonLog({ captured: [trimForLog(turnText, 260)] })}`
+ : "";
logger.info(
`openviking: committed session=${OVSessionId}, ` +
`status=${commitResult.status}, archived=${commitResult.archived ?? false}, ` +
- `task_id=${commitResult.task_id ?? "none"} ${toJsonLog({ captured: [trimForLog(turnText, 260)] })}`,
+ `task_id=${commitResult.task_id ?? "none"}${commitExtra}`,
);
diag("afterTurn_commit", OVSessionId, {
@@ -668,9 +803,24 @@ export function createMemoryOpenVikingContextEngine(params: {
taskId: commitResult.task_id ?? null,
extractedMemories: (commitResult as any).extracted_memories ?? null,
});
+ if (commitResult.task_id && cfg.logFindRequests) {
+ logger.info(
+ `openviking: Phase2 memory extraction runs asynchronously on the server (task_id=${commitResult.task_id}). ` +
+ "memories_extracted appears only after that task completes — not in this immediate response.",
+ );
+ if (cfg.logFindRequests) {
+ void pollPhase2ExtractionOutcome(
+ getClient,
+ commitResult.task_id,
+ agentId,
+ logger,
+ OVSessionId,
+ );
+ }
+ }
} catch (err) {
warnOrInfo(logger, `openviking: afterTurn failed: ${String(err)}`);
- diag("afterTurn_error", OVSessionId, {
+ diag("afterTurn_error", afterTurnParams.sessionId ?? "(unknown)", {
error: String(err),
});
}
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 68076f77b..c1c904bb0 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -28,7 +28,10 @@ import {
resolvePythonCommand,
prepareLocalPort,
} from "./process-manager.js";
-import { createMemoryOpenVikingContextEngine } from "./context-engine.js";
+import {
+ createMemoryOpenVikingContextEngine,
+ openClawSessionToOvStorageId,
+} from "./context-engine.js";
import type { ContextEngineWithCommit } from "./context-engine.js";
type PluginLogger = {
@@ -44,6 +47,27 @@ type HookAgentContext = {
sessionKey?: string;
};
+type SessionAgentLookup = {
+ agentId?: string;
+ sessionId?: string;
+ sessionKey?: string;
+ ovSessionId?: string;
+};
+
+type SessionAgentResolveBranch =
+ | "session_resolved"
+ | "config_only_fallback"
+ | "default_no_session";
+
+export type SessionAgentResolveResult = {
+ resolved: string;
+ resolvedBeforeSanitize: string;
+ branch: SessionAgentResolveBranch;
+ mappedResolvedAgentId: string | null;
+ aliases: string[];
+ fromExplicitBinding: boolean;
+};
+
type ToolDefinition = {
name: string;
label: string;
@@ -63,7 +87,10 @@ type OpenClawPluginApi = {
logger: PluginLogger;
registerTool: {
(tool: ToolDefinition, opts?: { name?: string; names?: string[] }): void;
- (factory: (ctx: ToolContext) => ToolDefinition): void;
+ (
+ factory: (ctx: ToolContext) => ToolDefinition,
+ opts?: { name?: string; names?: string[] },
+ ): void;
};
registerService: (service: {
id: string;
@@ -82,6 +109,151 @@ const MAX_OPENVIKING_STDERR_LINES = 200;
const MAX_OPENVIKING_STDERR_CHARS = 256_000;
const AUTO_RECALL_TIMEOUT_MS = 5_000;
+/**
+ * OpenViking `UserIdentifier` allows only [a-zA-Z0-9_-] for agent_id
+ * (see openviking_cli/session/user_id.py). OpenClaw ids may contain ":"
+ * (e.g. session keys); never send raw colons in X-OpenViking-Agent.
+ */
+export function sanitizeOpenVikingAgentIdHeader(raw: string): string {
+ const trimmed = raw.trim();
+ if (!trimmed) {
+ return "default";
+ }
+ const normalized = trimmed
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
+ .replace(/_+/g, "_")
+ .replace(/^_|_$/g, "");
+ return normalized.length > 0 ? normalized : "ov_agent";
+}
+
+function extractAgentIdFromSessionKey(sessionKey?: string): string | undefined {
+ const raw = typeof sessionKey === "string" ? sessionKey.trim() : "";
+ if (!raw) {
+ return undefined;
+ }
+
+ const match = raw.match(/^agent:([^:]+):/);
+ const agentId = match?.[1]?.trim();
+ return agentId || undefined;
+}
+
+function collectSessionAgentAliases(
+ sessionId?: string,
+ sessionKey?: string,
+ ovSessionId?: string,
+): string[] {
+ const aliases = new Set<string>();
+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";
+ const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";
+ const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";
+
+ if (sid) {
+ aliases.add(sid);
+ }
+ if (sk) {
+ aliases.add(sk);
+ }
+ if (ovSid) {
+ aliases.add(ovSid);
+ }
+
+ if (!ovSid && (sid || sk)) {
+ try {
+ aliases.add(
+ openClawSessionToOvStorageId(
+ sid || undefined,
+ sk || undefined,
+ ),
+ );
+ } catch {
+ /* need a resolvable OpenClaw session identity */
+ }
+ }
+
+ return [...aliases];
+}
+
+export function createSessionAgentResolver(configAgentId: string) {
+ const sessionAgentIds = new Map<string, string>();
+
+ const remember = (ctx: SessionAgentLookup): void => {
+ const sessionScopedAgentId =
+ extractAgentIdFromSessionKey(ctx.sessionKey) ||
+ extractAgentIdFromSessionKey(ctx.sessionId);
+ const rawAgentId =
+ (typeof ctx.agentId === "string" ? ctx.agentId.trim() : "") ||
+ sessionScopedAgentId ||
+ "";
+ if (!rawAgentId) {
+ return;
+ }
+
+ const resolvedBeforeSanitize =
+ !configAgentId || configAgentId === "default"
+ ? rawAgentId
+ : `${configAgentId}_${rawAgentId}`;
+ const resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);
+ for (const alias of collectSessionAgentAliases(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId)) {
+ sessionAgentIds.set(alias, resolved);
+ }
+ };
+
+ const resolve = (
+ sessionId?: string,
+ sessionKey?: string,
+ ovSessionId?: string,
+ ): SessionAgentResolveResult => {
+ const aliases = collectSessionAgentAliases(sessionId, sessionKey, ovSessionId);
+ const mappedAlias = aliases.find((alias) => sessionAgentIds.has(alias));
+ const mappedResolvedAgentId = mappedAlias ? sessionAgentIds.get(mappedAlias) : undefined;
+ const sessionScopedAgentId =
+ extractAgentIdFromSessionKey(sessionKey) ||
+ extractAgentIdFromSessionKey(sessionId);
+
+ let resolvedBeforeSanitize: string;
+ let resolved: string;
+ let branch: SessionAgentResolveBranch;
+
+ if (mappedResolvedAgentId) {
+ resolvedBeforeSanitize = mappedResolvedAgentId;
+ resolved = mappedResolvedAgentId;
+ branch = "session_resolved";
+ } else if (sessionScopedAgentId) {
+ resolvedBeforeSanitize =
+ !configAgentId || configAgentId === "default"
+ ? sessionScopedAgentId
+ : `${configAgentId}_${sessionScopedAgentId}`;
+ resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);
+ branch = "session_resolved";
+ } else if (!configAgentId || configAgentId === "default") {
+ resolvedBeforeSanitize = "default";
+ resolved = "default";
+ branch = "default_no_session";
+ } else {
+ resolvedBeforeSanitize = configAgentId;
+ resolved = sanitizeOpenVikingAgentIdHeader(configAgentId);
+ branch = "config_only_fallback";
+ }
+
+ // Only explicit agent observations are persisted via remember().
+ // Fallback values must stay ephemeral so a later real ctx.agentId
+ // can safely take over without inheriting a stale default binding.
+ return {
+ resolved,
+ resolvedBeforeSanitize,
+ branch,
+ mappedResolvedAgentId: mappedResolvedAgentId ?? null,
+ aliases,
+ fromExplicitBinding: !!(mappedResolvedAgentId || sessionScopedAgentId),
+ };
+ };
+
+ return {
+ remember,
+ resolve,
+ };
+}
+
function totalCommitMemories(r: CommitSessionResult): number {
const m = r.memories_extracted;
if (!m || typeof m !== "object") return 0;
@@ -96,8 +268,39 @@ const contextEnginePlugin = {
configSchema: memoryOpenVikingConfigSchema,
register(api: OpenClawPluginApi) {
+ const rawCfg =
+ api.pluginConfig && typeof api.pluginConfig === "object" && !Array.isArray(api.pluginConfig)
+ ? (api.pluginConfig as Record<string, unknown>)
+ : {};
const cfg = memoryOpenVikingConfigSchema.parse(api.pluginConfig);
- const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}`;
+ const rawAgentId = rawCfg.agentId;
+ if (cfg.logFindRequests) {
+ api.logger.info(
+ "openviking: routing debug logging enabled (config logFindRequests, or env OPENVIKING_LOG_ROUTING=1 / OPENVIKING_DEBUG=1)",
+ );
+ }
+ const verboseRoutingInfo = (message: string) => {
+ if (cfg.logFindRequests) {
+ api.logger.info(message);
+ }
+ };
+ verboseRoutingInfo(
+ `openviking: loaded plugin config agentId="${cfg.agentId}" ` +
+ `(raw plugins.entries.openviking.config.agentId=${JSON.stringify(rawAgentId ?? "(missing)")}; ` +
+ `${
+ cfg.agentId !== "default"
+ ? "non-default → X-OpenViking-Agent is <configAgentId>_<ctx.agentId> (sanitized to [a-zA-Z0-9_-]) when hooks expose session agent; config-only if ctx.agentId unknown"
+ : 'default → X-OpenViking-Agent follows OpenClaw ctx.agentId per session (e.g. "main")'
+ })`,
+ );
+ const routingDebugLog = cfg.logFindRequests
+ ? (msg: string) => {
+ api.logger.info(msg);
+ }
+ : undefined;
+ const tenantAccount = "";
+ const tenantUser = "";
+ const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}:${tenantAccount}:${tenantUser}:${cfg.agentId}:${cfg.logFindRequests ? "1" : "0"}`;
let clientPromise: Promise<OpenVikingClient>;
let localProcess: ReturnType<typeof spawn> | null = null;
@@ -140,13 +343,23 @@ const contextEnginePlugin = {
}
}
} else {
- clientPromise = Promise.resolve(new OpenVikingClient(cfg.baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs));
+ clientPromise = Promise.resolve(
+ new OpenVikingClient(
+ cfg.baseUrl,
+ cfg.apiKey,
+ cfg.agentId,
+ cfg.timeoutMs,
+ tenantAccount,
+ tenantUser,
+ routingDebugLog,
+ ),
+ );
}
const getClient = (): Promise<OpenVikingClient> => clientPromise;
api.registerTool(
- {
+ (ctx: ToolContext) => ({
name: "memory_recall",
label: "Memory Recall (OpenViking)",
description:
@@ -164,6 +377,8 @@ const contextEnginePlugin = {
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const { query } = params as { query: string };
const limit =
typeof (params as { limit?: number }).limit === "number"
@@ -179,27 +394,47 @@ const contextEnginePlugin = {
: undefined;
const requestLimit = Math.max(limit * 4, 20);
+ const recallClient = await getClient();
+ if (cfg.logFindRequests) {
+ api.logger.info(
+ `openviking: memory_recall X-OpenViking-Agent="${agentId}" ` +
+ `(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,
+ );
+ }
+
let result;
if (targetUri) {
// 如果指定了目标 URI,只检索该位置
- result = await (await getClient()).find(query, {
- targetUri,
- limit: requestLimit,
- scoreThreshold: 0,
- });
+ result = await recallClient.find(
+ query,
+ {
+ targetUri,
+ limit: requestLimit,
+ scoreThreshold: 0,
+ },
+ agentId,
+ );
} else {
// 默认同时检索 user 和 agent 两个位置的记忆
const [userSettled, agentSettled] = await Promise.allSettled([
- (await getClient()).find(query, {
- targetUri: "viking://user/memories",
- limit: requestLimit,
- scoreThreshold: 0,
- }),
- (await getClient()).find(query, {
- targetUri: "viking://agent/memories",
- limit: requestLimit,
- scoreThreshold: 0,
- }),
+ recallClient.find(
+ query,
+ {
+ targetUri: "viking://user/memories",
+ limit: requestLimit,
+ scoreThreshold: 0,
+ },
+ agentId,
+ ),
+ recallClient.find(
+ query,
+ {
+ targetUri: "viking://agent/memories",
+ limit: requestLimit,
+ scoreThreshold: 0,
+ },
+ agentId,
+ ),
]);
const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };
const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };
@@ -241,12 +476,12 @@ const contextEnginePlugin = {
},
};
},
- },
+ }),
{ name: "memory_recall" },
);
api.registerTool(
- {
+ (ctx: ToolContext) => ({
name: "memory_store",
label: "Memory Store (OpenViking)",
description:
@@ -257,6 +492,8 @@ const contextEnginePlugin = {
sessionId: Type.Optional(Type.String({ description: "Existing OpenViking session ID" })),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ rememberSessionAgentId(ctx);
+ const storeAgentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const { text } = params as { text: string };
const role =
typeof (params as { role?: string }).role === "string"
@@ -264,19 +501,21 @@ const contextEnginePlugin = {
: "user";
const sessionIdIn = (params as { sessionId?: string }).sessionId;
- api.logger.info?.(
- `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${sessionIdIn ?? "auto"})`,
- );
+ if (cfg.logFindRequests) {
+ api.logger.info?.(
+ `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${sessionIdIn ?? "auto"})`,
+ );
+ }
let sessionId = sessionIdIn;
let usedTempSession = false;
- const storeAgentId = sessionId ? resolveAgentId(sessionId) : undefined;
try {
const c = await getClient();
if (!sessionId) {
sessionId = `memory-store-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
usedTempSession = true;
}
+ sessionId = openClawSessionToOvStorageId(sessionId, ctx.sessionKey);
await c.addSessionMessage(sessionId, role, text, storeAgentId);
const commitResult = await c.commitSession(sessionId, { wait: true, agentId: storeAgentId });
const memoriesCount = totalCommitMemories(commitResult);
@@ -339,12 +578,12 @@ const contextEnginePlugin = {
throw err;
}
},
- },
+ }),
{ name: "memory_store" },
);
api.registerTool(
- {
+ (ctx: ToolContext) => ({
name: "memory_forget",
label: "Memory Forget (OpenViking)",
description:
@@ -361,6 +600,9 @@ const contextEnginePlugin = {
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const client = await getClient();
const uri = (params as { uri?: string }).uri;
if (uri) {
if (!isMemoryUri(uri)) {
@@ -369,7 +611,7 @@ const contextEnginePlugin = {
details: { action: "rejected", uri },
};
}
- await (await getClient()).deleteUri(uri);
+ await client.deleteUri(uri, agentId);
return {
content: [{ type: "text", text: `Forgotten: ${uri}` }],
details: { action: "deleted", uri },
@@ -398,11 +640,15 @@ const contextEnginePlugin = {
: cfg.targetUri;
const requestLimit = Math.max(limit * 4, 20);
- const result = await (await getClient()).find(query, {
- targetUri,
- limit: requestLimit,
- scoreThreshold: 0,
- });
+ const result = await client.find(
+ query,
+ {
+ targetUri,
+ limit: requestLimit,
+ scoreThreshold: 0,
+ },
+ agentId,
+ );
const candidates = postProcessMemories(result.memories ?? [], {
limit: requestLimit,
scoreThreshold,
@@ -421,7 +667,7 @@ const contextEnginePlugin = {
}
const top = candidates[0];
if (candidates.length === 1 && clampScore(top.score) >= 0.85) {
- await (await getClient()).deleteUri(top.uri);
+ await client.deleteUri(top.uri, agentId);
return {
content: [{ type: "text", text: `Forgotten: ${top.uri}` }],
details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },
@@ -442,7 +688,7 @@ const contextEnginePlugin = {
details: { action: "candidates", candidates, scoreThreshold, requestLimit },
};
},
- },
+ }),
{ name: "memory_forget" },
);
api.registerTool((ctx: ToolContext) => ({
@@ -460,6 +706,7 @@ const contextEnginePlugin = {
}),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ rememberSessionAgentId(ctx);
const archiveId = String((params as { archiveId?: string }).archiveId ?? "").trim();
const sessionId = ctx.sessionId ?? "";
api.logger.info?.(`openviking: ov_archive_expand invoked (archiveId=${archiveId || "(empty)"}, sessionId=${sessionId || "(empty)"})`);
@@ -472,18 +719,24 @@ const contextEnginePlugin = {
};
}
- if (!sessionId) {
+ const sessionId = ctx.sessionId ?? "";
+ const sessionKey = ctx.sessionKey ?? "";
+ if (!sessionId && !sessionKey) {
return {
content: [{ type: "text", text: "Error: no active session." }],
details: { error: "no_session" },
};
}
+ const ovSessionId = openClawSessionToOvStorageId(
+ ctx.sessionId,
+ ctx.sessionKey,
+ );
try {
const client = await getClient();
- const agentId = resolveAgentId(sessionId);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const detail = await client.getSessionArchive(
- sessionId,
+ ovSessionId,
archiveId,
agentId,
);
@@ -507,6 +760,7 @@ const contextEnginePlugin = {
archiveId: detail.archive_id,
messageCount: detail.messages.length,
sessionId,
+ ovSessionId,
},
};
} catch (err) {
@@ -514,32 +768,44 @@ const contextEnginePlugin = {
api.logger.warn?.(`openviking: ov_archive_expand failed (archiveId=${archiveId}, sessionId=${sessionId}): ${msg}`);
return {
content: [{ type: "text", text: `Failed to expand ${archiveId}: ${msg}` }],
- details: { error: msg, archiveId, sessionId },
+ details: { error: msg, archiveId, sessionId, ovSessionId },
};
}
},
}));
let contextEngineRef: ContextEngineWithCommit | null = null;
-
- const sessionAgentIds = new Map<string, string>();
- const rememberSessionAgentId = (ctx: {
- agentId?: string;
- sessionId?: string;
- sessionKey?: string;
- }) => {
- if (!ctx?.agentId) {
- return;
- }
- if (ctx.sessionId) {
- sessionAgentIds.set(ctx.sessionId, ctx.agentId);
- }
- if (ctx.sessionKey) {
- sessionAgentIds.set(ctx.sessionKey, ctx.agentId);
+ const sessionAgentResolver = createSessionAgentResolver(cfg.agentId);
+ const rememberSessionAgentId = (ctx: SessionAgentLookup) => {
+ sessionAgentResolver.remember(ctx);
+ };
+ const resolveAgentId = (
+ sessionId?: string,
+ sessionKey?: string,
+ ovSessionId?: string,
+ ): string => {
+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";
+ const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";
+ const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";
+ const result = sessionAgentResolver.resolve(sid, sk, ovSid);
+ if (cfg.logFindRequests) {
+ api.logger.info(
+ `openviking: resolveAgentId ${JSON.stringify({
+ sessionId: sid || "(empty)",
+ sessionKey: sk || "(empty)",
+ ovSessionId: ovSid || "(empty)",
+ parsedConfigAgentId: cfg.agentId,
+ mappedResolvedAgentId: result.mappedResolvedAgentId,
+ resolvedBeforeSanitize: result.resolvedBeforeSanitize,
+ resolved: result.resolved,
+ branch: result.branch,
+ aliases: result.aliases,
+ fromExplicitBinding: result.fromExplicitBinding,
+ })}`,
+ );
}
+ return result.resolved;
};
- const resolveAgentId = (sessionId: string): string =>
- sessionAgentIds.get(sessionId) ?? cfg.agentId;
api.on("session_start", async (_event: unknown, ctx?: HookAgentContext) => {
rememberSessionAgentId(ctx ?? {});
@@ -550,8 +816,16 @@ const contextEnginePlugin = {
api.on("before_prompt_build", async (event: unknown, ctx?: HookAgentContext) => {
rememberSessionAgentId(ctx ?? {});
- const hookSessionId = ctx?.sessionId ?? "";
- const agentId = resolveAgentId(hookSessionId);
+ if (cfg.logFindRequests) {
+ api.logger.info(
+ `openviking: hook before_prompt_build ctx=${JSON.stringify({
+ sessionId: ctx?.sessionId,
+ sessionKey: ctx?.sessionKey,
+ agentId: ctx?.agentId,
+ })}`,
+ );
+ }
+ const agentId = resolveAgentId(ctx?.sessionId, ctx?.sessionKey);
let client: OpenVikingClient;
try {
client = await withTimeout(
@@ -577,7 +851,7 @@ const contextEnginePlugin = {
if (cfg.autoRecall && queryText.length >= 5) {
const precheck = await quickRecallPrecheck(cfg.mode, cfg.baseUrl, cfg.port, localProcess);
if (!precheck.ok) {
- api.logger.info(
+ verboseRoutingInfo(
`openviking: skipping auto-recall because precheck failed (${precheck.reason})`,
);
} else {
@@ -629,10 +903,10 @@ const contextEnginePlugin = {
},
);
const memoryContext = memoryLines.join("\n");
- api.logger.info(
+ verboseRoutingInfo(
`openviking: injecting ${memoryLines.length} memories (~${estimatedTokens} tokens, budget=${cfg.recallTokenBudget})`,
);
- api.logger.info(
+ verboseRoutingInfo(
`openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,
);
prependContextParts.push(
@@ -657,7 +931,7 @@ const contextEnginePlugin = {
minChars: cfg.ingestReplyAssistMinChars,
});
if (decision.shouldAssist) {
- api.logger.info(
+ verboseRoutingInfo(
`openviking: ingest-reply-assist applied (reason=${decision.reason}, speakerTurns=${decision.speakerTurns}, chars=${decision.chars})`,
);
prependContextParts.push(
@@ -707,11 +981,12 @@ const contextEnginePlugin = {
logger: api.logger,
getClient,
resolveAgentId,
+ rememberSessionAgentId,
});
return contextEngineRef;
});
api.logger.info(
- "openviking: registered context-engine (before_prompt_build=auto-recall, afterTurn=auto-capture, assemble=archive+active)",
+ "openviking: registered context-engine (before_prompt_build=auto-recall, afterTurn=auto-capture, assemble=archive+active, session→OV id=uuid-or-sha256 + diag/Phase2 options)",
);
} else {
api.logger.warn(
@@ -793,7 +1068,11 @@ const contextEnginePlugin = {
child.stderr?.on("data", (chunk: Buffer) => {
const s = String(chunk).trim();
pushStderrChunk(s);
- api.logger.debug?.(`[openviking] ${s}`);
+ if (cfg.logFindRequests) {
+ api.logger.info(`[openviking-local] ${s}`);
+ } else {
+ api.logger.debug?.(`[openviking] ${s}`);
+ }
});
child.on("exit", (code: number | null, signal: string | null) => {
if (localProcess === child) {
@@ -805,7 +1084,15 @@ const contextEnginePlugin = {
});
try {
await waitForHealth(baseUrl, timeoutMs, intervalMs);
- const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs);
+ const client = new OpenVikingClient(
+ baseUrl,
+ cfg.apiKey,
+ cfg.agentId,
+ cfg.timeoutMs,
+ tenantAccount,
+ tenantUser,
+ routingDebugLog,
+ );
localClientCache.set(localCacheKey, { client, process: child });
resolveLocalClient!(client);
rejectLocalClient = null;
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index e6d918d4b..cd007ce29 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -25,7 +25,7 @@
"agentId": {
"label": "Agent ID",
"placeholder": "random unique ID",
- "help": "Identifies this agent to OpenViking. A random unique ID is generated if not set."
+ "help": "Instance prefix for X-OpenViking-Agent. Non-default: `<this>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-). default: use OpenClaw session agent only."
},
"apiKey": {
"label": "OpenViking API Key",
@@ -117,6 +117,11 @@
"label": "Standard diagnostics (diag JSON lines)",
"advanced": true,
"help": "Emit structured openviking: diag {...} for assemble/afterTurn. Set false to disable."
+ },
+ "logFindRequests": {
+ "label": "Log find requests",
+ "help": "Log tenant routing: /search/find + session messages/commit (X-OpenViking-*; not apiKey). Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1. Local mode: subprocess stderr at info when enabled.",
+ "advanced": true
}
},
"configSchema": {
@@ -188,6 +193,9 @@
},
"emitStandardDiagnostics": {
"type": "boolean"
+ },
+ "logFindRequests": {
+ "type": "boolean"
}
}
}
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index b10ca5916..ba322b617 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -109,15 +109,20 @@ async def readiness_check(request: Request):
@router.get("/api/v1/system/status", tags=["system"])
async def system_status(
- _ctx: RequestContext = Depends(get_request_context),
+ ctx: RequestContext = Depends(get_request_context),
):
- """Get system status."""
+ """Get system status.
+
+ ``result.user`` is the authenticated request's ``user_id`` (from API key or
+ headers), not the process-wide service default — clients use this to resolve
+ multi-tenant paths (e.g. OpenClaw plugin).
+ """
service = get_service()
return Response(
status="ok",
result={
"initialized": service._initialized,
- "user": service.user._user_id,
+ "user": ctx.user.user_id,
},
)