@openviking/openclaw-plugin 2026.9.1 → 2026.9.4

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.
@@ -0,0 +1,645 @@
1
+ // GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { compressRecallContext } from "./recall-compress-core.mjs";
6
+ const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
7
+ const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;
8
+ const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;
9
+ const STOPWORDS = new Set([
10
+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",
11
+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",
12
+ ]);
13
+ const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
14
+ const SOURCES = [
15
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
16
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
17
+ ];
18
+ const DEFAULT_CONTEXT_LIMIT = 10;
19
+ const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
20
+ const DEFAULT_REWRITE_MAX_BULLETS = 6;
21
+ const CODING_QUOTA_WEIGHTS = {
22
+ events: 1,
23
+ entities: 2,
24
+ preferences: 1,
25
+ experiences: 1,
26
+ resources: 3,
27
+ skills: 2,
28
+ };
29
+ let userSpaceCache = "";
30
+ export function estimateTokens(text) {
31
+ return text ? Math.ceil(String(text).length / 4) : 0;
32
+ }
33
+ function scaleQuotas(limit, weights) {
34
+ const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
35
+ const order = Object.keys(weights);
36
+ const quotas = Object.fromEntries(order.map((key) => [key, 0]));
37
+ if (slots < order.length) {
38
+ for (const key of order)
39
+ quotas[key] = 1;
40
+ return quotas;
41
+ }
42
+ for (const key of order)
43
+ quotas[key] = 1;
44
+ const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
45
+ const ideals = Object.fromEntries(order.map((key) => [key, slots * weights[key] / totalWeight]));
46
+ while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
47
+ const key = order.reduce((best, candidate) => (ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
48
+ ? candidate
49
+ : best));
50
+ quotas[key] += 1;
51
+ }
52
+ return quotas;
53
+ }
54
+ function legacyMemoryQuotas(limit) {
55
+ return {
56
+ ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
57
+ experiences: 0,
58
+ };
59
+ }
60
+ function codingQuotas(limit) {
61
+ return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
62
+ }
63
+ export function buildRecallEndpointBody(cfg = {}) {
64
+ const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
65
+ const body = {
66
+ query: "",
67
+ quotas: legacyMemoryQuotas(limit),
68
+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),
69
+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
70
+ render: true,
71
+ };
72
+ if (cfg.recallPeerScope === "actor")
73
+ body.peer_scope = "actor";
74
+ return body;
75
+ }
76
+ /**
77
+ * Body for the server-side context face. The plugin declares intent (coding
78
+ * purpose, budget, session) and leaves the mechanics — quota ratios, tier
79
+ * degradation, cross-turn dedup — to the server's defaults.
80
+ */
81
+ export function buildContextSearchBody(cfg = {}, options = {}) {
82
+ const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
83
+ const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
84
+ const maxTokens = Math.max(64, Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)));
85
+ const body = {
86
+ query: "",
87
+ mode: "context",
88
+ purpose: "coding",
89
+ score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
90
+ };
91
+ const limitConfigured = cfg.recallLimitConfigured === true;
92
+ const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
93
+ if (limitConfigured)
94
+ body.quotas = codingQuotas(limit);
95
+ if (maxTokensConfigured)
96
+ body.max_tokens = maxTokens;
97
+ if (cfg.recallPeerScope === "actor")
98
+ body.peer_scope = "actor";
99
+ const sessionId = String(options.sessionId || "").trim();
100
+ if (sessionId) {
101
+ body.session_id = sessionId;
102
+ const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
103
+ if (queryExpansionConfigured) {
104
+ body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
105
+ }
106
+ const dedupTurns = Number(cfg.recallDedupTurns);
107
+ const resolvedDedupTurns = Number.isFinite(dedupTurns)
108
+ ? Math.max(0, Math.floor(dedupTurns))
109
+ : 5;
110
+ if (resolvedDedupTurns > 0)
111
+ body.dedup_turns = resolvedDedupTurns;
112
+ }
113
+ const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
114
+ if (excludeUris.length)
115
+ body.exclude_uris = excludeUris;
116
+ if (rewriteMode === "server")
117
+ body.rewrite = true;
118
+ else if (rewriteMode === "auto" && !options.localCompressorAvailable)
119
+ body.rewrite = "auto";
120
+ const rewriteMaxBullets = Math.max(1, Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)));
121
+ const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
122
+ if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
123
+ body.rewrite_max_bullets = rewriteMaxBullets;
124
+ }
125
+ return body;
126
+ }
127
+ // The server pipeline is serial and each optional stage has its own fuse. A
128
+ // request is aborted client-side unless its deadline covers every stage it
129
+ // asked for, and aborting discards the whole response rather than just the
130
+ // stage that ran long.
131
+ //
132
+ // session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
133
+ // always -> retrieval, body reads, budget planning
134
+ // rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
135
+ //
136
+ // Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
137
+ // a quarter to spare.
138
+ const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
139
+ const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
140
+ /**
141
+ * HTTP deadline for one context request, or undefined to keep the caller's own.
142
+ *
143
+ * Derived from the request body, because the body is what states which server
144
+ * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
145
+ * that also spends the expansion or rewrite fuse.
146
+ */
147
+ export function contextRequestTimeoutMs(cfg = {}, body = {}) {
148
+ const wantsRewrite = body.rewrite !== undefined;
149
+ // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
150
+ // takes the expansion fuse back out of the budget.
151
+ const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
152
+ const configured = Number(cfg.recallContextTimeoutMs);
153
+ if (Number.isFinite(configured) && configured > 0)
154
+ return Math.max(1000, Math.floor(configured));
155
+ if (!wantsRewrite && !wantsExpansion)
156
+ return undefined;
157
+ const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
158
+ return Math.max(Number(cfg.timeoutMs) || 0, floor);
159
+ }
160
+ /**
161
+ * Strip the context-face fields a pre-context server rejects, converting the
162
+ * token budget back to v1's character budget.
163
+ */
164
+ export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
165
+ const body = buildRecallEndpointBody(cfg);
166
+ body.query = contextBody.query || "";
167
+ body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
168
+ if (contextBody.peer_scope)
169
+ body.peer_scope = contextBody.peer_scope;
170
+ return body;
171
+ }
172
+ function clampScore(v) {
173
+ if (typeof v !== "number" || Number.isNaN(v))
174
+ return 0;
175
+ return Math.max(0, Math.min(1, v));
176
+ }
177
+ function buildQueryProfile(query) {
178
+ const text = query.trim();
179
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
180
+ return {
181
+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),
182
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
183
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
184
+ };
185
+ }
186
+ function lexicalOverlapBoost(tokens, text) {
187
+ if (tokens.length === 0 || !text)
188
+ return 0;
189
+ const haystack = ` ${text.toLowerCase()} `;
190
+ let matched = 0;
191
+ for (const token of tokens.slice(0, 8)) {
192
+ if (haystack.includes(token))
193
+ matched += 1;
194
+ }
195
+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
196
+ }
197
+ function rankItem(item, profile) {
198
+ const base = clampScore(item.score);
199
+ const abstract = (item.abstract || item.overview || "").trim();
200
+ const cat = (item.category || "").toLowerCase();
201
+ const uri = (item.uri || "").toLowerCase();
202
+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;
203
+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;
204
+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;
205
+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);
206
+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;
207
+ }
208
+ function isEventOrCaseItem(item) {
209
+ const cat = (item.category || "").toLowerCase();
210
+ const uri = (item.uri || "").toLowerCase();
211
+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");
212
+ }
213
+ function dedupeItems(items) {
214
+ const seen = new Set();
215
+ const out = [];
216
+ for (const item of items) {
217
+ const key = isEventOrCaseItem(item)
218
+ ? `uri:${item.uri}`
219
+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);
220
+ if (seen.has(key))
221
+ continue;
222
+ seen.add(key);
223
+ out.push(item);
224
+ }
225
+ return out;
226
+ }
227
+ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
228
+ if (userSpaceCache)
229
+ return userSpaceCache;
230
+ let fallbackSpace = "default";
231
+ const status = await fetchJSON("/api/v1/system/status");
232
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
233
+ fallbackSpace = status.result.user.trim();
234
+ }
235
+ const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`, {}, { actorPeerId });
236
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
237
+ const spaces = lsRes.result
238
+ .filter((e) => e?.isDir)
239
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
240
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
241
+ if (spaces.length > 0) {
242
+ if (spaces.includes(fallbackSpace)) {
243
+ userSpaceCache = fallbackSpace;
244
+ return fallbackSpace;
245
+ }
246
+ if (spaces.includes("default")) {
247
+ userSpaceCache = "default";
248
+ return "default";
249
+ }
250
+ if (spaces.length === 1) {
251
+ userSpaceCache = spaces[0];
252
+ return spaces[0];
253
+ }
254
+ }
255
+ }
256
+ userSpaceCache = fallbackSpace;
257
+ return fallbackSpace;
258
+ }
259
+ async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
260
+ const trimmed = targetUri.trim().replace(/\/+$/, "");
261
+ // viking://~ is the home alias: the server expands it to the caller's own user
262
+ // space, so it needs no client-side rewrite.
263
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/"))
264
+ return trimmed;
265
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
266
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
267
+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
268
+ if (!m)
269
+ return trimmed;
270
+ const rawRest = (m[1] ?? "").trim();
271
+ if (!rawRest)
272
+ return trimmed;
273
+ const parts = rawRest.split("/").filter(Boolean);
274
+ if (parts.length === 0)
275
+ return trimmed;
276
+ if (!USER_RESERVED_DIRS.has(parts[0]))
277
+ return trimmed;
278
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
279
+ return `viking://user/${space}/${parts.join("/")}`;
280
+ }
281
+ async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {
282
+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);
283
+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };
284
+ const res = await fetchJSON("/api/v1/search/find", {
285
+ method: "POST",
286
+ body: JSON.stringify(body),
287
+ }, { actorPeerId });
288
+ if (!res.ok)
289
+ return [];
290
+ const items = res.result?.[source.bucket] || [];
291
+ return items.map((item) => ({ ...item, _sourceType: source.type }));
292
+ }
293
+ async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => { }) {
294
+ const results = await Promise.all(SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)));
295
+ const all = results.flat();
296
+ log("recall_search_summary", {
297
+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),
298
+ total: all.length,
299
+ });
300
+ return all;
301
+ }
302
+ async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
303
+ let content;
304
+ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {
305
+ content = (item.abstract || item.overview).trim();
306
+ }
307
+ else if (item.level === 2) {
308
+ try {
309
+ const res = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`, {}, { actorPeerId });
310
+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";
311
+ content = body || (item.abstract || item.overview || "").trim() || item.uri;
312
+ }
313
+ catch {
314
+ content = (item.abstract || item.overview || "").trim() || item.uri;
315
+ }
316
+ }
317
+ else {
318
+ content = (item.abstract || item.overview || "").trim() || item.uri;
319
+ }
320
+ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));
321
+ if (content.length > maxChars)
322
+ content = `${content.slice(0, maxChars)}...`;
323
+ return content;
324
+ }
325
+ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => { }) {
326
+ if (items.length === 0)
327
+ return null;
328
+ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
329
+ const lines = [
330
+ "<openviking-context>",
331
+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
332
+ ];
333
+ let contentCount = 0;
334
+ let hintCount = 0;
335
+ for (const item of items) {
336
+ const score = (clampScore(item.score) * 100).toFixed(0);
337
+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;
338
+ if (budgetRemaining > 0) {
339
+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);
340
+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;
341
+ const lineTokens = estimateTokens(contentLine);
342
+ if (lineTokens > budgetRemaining && contentCount > 0) {
343
+ lines.push(uriLine);
344
+ hintCount++;
345
+ }
346
+ else {
347
+ lines.push(contentLine);
348
+ budgetRemaining -= lineTokens;
349
+ contentCount++;
350
+ }
351
+ }
352
+ else {
353
+ lines.push(uriLine);
354
+ hintCount++;
355
+ }
356
+ }
357
+ lines.push("</openviking-context>");
358
+ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
359
+ log("recall_injection_built", {
360
+ contentItems: contentCount,
361
+ hintItems: hintCount,
362
+ budgetUsed,
363
+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
364
+ });
365
+ return lines.join("\n");
366
+ }
367
+ const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
368
+ function stateFile(name) {
369
+ const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
370
+ return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
371
+ }
372
+ async function readJsonFile(path) {
373
+ try {
374
+ return JSON.parse(await readFile(path, "utf8"));
375
+ }
376
+ catch {
377
+ return null;
378
+ }
379
+ }
380
+ async function writeJsonFile(path, value) {
381
+ try {
382
+ await mkdir(dirname(path), { recursive: true });
383
+ const tmp = `${path}.tmp`;
384
+ await writeFile(tmp, JSON.stringify(value));
385
+ await rename(tmp, path);
386
+ }
387
+ catch { /* best effort */ }
388
+ }
389
+ /**
390
+ * Hooks are one-shot processes, so "this server has no context face" has to be
391
+ * remembered on disk or every turn pays for a rejected request.
392
+ */
393
+ export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
394
+ const cached = await readJsonFile(path);
395
+ return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
396
+ }
397
+ export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
398
+ await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
399
+ }
400
+ /**
401
+ * A `peer_scope` the server rejects is remembered the same way, but unlike the
402
+ * context face this one is not a silent capability probe: dropping the field
403
+ * widens recall from the caller's own peer to the whole user root, so doctor
404
+ * reads this file back and warns.
405
+ */
406
+ export function peerScopeMemoPath() {
407
+ return stateFile("peer-scope.json");
408
+ }
409
+ export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
410
+ const cached = await readJsonFile(path);
411
+ if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now)
412
+ return null;
413
+ return cached;
414
+ }
415
+ export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
416
+ await writeJsonFile(path, {
417
+ legacyUntil: now + LEGACY_CACHE_TTL_MS,
418
+ scope: String(scope || ""),
419
+ status: Number(status) || 0,
420
+ at: now,
421
+ });
422
+ }
423
+ function looksLikeUnknownField(res) {
424
+ const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
425
+ return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
426
+ }
427
+ function wrapContext(body) {
428
+ return [
429
+ "<openviking-context>",
430
+ "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
431
+ body,
432
+ "</openviking-context>",
433
+ ].join("\n");
434
+ }
435
+ /**
436
+ * Server-assembled context: the context face when the deployment has it, else
437
+ * the deprecated /recall preset. Returns the injection block, "" when there was
438
+ * nothing relevant, or null when no server-side path was usable at all.
439
+ */
440
+ export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
441
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
442
+ const log = options.log || (() => { });
443
+ const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
444
+ if (block !== null)
445
+ return block;
446
+ return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
447
+ }
448
+ /**
449
+ * Raw server-assembled context, or null when the deployment has no context face.
450
+ * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
451
+ * (their own compression, their own envelope) use this instead of the block
452
+ * builders below.
453
+ */
454
+ export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
455
+ const actorPeerId = options.actorPeerId || "";
456
+ const log = options.log || (() => { });
457
+ if (await isContextFaceLegacy(options.legacyCachePath))
458
+ return null;
459
+ const body = buildContextSearchBody(cfg, options);
460
+ body.query = query;
461
+ const res = await fetchJSON("/api/v1/search/search", {
462
+ method: "POST",
463
+ body: JSON.stringify(body),
464
+ }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
465
+ if (!res.ok) {
466
+ const status = res.status || 0;
467
+ if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
468
+ await markContextFaceLegacy(options.legacyCachePath);
469
+ log("recall_context_face_unsupported", { status });
470
+ }
471
+ else {
472
+ log("recall_context_face_error", { status });
473
+ }
474
+ return null;
475
+ }
476
+ const result = res.result || {};
477
+ const stats = result.stats || {};
478
+ log("recall_context_assembled", {
479
+ entries: Array.isArray(result.entries) ? result.entries.length : 0,
480
+ usedTokens: stats.used_tokens || 0,
481
+ tiers: stats.tier_counts || {},
482
+ rewrite: stats.rewrite || "off",
483
+ });
484
+ return {
485
+ rendered: String(result.rendered || "").trim(),
486
+ entries: Array.isArray(result.entries) ? result.entries : [],
487
+ digest: String(result.digest || "").trim(),
488
+ stats,
489
+ };
490
+ }
491
+ /**
492
+ * Entry field compatibility: the context face returns `category`/`text`, while
493
+ * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
494
+ */
495
+ export function normalizeContextEntry(entry = {}) {
496
+ return {
497
+ uri: String(entry.uri || "").trim(),
498
+ category: String(entry.category || entry.type || "memory").trim() || "memory",
499
+ detail: String(entry.detail || entry.mode || "").trim(),
500
+ score: Number(entry.score) || 0,
501
+ text: String(entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "").trim(),
502
+ };
503
+ }
504
+ async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
505
+ const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
506
+ if (assembled === null)
507
+ return null;
508
+ const { rendered, entries } = assembled;
509
+ let digest = assembled.digest;
510
+ const mode = String(cfg.recallRewrite || "off").toLowerCase();
511
+ if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
512
+ log("recall_server_compression", { status: "empty" });
513
+ return "";
514
+ }
515
+ const wantsLocal = mode === "client" || (mode === "auto" && !digest);
516
+ if (wantsLocal && rendered && typeof options.runCompressor === "function") {
517
+ try {
518
+ const compression = await compressRecallContext({
519
+ query,
520
+ rendered,
521
+ entries,
522
+ cfg,
523
+ runCompressor: options.runCompressor,
524
+ cachePath: options.digestCachePath || stateFile("recall-digest.json"),
525
+ now: Date.now(),
526
+ });
527
+ log("recall_local_compression", { status: compression.status });
528
+ if (compression.status === "ok")
529
+ digest = compression.context;
530
+ if (compression.status === "empty")
531
+ return "";
532
+ }
533
+ catch (err) {
534
+ log("recall_local_compression_failed", { error: String(err?.message || err) });
535
+ }
536
+ }
537
+ const injected = digest || rendered;
538
+ if (!injected)
539
+ return "";
540
+ return wrapContext(injected);
541
+ }
542
+ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => { }) {
543
+ const body = buildRecallEndpointBody(cfg);
544
+ body.query = query;
545
+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });
546
+ if (!res.ok) {
547
+ log("recall_endpoint_fallback", { status: res.status || 0 });
548
+ return null;
549
+ }
550
+ const rendered = String(res.result?.rendered || "").trim();
551
+ if (!rendered)
552
+ return "";
553
+ return wrapContext(rendered);
554
+ }
555
+ export async function postRecall(fetchJSON, body, opts = {}) {
556
+ const actorPeerId = opts.actorPeerId || "";
557
+ const log = opts.log || (() => { });
558
+ const memoPath = opts.peerScopeMemoPath;
559
+ const request = { ...body };
560
+ // A remembered downgrade is still a downgrade: recall runs wider than the
561
+ // caller asked for, so the memo doubles as the doctor's evidence.
562
+ if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
563
+ delete request.peer_scope;
564
+ }
565
+ const res = await fetchJSON("/api/v1/search/recall", {
566
+ method: "POST",
567
+ body: JSON.stringify(request),
568
+ }, { actorPeerId });
569
+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {
570
+ return res;
571
+ }
572
+ // Only an unknown-field rejection means "this server predates peer_scope".
573
+ // Retrying every other 400/422 without it silently widens the search from
574
+ // the caller's own peer to the whole user root.
575
+ if (!looksLikeUnknownField(res)) {
576
+ log("recall_peer_scope_error", { status: res.status || 0 });
577
+ return res;
578
+ }
579
+ const downgraded = { ...request };
580
+ delete downgraded.peer_scope;
581
+ await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
582
+ log("recall_peer_scope_downgrade", { status: res.status || 0 });
583
+ return fetchJSON("/api/v1/search/recall", {
584
+ method: "POST",
585
+ body: JSON.stringify(downgraded),
586
+ }, { actorPeerId });
587
+ }
588
+ /**
589
+ * Recall, plus whatever is still filed under the peer this workspace used
590
+ * before the identity rule changed.
591
+ *
592
+ * Under the default `peer_scope: "all"` this costs nothing: the server's own
593
+ * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
594
+ * `"actor"` that sweep is off by definition, so the old peer is asked for
595
+ * separately — as itself, which is both cheaper and wider than a bare
596
+ * cross-peer read (that would need the user id, and reaches memories only).
597
+ */
598
+ export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
599
+ const primary = await recallForPeer(fetchJSON, cfg, query, options);
600
+ const legacyPeerId = String(options.legacyPeerId || "").trim();
601
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
602
+ if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId)
603
+ return primary;
604
+ const log = options.log || (() => { });
605
+ const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
606
+ if (!legacy)
607
+ return primary;
608
+ log("recall_legacy_peer_hit", { legacyPeerId });
609
+ return primary ? `${primary}\n${legacy}` : legacy;
610
+ }
611
+ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
612
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
613
+ const log = options.log || (() => { });
614
+ const trimmed = String(query || "").trim();
615
+ if (!trimmed)
616
+ return null;
617
+ // Assembly happens server-side when the deployment offers the context face;
618
+ // older servers fall through to /recall, then to raw find.
619
+ const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
620
+ ...options,
621
+ actorPeerId,
622
+ log,
623
+ });
624
+ if (serverBlock !== null)
625
+ return serverBlock || null;
626
+ const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
627
+ const perSourceLimit = Math.max(recallLimit * 2, 8);
628
+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
629
+ if (raw.length === 0)
630
+ return null;
631
+ const profile = buildQueryProfile(trimmed);
632
+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
633
+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);
634
+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));
635
+ const picked = dedupeItems(filtered).slice(0, recallLimit);
636
+ log("recall_picked", {
637
+ rawCount: raw.length,
638
+ filteredCount: filtered.length,
639
+ pickedCount: picked.length,
640
+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
641
+ });
642
+ if (picked.length === 0)
643
+ return null;
644
+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
645
+ }
@@ -26,6 +26,7 @@
26
26
  "adapters/",
27
27
  "registries/",
28
28
  "routing/",
29
+ "shared/",
29
30
  "plugin/",
30
31
  "services/",
31
32
  "commands/setup.ts",
@@ -144,9 +144,9 @@
144
144
  },
145
145
  "autoRecallTimeoutMs": {
146
146
  "label": "Auto-Recall Timeout (ms)",
147
- "placeholder": "5000",
147
+ "placeholder": "15000",
148
148
  "advanced": true,
149
- "help": "Outer time budget for the whole auto-recall flow, including search, ranking, and memory reads."
149
+ "help": "Outer time budget for the server-assembled context search, including session-aware query expansion."
150
150
  },
151
151
  "recallResources": {
152
152
  "label": "Recall Resources",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openviking/openclaw-plugin",
3
- "version": "2026.9.1",
3
+ "version": "2026.9.4",
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",
@@ -26,6 +26,7 @@
26
26
  "config/feature-gates.json",
27
27
  "registries/",
28
28
  "routing/",
29
+ "shared/",
29
30
  "plugin/",
30
31
  "services/",
31
32
  "!vitest.config.ts",