@openviking/openclaw-plugin 2026.11.19 → 2026.11.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -164,23 +164,28 @@ In this setup:
164
164
 
165
165
  The plugin writes and searches user-scoped memory through `viking://user/...`; OpenViking resolves that alias from the request tenant and actor-peer context. Deprecated agent URI paths are not used by the plugin.
166
166
 
167
- ## assemble Recall Flow
167
+ ## Auto-Recall Flow
168
168
 
169
169
  ![Automatic recall flow before prompt build](./images/openclaw-plugin-recall-flow.png)
170
170
 
171
- Auto-recall now runs through `assemble()`. OpenClaw calls the same context engine method in two shapes, and the plugin assigns different responsibilities to each shape:
171
+ Auto-recall runs in a `before_prompt_build` hook once per user turn and returns the memory block as `prependContext`. OpenClaw freezes that text into the admitted user turn and replays it unchanged on later model calls and turns, so the history prefix stays cacheable. `assemble()` keeps rebuilding history and adds the session guide and user profile to `systemPromptAddition`; it no longer injects per-turn recall.
172
172
 
173
- 1. Preflight assemble: params include `prompt`; `messages` is still old history. The plugin reads archive/session context back from OpenViking and rebuilds history.
174
- 2. transformContext assemble: params do not include `prompt`; the latest `messages` entry is already the current user turn. The plugin only runs long-term recall and prepends the memory block to that user message content.
173
+ OpenClaw dispatches `before_prompt_build` to a non-bundled plugin only with an explicit grant. `openclaw openviking setup` and the installer write it for you:
174
+
175
+ ```json
176
+ { "plugins": { "entries": { "openviking": { "hooks": { "allowConversationAccess": true } } } } }
177
+ ```
178
+
179
+ Without the grant (or with `allowPromptModification: false`, `allowPromptInjection: false` on older hosts), the plugin keeps the previous behavior and recalls inside `assemble()`: recall goes into `systemPromptAddition`, which changes every turn and can invalidate the provider prompt cache for the history that follows it.
175
180
 
176
181
  During recall, the plugin:
177
182
 
178
- 1. Extracts query text from the latest user message.
183
+ 1. Uses the current request text (`currentUserMessage`, falling back to `prompt` on older hosts) as the query.
179
184
  2. Resolves the agent routing for the current `sessionId/sessionKey`.
180
185
  3. Runs a quick availability precheck so model requests do not stall when OpenViking is unavailable.
181
186
  4. Sends one session-aware context search for the configured `recallTargetTypes` (`user,agent` by default; optionally `resource`; use `ov_archive_search` and `ov_archive_expand` to inspect raw session history).
182
187
  5. Lets OpenViking expand the query from session history, filter and rank candidates, apply cross-turn deduplication, select detail tiers, and assemble the result under the injection budget.
183
- 6. Prepends the server-rendered context inside `<relevant-memories>` to the current user message; it does not append a standalone synthetic user message.
188
+ 6. Returns the server-rendered context inside `<relevant-memories>`; retries of the same turn reuse the first result.
184
189
 
185
190
  ## Session Lifecycle
186
191
 
package/commands/setup.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  type SetupApiKeyProbeResult,
14
14
  type SetupHealthResult,
15
15
  } from "../services/setup/probe-service.js";
16
+ import { grantPromptRecallHook } from "../services/setup/config-writer.js";
16
17
 
17
18
  const HOME = os.homedir();
18
19
  const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");
@@ -392,7 +393,7 @@ function writeConfig(
392
393
  const entries = plugins.entries as Record<string, unknown>;
393
394
 
394
395
  const existingEntry = (entries.openviking as Record<string, unknown>) ?? {};
395
- entries.openviking = { ...existingEntry, config: pluginCfg };
396
+ entries.openviking = { ...existingEntry, hooks: grantPromptRecallHook(existingEntry.hooks), config: pluginCfg };
396
397
 
397
398
  ensureInstallRecord(plugins);
398
399
 
package/context-engine.ts CHANGED
@@ -94,6 +94,7 @@ type ContextEngine = {
94
94
  sessionId: string;
95
95
  sessionKey?: string;
96
96
  isHeartbeat?: boolean;
97
+ runtimeContext?: Record<string, unknown>;
97
98
  }) => Promise<{ status: "committed" | "duplicate" }>;
98
99
  compact: (params: {
99
100
  sessionId: string;
@@ -286,6 +287,8 @@ export function createMemoryOpenVikingContextEngine(params: {
286
287
  }) => void;
287
288
  queryConfigStore?: RuntimeQueryConfigStore;
288
289
  traceRecorder?: { record(entry: RecallTraceEntry): void; recordAndFlush?: (entry: RecallTraceEntry) => Promise<unknown> };
290
+ /** Auto-recall runs in before_prompt_build instead of assemble. */
291
+ recallViaPromptHook?: boolean;
289
292
  }): ContextEngineWithCommit {
290
293
  const {
291
294
  id,
@@ -298,6 +301,7 @@ export function createMemoryOpenVikingContextEngine(params: {
298
301
  rememberSessionAgentId,
299
302
  queryConfigStore,
300
303
  traceRecorder,
304
+ recallViaPromptHook,
301
305
  } = params;
302
306
 
303
307
  const diagEnabled = cfg.emitStandardDiagnostics;
@@ -398,6 +402,7 @@ export function createMemoryOpenVikingContextEngine(params: {
398
402
  tokenBudget,
399
403
  runtimeContext: assembleParams.runtimeContext,
400
404
  isMainAssemble,
405
+ recallViaPromptHook,
401
406
  cfg,
402
407
  getClient,
403
408
  logger,
@@ -442,6 +447,7 @@ export function createMemoryOpenVikingContextEngine(params: {
442
447
  prePromptMessageCount: 0, // Host already supplies the closed-turn range.
443
448
  isHeartbeat: commitParams.isHeartbeat,
444
449
  tokenBudget: 128_000, // Durable delivery does not carry a token budget.
450
+ runtimeContext: commitParams.runtimeContext,
445
451
  throwOnError: true,
446
452
  cfg,
447
453
  getClient,
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
6
6
  import { getEnv } from "../runtime-utils.js";
7
7
  import { cleanOpenVikingRequestHeaders, } from "../request-headers.js";
8
8
  import { createSetupNetworkProbes, } from "../services/setup/probe-service.js";
9
+ import { grantPromptRecallHook } from "../services/setup/config-writer.js";
9
10
  const HOME = os.homedir();
10
11
  const OPENCLAW_DIR = getEnv("OPENCLAW_STATE_DIR") || path.join(HOME, ".openclaw");
11
12
  const DEFAULT_REMOTE_URL = "http://127.0.0.1:1933";
@@ -322,7 +323,7 @@ function writeConfig(configPath, pluginCfg) {
322
323
  plugins.entries = {};
323
324
  const entries = plugins.entries;
324
325
  const existingEntry = entries.openviking ?? {};
325
- entries.openviking = { ...existingEntry, config: pluginCfg };
326
+ entries.openviking = { ...existingEntry, hooks: grantPromptRecallHook(existingEntry.hooks), config: pluginCfg };
326
327
  ensureInstallRecord(plugins);
327
328
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
328
329
  }
@@ -145,7 +145,7 @@ function usesDeferredTurnCapture(version) {
145
145
  return year > 2026 || (year === 2026 && (month > 9 || (month === 9 && day >= 3)));
146
146
  }
147
147
  export function createMemoryOpenVikingContextEngine(params) {
148
- const { id, name, version, cfg, logger, getClient, resolveAgentId, rememberSessionAgentId, queryConfigStore, traceRecorder, } = params;
148
+ const { id, name, version, cfg, logger, getClient, resolveAgentId, rememberSessionAgentId, queryConfigStore, traceRecorder, recallViaPromptHook, } = params;
149
149
  const diagEnabled = cfg.emitStandardDiagnostics;
150
150
  const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);
151
151
  const diag = (stage, sessionId, data) => emitDiag(logger, stage, sessionId, data, diagEnabled);
@@ -218,6 +218,7 @@ export function createMemoryOpenVikingContextEngine(params) {
218
218
  tokenBudget,
219
219
  runtimeContext: assembleParams.runtimeContext,
220
220
  isMainAssemble,
221
+ recallViaPromptHook,
221
222
  cfg,
222
223
  getClient,
223
224
  logger,
@@ -261,6 +262,7 @@ export function createMemoryOpenVikingContextEngine(params) {
261
262
  prePromptMessageCount: 0, // Host already supplies the closed-turn range.
262
263
  isHeartbeat: commitParams.isHeartbeat,
263
264
  tokenBudget: 128_000, // Durable delivery does not carry a token budget.
265
+ runtimeContext: commitParams.runtimeContext,
264
266
  throwOnError: true,
265
267
  cfg,
266
268
  getClient,
package/dist/index.js CHANGED
@@ -18,6 +18,8 @@ import { registerOpenVikingArchiveTools } from "./plugin/openviking-archive-tool
18
18
  import { createOpenVikingImportRuntime } from "./plugin/openviking-import-runtime.js";
19
19
  import { registerOpenVikingImportTools } from "./plugin/openviking-import-tools.js";
20
20
  import { registerOpenVikingLifecycleHooks } from "./plugin/openviking-lifecycle-hooks.js";
21
+ import { promptRecallHookGranted, registerOpenVikingPromptRecallHook } from "./plugin/openviking-prompt-recall-hook.js";
22
+ import { recallForPromptHook } from "./services/context-lifecycle-service.js";
21
23
  import { registerOpenVikingMemoryRecallTools } from "./plugin/openviking-memory-recall-tools.js";
22
24
  import { registerOpenVikingMemoryTools } from "./plugin/openviking-memory-tools.js";
23
25
  import { registerOpenVikingQueryTools } from "./plugin/openviking-query-tools.js";
@@ -233,6 +235,25 @@ const contextEnginePlugin = {
233
235
  getContextEngine,
234
236
  logger: api.logger,
235
237
  });
238
+ const recallViaPromptHook = cfg.autoRecall
239
+ && promptRecallHookGranted(api.config, api.id ?? contextEnginePlugin.id);
240
+ if (recallViaPromptHook) {
241
+ registerOpenVikingPromptRecallHook({
242
+ api,
243
+ cfg,
244
+ logger: api.logger,
245
+ getClient,
246
+ resolveAgentId,
247
+ queryConfigStore,
248
+ traceRecorder,
249
+ isBypassedSession,
250
+ recall: recallForPromptHook,
251
+ });
252
+ }
253
+ else if (cfg.autoRecall) {
254
+ api.logger.info(`openviking: auto-recall runs in assemble; set plugins.entries.${api.id ?? contextEnginePlugin.id}.hooks.allowConversationAccess=true ` +
255
+ "to recall through before_prompt_build and keep the prompt cache stable");
256
+ }
236
257
  registerOpenVikingContextEngine({
237
258
  api,
238
259
  plugin: contextEnginePlugin,
@@ -244,6 +265,7 @@ const contextEnginePlugin = {
244
265
  rememberSessionAgentId,
245
266
  queryConfigStore,
246
267
  traceRecorder,
268
+ recallViaPromptHook,
247
269
  createContextEngine: createMemoryOpenVikingContextEngine,
248
270
  setContextEngineRef,
249
271
  });
@@ -16,9 +16,10 @@ export function registerOpenVikingContextEngine(deps) {
16
16
  rememberSessionAgentId: deps.rememberSessionAgentId,
17
17
  queryConfigStore: deps.queryConfigStore,
18
18
  traceRecorder: deps.traceRecorder,
19
+ recallViaPromptHook: deps.recallViaPromptHook,
19
20
  });
20
21
  deps.setContextEngineRef(contextEngine);
21
22
  return contextEngine;
22
23
  });
23
- deps.logger.info("openviking: registered context-engine (assemble=archive+active+auto-recall, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)");
24
+ deps.logger.info(`openviking: registered context-engine (assemble=archive+active${deps.recallViaPromptHook ? "" : "+auto-recall"}, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)`);
24
25
  }
@@ -0,0 +1,67 @@
1
+ const RECALLED_TURNS_MAX = 64;
2
+ // Covers the health precheck and client setup that run outside autoRecallTimeoutMs.
3
+ const RECALL_HOOK_HEADROOM_MS = 2_000;
4
+ /**
5
+ * OpenClaw registers before_prompt_build for a non-bundled plugin only with an
6
+ * explicit conversation-access grant. Without it, recall stays on assemble.
7
+ */
8
+ export function promptRecallHookGranted(hostConfig, pluginId) {
9
+ const entries = hostConfig?.plugins?.entries;
10
+ const hooks = entries?.[pluginId]?.hooks;
11
+ // Newer OpenClaw reads allowPromptModification; older hosts read allowPromptInjection.
12
+ return hooks?.allowConversationAccess === true
13
+ && hooks.allowPromptModification !== false
14
+ && hooks.allowPromptInjection !== false;
15
+ }
16
+ /**
17
+ * Recall once per admitted user turn and return it as prependContext. OpenClaw
18
+ * freezes that text into the turn and replays it unchanged, so the history
19
+ * prefix stays cacheable, unlike a per-turn systemPromptAddition.
20
+ */
21
+ export function registerOpenVikingPromptRecallHook(deps) {
22
+ const { api, cfg, logger, isBypassedSession, recall, ...recallDeps } = deps;
23
+ // Retries and model fallback rebuild the prompt for the same admission; reuse
24
+ // the first result instead of searching again into the server cooldown.
25
+ const recalledTurns = new Map();
26
+ api.on("before_prompt_build", async (event, ctx) => {
27
+ if (!cfg.autoRecall)
28
+ return undefined;
29
+ const sessionId = ctx?.sessionId ?? ctx?.sessionKey;
30
+ if (!sessionId || isBypassedSession(ctx))
31
+ return undefined;
32
+ const { prompt, currentUserMessage, currentUserMessageId } = (event ?? {});
33
+ // An explicit empty currentUserMessage means no textual request; `prompt` may hold rebuilt history.
34
+ const text = typeof currentUserMessage === "string" ? currentUserMessage : typeof prompt === "string" ? prompt : "";
35
+ const turnKey = typeof currentUserMessageId === "string" && currentUserMessageId
36
+ ? `${sessionId}\u0000${currentUserMessageId}`
37
+ : undefined;
38
+ let block = turnKey ? recalledTurns.get(turnKey) : undefined;
39
+ if (block === undefined) {
40
+ try {
41
+ block = await recall({
42
+ ...recallDeps,
43
+ cfg,
44
+ logger,
45
+ sessionId,
46
+ sessionKey: ctx?.sessionKey,
47
+ runtimeContext: ctx?.senderId ? { senderId: ctx.senderId } : undefined,
48
+ prompt: text,
49
+ });
50
+ }
51
+ catch (err) {
52
+ logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
53
+ return undefined;
54
+ }
55
+ if (turnKey) {
56
+ recalledTurns.set(turnKey, block);
57
+ if (recalledTurns.size > RECALLED_TURNS_MAX) {
58
+ recalledTurns.delete(recalledTurns.keys().next().value);
59
+ }
60
+ }
61
+ }
62
+ return block ? { prependContext: block } : undefined;
63
+ }, {
64
+ // OpenClaw otherwise bounds before_prompt_build at 15s; explicit host hook policy still wins.
65
+ timeoutMs: cfg.autoRecallTimeoutMs + RECALL_HOOK_HEADROOM_MS,
66
+ });
67
+ }
@@ -21,11 +21,10 @@ export function resolveOpenVikingMessagePeerId(params) {
21
21
  return undefined;
22
22
  }
23
23
  /**
24
- * Peer scoping is soft isolation. OpenClaw does not hand every path a sender
25
- * (context-engine assemble gets no runtimeContext; cron and heartbeat turns
26
- * have no sender at all), so a missing one widens to the unscoped request a
27
- * caller without X-OpenViking-Actor-Peer gets, with a warning, rather than
28
- * taking OpenViking away for the turn.
24
+ * Peer scoping is soft isolation. OpenClaw may not hand every path a sender
25
+ * (for example, cron and heartbeat turns have no sender at all), so a missing
26
+ * one widens to the unscoped request a caller without X-OpenViking-Actor-Peer
27
+ * gets, with a warning, rather than taking OpenViking away for the turn.
29
28
  */
30
29
  export function resolveOpenVikingActorPeerId(params) {
31
30
  const actorPeerId = resolveOpenVikingMessagePeerId({
@@ -235,7 +235,7 @@ async function readProfileBlock(client, actorPeerId, timeoutMs, logger) {
235
235
  .filter(Boolean)
236
236
  .join("\n\n");
237
237
  }
238
- async function recallForAssemble(params, recallQuery, client, routing) {
238
+ async function recallForAssemble(params, recallQuery, client, routing, dedupTurns) {
239
239
  const { sessionId, sessionKey, cfg, queryConfigStore, logger, traceRecorder } = params;
240
240
  const { ovSessionId, agentId, actorPeerId } = routing;
241
241
  const queryConfig = await queryConfigStore?.getEffective({
@@ -259,10 +259,18 @@ async function recallForAssemble(params, recallQuery, client, routing) {
259
259
  ovSessionId,
260
260
  queryTruncated: recallQuery.truncated,
261
261
  rawUserTextPreview: recallQuery.query,
262
- // System additions are transient; the next turn must be able to recall the same URI.
263
- dedupTurns: params.isMainAssemble ? 0 : undefined,
262
+ dedupTurns,
264
263
  });
265
264
  }
265
+ // Recall for before_prompt_build. The host freezes prependContext into the
266
+ // admitted user turn and replays it byte-for-byte, so the default cooldown applies.
267
+ export async function recallForPromptHook(params) {
268
+ const query = prepareRecallQuery(params.prompt);
269
+ if (query.query.length < 5)
270
+ return "";
271
+ const recall = await recallForAssemble(params, query, await params.getClient(), resolveAssembleRouting(params));
272
+ return recall.block ?? "";
273
+ }
266
274
  export async function assembleOpenVikingSession(params) {
267
275
  const assembled = await assembleSessionContext(params);
268
276
  // Current OpenClaw supplies the pending turn separately from history. Keep
@@ -270,13 +278,14 @@ export async function assembleOpenVikingSession(params) {
270
278
  if (!params.isMainAssemble || !params.cfg.autoRecall || params.isBypassedSession(params)) {
271
279
  return assembled;
272
280
  }
273
- const query = prepareRecallQuery(params.prompt ?? "");
281
+ const query = prepareRecallQuery(params.recallViaPromptHook ? "" : params.prompt ?? "");
274
282
  try {
275
283
  const routing = resolveAssembleRouting(params);
276
284
  const client = await params.getClient();
277
285
  const [profileBlock, recallBlock] = await Promise.all([
278
286
  readProfileBlock(client, routing.actorPeerId, Math.min(params.cfg.autoRecallTimeoutMs ?? PROFILE_READ_TIMEOUT_MS, PROFILE_READ_TIMEOUT_MS), params.logger),
279
- query.query.length < 5 ? "" : recallForAssemble(params, query, client, routing)
287
+ // System additions are transient; the next turn must be able to recall the same URI.
288
+ query.query.length < 5 ? "" : recallForAssemble(params, query, client, routing, 0)
280
289
  .then((recall) => recall.block)
281
290
  .catch((err) => {
282
291
  params.logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
@@ -332,6 +341,9 @@ async function assembleSessionContext(params) {
332
341
  if (!cfg.autoRecall) {
333
342
  return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_auto_recall_disabled", liveMessages: messages, originalTokens });
334
343
  }
344
+ if (params.recallViaPromptHook) {
345
+ return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_recall_via_prompt_hook", liveMessages: messages, originalTokens });
346
+ }
335
347
  if (hasAutoRecallBlock(latestMessage)) {
336
348
  return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_recall_already_injected", liveMessages: messages, originalTokens });
337
349
  }
@@ -0,0 +1,109 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ export const defaultSetupIO = {
4
+ readConfig: readOpenClawConfig,
5
+ writeConfig: writeOpenClawConfigFile,
6
+ backupConfig,
7
+ };
8
+ export function readOpenClawConfig(configPath) {
9
+ if (!fs.existsSync(configPath))
10
+ return {};
11
+ try {
12
+ return JSON.parse(fs.readFileSync(configPath, "utf-8"));
13
+ }
14
+ catch {
15
+ return {};
16
+ }
17
+ }
18
+ function writeOpenClawConfigFile(configPath, config) {
19
+ const configDir = path.dirname(configPath);
20
+ if (!fs.existsSync(configDir))
21
+ fs.mkdirSync(configDir, { recursive: true });
22
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
23
+ }
24
+ export function backupConfig(configPath) {
25
+ if (!fs.existsSync(configPath))
26
+ return null;
27
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
28
+ const backupPath = `${configPath}.bak.${timestamp}`;
29
+ try {
30
+ fs.copyFileSync(configPath, backupPath);
31
+ return backupPath;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ export function getExistingPluginConfig(config) {
38
+ const plugins = config.plugins;
39
+ if (!plugins)
40
+ return null;
41
+ const entries = plugins.entries;
42
+ if (!entries)
43
+ return null;
44
+ const entry = entries.openviking;
45
+ if (!entry)
46
+ return null;
47
+ const cfg = entry.config;
48
+ return cfg && cfg.mode ? cfg : null;
49
+ }
50
+ export function ensureInstallRecord(plugins) {
51
+ const installs = plugins.installs;
52
+ if (installs && typeof installs === "object") {
53
+ delete installs.openviking;
54
+ }
55
+ if (!plugins.allow)
56
+ plugins.allow = [];
57
+ const allow = plugins.allow;
58
+ if (!allow.includes("openviking")) {
59
+ allow.push("openviking");
60
+ }
61
+ }
62
+ // Auto-recall uses before_prompt_build, which OpenClaw only dispatches to a
63
+ // non-bundled plugin with conversation access. An explicit false is kept.
64
+ export function grantPromptRecallHook(hooks) {
65
+ const existing = hooks && typeof hooks === "object" && !Array.isArray(hooks)
66
+ ? hooks
67
+ : {};
68
+ return existing.allowConversationAccess === false ? existing : { ...existing, allowConversationAccess: true };
69
+ }
70
+ export function writeOpenVikingConfig(configPath, pluginCfg, io = defaultSetupIO) {
71
+ io.backupConfig(configPath);
72
+ const config = io.readConfig(configPath);
73
+ if (!config.plugins)
74
+ config.plugins = {};
75
+ const plugins = config.plugins;
76
+ if (!plugins.entries)
77
+ plugins.entries = {};
78
+ const entries = plugins.entries;
79
+ const existingEntry = entries.openviking ?? {};
80
+ entries.openviking = { ...existingEntry, hooks: grantPromptRecallHook(existingEntry.hooks), config: pluginCfg };
81
+ ensureInstallRecord(plugins);
82
+ io.writeConfig(configPath, config);
83
+ }
84
+ export function activateContextEngineSlot(configPath, force, io = defaultSetupIO) {
85
+ const config = io.readConfig(configPath);
86
+ if (!config.plugins)
87
+ config.plugins = {};
88
+ const plugins = config.plugins;
89
+ if (!plugins.slots)
90
+ plugins.slots = {};
91
+ const slots = plugins.slots;
92
+ const current = slots.contextEngine;
93
+ if (current === "openviking")
94
+ return { activated: false, replaced: false };
95
+ if (current && current !== "openviking" && !force) {
96
+ return { activated: false, previousOwner: current, replaced: false };
97
+ }
98
+ slots.contextEngine = "openviking";
99
+ io.writeConfig(configPath, config);
100
+ return { activated: true, previousOwner: current || undefined, replaced: !!current };
101
+ }
102
+ export function isContextEngineSlotActive(configPath, io = defaultSetupIO) {
103
+ const config = io.readConfig(configPath);
104
+ const plugins = config.plugins;
105
+ if (!plugins)
106
+ return false;
107
+ const slots = plugins.slots;
108
+ return slots?.contextEngine === "openviking";
109
+ }
package/index.ts CHANGED
@@ -22,6 +22,8 @@ import { registerOpenVikingArchiveTools } from "./plugin/openviking-archive-tool
22
22
  import { createOpenVikingImportRuntime } from "./plugin/openviking-import-runtime.js";
23
23
  import { registerOpenVikingImportTools } from "./plugin/openviking-import-tools.js";
24
24
  import { registerOpenVikingLifecycleHooks } from "./plugin/openviking-lifecycle-hooks.js";
25
+ import { promptRecallHookGranted, registerOpenVikingPromptRecallHook } from "./plugin/openviking-prompt-recall-hook.js";
26
+ import { recallForPromptHook } from "./services/context-lifecycle-service.js";
25
27
  import { registerOpenVikingMemoryRecallTools } from "./plugin/openviking-memory-recall-tools.js";
26
28
  import { registerOpenVikingMemoryTools } from "./plugin/openviking-memory-tools.js";
27
29
  import { registerOpenVikingQueryTools } from "./plugin/openviking-query-tools.js";
@@ -78,6 +80,7 @@ type HookAgentContext = {
78
80
  agentId?: string;
79
81
  sessionId?: string;
80
82
  sessionKey?: string;
83
+ senderId?: string;
81
84
  };
82
85
 
83
86
  type ToolDefinition = {
@@ -96,7 +99,9 @@ type ToolContext = {
96
99
  };
97
100
 
98
101
  type OpenClawPluginApi = {
102
+ id?: string;
99
103
  runtime?: { version?: string };
104
+ config?: unknown;
100
105
  pluginConfig?: unknown;
101
106
  openVikingTransport?: HttpTransport;
102
107
  logger: PluginLogger;
@@ -138,7 +143,7 @@ type OpenClawPluginApi = {
138
143
  on: (
139
144
  hookName: string,
140
145
  handler: (event: unknown, ctx?: HookAgentContext) => unknown,
141
- opts?: { priority?: number },
146
+ opts?: { priority?: number; timeoutMs?: number },
142
147
  ) => void;
143
148
  };
144
149
 
@@ -387,6 +392,27 @@ const contextEnginePlugin = {
387
392
  logger: api.logger,
388
393
  });
389
394
 
395
+ const recallViaPromptHook = cfg.autoRecall
396
+ && promptRecallHookGranted(api.config, api.id ?? contextEnginePlugin.id);
397
+ if (recallViaPromptHook) {
398
+ registerOpenVikingPromptRecallHook({
399
+ api,
400
+ cfg,
401
+ logger: api.logger,
402
+ getClient,
403
+ resolveAgentId,
404
+ queryConfigStore,
405
+ traceRecorder,
406
+ isBypassedSession,
407
+ recall: recallForPromptHook,
408
+ });
409
+ } else if (cfg.autoRecall) {
410
+ api.logger.info(
411
+ `openviking: auto-recall runs in assemble; set plugins.entries.${api.id ?? contextEnginePlugin.id}.hooks.allowConversationAccess=true ` +
412
+ "to recall through before_prompt_build and keep the prompt cache stable",
413
+ );
414
+ }
415
+
390
416
  registerOpenVikingContextEngine({
391
417
  api,
392
418
  plugin: contextEnginePlugin,
@@ -398,6 +424,7 @@ const contextEnginePlugin = {
398
424
  rememberSessionAgentId,
399
425
  queryConfigStore,
400
426
  traceRecorder,
427
+ recallViaPromptHook,
401
428
  createContextEngine: createMemoryOpenVikingContextEngine,
402
429
  setContextEngineRef,
403
430
  });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "manifestVersion": "1.0",
3
- "pluginVersion": "2026.11.3",
3
+ "pluginVersion": "2026.11.19",
4
4
  "plugin": {
5
5
  "id": "openviking",
6
6
  "kind": "context-engine",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openviking/openclaw-plugin",
3
- "version": "2026.11.19",
3
+ "version": "2026.11.23",
4
4
  "displayName": "OpenViking",
5
5
  "description": "OpenClaw context-engine plugin — OpenViking AI memory, long-term memory, knowledge base, semantic search, RAG, context engine. 长期记忆 · 知识库 · 语义检索 · 上下文引擎",
6
6
  "type": "module",
@@ -36,6 +36,7 @@ export type OpenVikingContextEngineCreateParams<
36
36
  }) => void;
37
37
  queryConfigStore: TQueryConfigStore;
38
38
  traceRecorder: TTraceRecorder;
39
+ recallViaPromptHook?: boolean;
39
40
  };
40
41
 
41
42
  export type OpenVikingContextEngineRegistrationDeps<
@@ -56,6 +57,7 @@ export type OpenVikingContextEngineRegistrationDeps<
56
57
  rememberSessionAgentId: OpenVikingContextEngineCreateParams["rememberSessionAgentId"];
57
58
  queryConfigStore: TQueryConfigStore;
58
59
  traceRecorder: TTraceRecorder;
60
+ recallViaPromptHook?: boolean;
59
61
  createContextEngine: (params: OpenVikingContextEngineCreateParams<TCfg, TClient, TQueryConfigStore, TTraceRecorder, TLogger>) => TEngine;
60
62
  setContextEngineRef: (engine: TEngine) => void;
61
63
  };
@@ -90,11 +92,12 @@ export function registerOpenVikingContextEngine<
90
92
  rememberSessionAgentId: deps.rememberSessionAgentId,
91
93
  queryConfigStore: deps.queryConfigStore,
92
94
  traceRecorder: deps.traceRecorder,
95
+ recallViaPromptHook: deps.recallViaPromptHook,
93
96
  });
94
97
  deps.setContextEngineRef(contextEngine);
95
98
  return contextEngine;
96
99
  });
97
100
  deps.logger.info(
98
- "openviking: registered context-engine (assemble=archive+active+auto-recall, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)",
101
+ `openviking: registered context-engine (assemble=archive+active${deps.recallViaPromptHook ? "" : "+auto-recall"}, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)`,
99
102
  );
100
103
  }
@@ -0,0 +1,98 @@
1
+ import type { PromptHookRecallParams } from "../services/context-lifecycle-service.js";
2
+
3
+ export type PromptRecallHookContext = {
4
+ agentId?: string;
5
+ sessionId?: string;
6
+ sessionKey?: string;
7
+ senderId?: string;
8
+ };
9
+
10
+ type PromptRecallHookEvent = {
11
+ prompt?: unknown;
12
+ currentUserMessage?: unknown;
13
+ currentUserMessageId?: unknown;
14
+ };
15
+
16
+ export type OpenVikingPromptRecallHookApi = {
17
+ on: (
18
+ hookName: string,
19
+ handler: (event: unknown, ctx?: PromptRecallHookContext) => unknown,
20
+ opts?: { priority?: number; timeoutMs?: number },
21
+ ) => void;
22
+ };
23
+
24
+ export type OpenVikingPromptRecallHookDeps = Omit<PromptHookRecallParams, "sessionId" | "sessionKey" | "runtimeContext" | "prompt"> & {
25
+ api: OpenVikingPromptRecallHookApi;
26
+ isBypassedSession: (ctx?: { sessionId?: string; sessionKey?: string }) => boolean;
27
+ recall: (params: PromptHookRecallParams) => Promise<string>;
28
+ };
29
+
30
+ const RECALLED_TURNS_MAX = 64;
31
+ // Covers the health precheck and client setup that run outside autoRecallTimeoutMs.
32
+ const RECALL_HOOK_HEADROOM_MS = 2_000;
33
+
34
+ /**
35
+ * OpenClaw registers before_prompt_build for a non-bundled plugin only with an
36
+ * explicit conversation-access grant. Without it, recall stays on assemble.
37
+ */
38
+ export function promptRecallHookGranted(hostConfig: unknown, pluginId: string): boolean {
39
+ const entries = (hostConfig as { plugins?: { entries?: Record<string, unknown> } } | undefined)?.plugins?.entries;
40
+ const hooks = (entries?.[pluginId] as { hooks?: Record<string, unknown> } | undefined)?.hooks;
41
+ // Newer OpenClaw reads allowPromptModification; older hosts read allowPromptInjection.
42
+ return hooks?.allowConversationAccess === true
43
+ && hooks.allowPromptModification !== false
44
+ && hooks.allowPromptInjection !== false;
45
+ }
46
+
47
+ /**
48
+ * Recall once per admitted user turn and return it as prependContext. OpenClaw
49
+ * freezes that text into the turn and replays it unchanged, so the history
50
+ * prefix stays cacheable, unlike a per-turn systemPromptAddition.
51
+ */
52
+ export function registerOpenVikingPromptRecallHook(deps: OpenVikingPromptRecallHookDeps): void {
53
+ const { api, cfg, logger, isBypassedSession, recall, ...recallDeps } = deps;
54
+ // Retries and model fallback rebuild the prompt for the same admission; reuse
55
+ // the first result instead of searching again into the server cooldown.
56
+ const recalledTurns = new Map<string, string>();
57
+
58
+ api.on("before_prompt_build", async (event: unknown, ctx?: PromptRecallHookContext) => {
59
+ if (!cfg.autoRecall) return undefined;
60
+ const sessionId = ctx?.sessionId ?? ctx?.sessionKey;
61
+ if (!sessionId || isBypassedSession(ctx)) return undefined;
62
+
63
+ const { prompt, currentUserMessage, currentUserMessageId } = (event ?? {}) as PromptRecallHookEvent;
64
+ // An explicit empty currentUserMessage means no textual request; `prompt` may hold rebuilt history.
65
+ const text = typeof currentUserMessage === "string" ? currentUserMessage : typeof prompt === "string" ? prompt : "";
66
+ const turnKey = typeof currentUserMessageId === "string" && currentUserMessageId
67
+ ? `${sessionId}\u0000${currentUserMessageId}`
68
+ : undefined;
69
+
70
+ let block = turnKey ? recalledTurns.get(turnKey) : undefined;
71
+ if (block === undefined) {
72
+ try {
73
+ block = await recall({
74
+ ...recallDeps,
75
+ cfg,
76
+ logger,
77
+ sessionId,
78
+ sessionKey: ctx?.sessionKey,
79
+ runtimeContext: ctx?.senderId ? { senderId: ctx.senderId } : undefined,
80
+ prompt: text,
81
+ });
82
+ } catch (err) {
83
+ logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
84
+ return undefined;
85
+ }
86
+ if (turnKey) {
87
+ recalledTurns.set(turnKey, block);
88
+ if (recalledTurns.size > RECALLED_TURNS_MAX) {
89
+ recalledTurns.delete(recalledTurns.keys().next().value as string);
90
+ }
91
+ }
92
+ }
93
+ return block ? { prependContext: block } : undefined;
94
+ }, {
95
+ // OpenClaw otherwise bounds before_prompt_build at 15s; explicit host hook policy still wins.
96
+ timeoutMs: cfg.autoRecallTimeoutMs + RECALL_HOOK_HEADROOM_MS,
97
+ });
98
+ }
@@ -42,11 +42,10 @@ export function resolveOpenVikingMessagePeerId(params: {
42
42
  }
43
43
 
44
44
  /**
45
- * Peer scoping is soft isolation. OpenClaw does not hand every path a sender
46
- * (context-engine assemble gets no runtimeContext; cron and heartbeat turns
47
- * have no sender at all), so a missing one widens to the unscoped request a
48
- * caller without X-OpenViking-Actor-Peer gets, with a warning, rather than
49
- * taking OpenViking away for the turn.
45
+ * Peer scoping is soft isolation. OpenClaw may not hand every path a sender
46
+ * (for example, cron and heartbeat turns have no sender at all), so a missing
47
+ * one widens to the unscoped request a caller without X-OpenViking-Actor-Peer
48
+ * gets, with a warning, rather than taking OpenViking away for the turn.
50
49
  */
51
50
  export function resolveOpenVikingActorPeerId(params: {
52
51
  peerRole: OpenVikingPeerRole;
@@ -76,6 +76,8 @@ export type AssembleOpenVikingSessionParams = {
76
76
  tokenBudget: number;
77
77
  runtimeContext?: Record<string, unknown>;
78
78
  isMainAssemble: boolean;
79
+ /** before_prompt_build owns auto-recall; assemble keeps history and profile only. */
80
+ recallViaPromptHook?: boolean;
79
81
  cfg: any;
80
82
  getClient: () => Promise<OpenVikingClient>;
81
83
  logger: ContextEngineLifecycleLogger;
@@ -431,7 +433,7 @@ function isSessionNotFoundError(err: unknown): boolean {
431
433
  const PROFILE_MAX_CHARS = 8000;
432
434
  const PROFILE_READ_TIMEOUT_MS = 3000;
433
435
 
434
- function resolveAssembleRouting(params: AssembleOpenVikingSessionParams) {
436
+ function resolveAssembleRouting(params: RecallParams) {
435
437
  const { sessionId, sessionKey, cfg, resolveAgentId, logger } = params;
436
438
  const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);
437
439
  const sender = extractRuntimeSenderId(params.runtimeContext);
@@ -473,11 +475,17 @@ async function readProfileBlock(
473
475
  .join("\n\n");
474
476
  }
475
477
 
478
+ type RecallParams = Pick<
479
+ AssembleOpenVikingSessionParams,
480
+ "sessionId" | "sessionKey" | "runtimeContext" | "cfg" | "logger" | "resolveAgentId" | "queryConfigStore" | "traceRecorder"
481
+ >;
482
+
476
483
  async function recallForAssemble(
477
- params: AssembleOpenVikingSessionParams,
484
+ params: RecallParams,
478
485
  recallQuery: ReturnType<typeof prepareRecallQuery>,
479
486
  client: OpenVikingClient,
480
487
  routing: ReturnType<typeof resolveAssembleRouting>,
488
+ dedupTurns?: number,
481
489
  ) {
482
490
  const { sessionId, sessionKey, cfg, queryConfigStore, logger, traceRecorder } = params;
483
491
  const { ovSessionId, agentId, actorPeerId } = routing;
@@ -502,11 +510,24 @@ async function recallForAssemble(
502
510
  ovSessionId,
503
511
  queryTruncated: recallQuery.truncated,
504
512
  rawUserTextPreview: recallQuery.query,
505
- // System additions are transient; the next turn must be able to recall the same URI.
506
- dedupTurns: params.isMainAssemble ? 0 : undefined,
513
+ dedupTurns,
507
514
  });
508
515
  }
509
516
 
517
+ export type PromptHookRecallParams = RecallParams & {
518
+ prompt: string;
519
+ getClient: () => Promise<OpenVikingClient>;
520
+ };
521
+
522
+ // Recall for before_prompt_build. The host freezes prependContext into the
523
+ // admitted user turn and replays it byte-for-byte, so the default cooldown applies.
524
+ export async function recallForPromptHook(params: PromptHookRecallParams): Promise<string> {
525
+ const query = prepareRecallQuery(params.prompt);
526
+ if (query.query.length < 5) return "";
527
+ const recall = await recallForAssemble(params, query, await params.getClient(), resolveAssembleRouting(params));
528
+ return recall.block ?? "";
529
+ }
530
+
510
531
  export async function assembleOpenVikingSession(
511
532
  params: AssembleOpenVikingSessionParams,
512
533
  ): Promise<AssembleOpenVikingSessionResult> {
@@ -516,7 +537,7 @@ export async function assembleOpenVikingSession(
516
537
  if (!params.isMainAssemble || !params.cfg.autoRecall || params.isBypassedSession(params)) {
517
538
  return assembled;
518
539
  }
519
- const query = prepareRecallQuery(params.prompt ?? "");
540
+ const query = prepareRecallQuery(params.recallViaPromptHook ? "" : params.prompt ?? "");
520
541
 
521
542
  try {
522
543
  const routing = resolveAssembleRouting(params);
@@ -528,7 +549,8 @@ export async function assembleOpenVikingSession(
528
549
  Math.min(params.cfg.autoRecallTimeoutMs ?? PROFILE_READ_TIMEOUT_MS, PROFILE_READ_TIMEOUT_MS),
529
550
  params.logger,
530
551
  ),
531
- query.query.length < 5 ? "" : recallForAssemble(params, query, client, routing)
552
+ // System additions are transient; the next turn must be able to recall the same URI.
553
+ query.query.length < 5 ? "" : recallForAssemble(params, query, client, routing, 0)
532
554
  .then((recall) => recall.block)
533
555
  .catch((err) => {
534
556
  params.logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
@@ -606,6 +628,9 @@ async function assembleSessionContext(params: AssembleOpenVikingSessionParams):
606
628
  if (!cfg.autoRecall) {
607
629
  return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_auto_recall_disabled", liveMessages: messages, originalTokens });
608
630
  }
631
+ if (params.recallViaPromptHook) {
632
+ return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_recall_via_prompt_hook", liveMessages: messages, originalTokens });
633
+ }
609
634
  if (hasAutoRecallBlock(latestMessage)) {
610
635
  return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_recall_already_injected", liveMessages: messages, originalTokens });
611
636
  }
@@ -70,6 +70,15 @@ export function ensureInstallRecord(plugins: Record<string, unknown>): void {
70
70
  }
71
71
  }
72
72
 
73
+ // Auto-recall uses before_prompt_build, which OpenClaw only dispatches to a
74
+ // non-bundled plugin with conversation access. An explicit false is kept.
75
+ export function grantPromptRecallHook(hooks: unknown): Record<string, unknown> {
76
+ const existing = hooks && typeof hooks === "object" && !Array.isArray(hooks)
77
+ ? (hooks as Record<string, unknown>)
78
+ : {};
79
+ return existing.allowConversationAccess === false ? existing : { ...existing, allowConversationAccess: true };
80
+ }
81
+
73
82
  export function writeOpenVikingConfig(
74
83
  configPath: string,
75
84
  pluginCfg: Record<string, unknown>,
@@ -85,7 +94,7 @@ export function writeOpenVikingConfig(
85
94
  const entries = plugins.entries as Record<string, unknown>;
86
95
 
87
96
  const existingEntry = (entries.openviking as Record<string, unknown>) ?? {};
88
- entries.openviking = { ...existingEntry, config: pluginCfg };
97
+ entries.openviking = { ...existingEntry, hooks: grantPromptRecallHook(existingEntry.hooks), config: pluginCfg };
89
98
 
90
99
  ensureInstallRecord(plugins);
91
100