@openviking/opencode-plugin 0.2.4 → 2026.9.9

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,124 @@
1
+ // GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
2
+ /**
3
+ * Shared config shaping for the stdio MCP proxy entrypoints.
4
+ *
5
+ * Every harness loads its credentials differently, but the shape
6
+ * `createOpenVikingMcpProxy` consumes is identical everywhere, and so is the
7
+ * set of files whose changes must trigger a credential reload. Keeping that
8
+ * here stops each entrypoint from re-deriving `~` expansion, URL trimming,
9
+ * timeout clamping, and the watch list.
10
+ */
11
+
12
+ import { homedir } from "node:os";
13
+ import { join, resolve as resolvePath } from "node:path";
14
+
15
+ export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
16
+ const MIN_PROXY_TIMEOUT_MS = 1000;
17
+
18
+ export function trimSlash(value) {
19
+ return String(value || "").replace(/\/+$/, "");
20
+ }
21
+
22
+ /** Expand a leading `~` and resolve to an absolute path; "" stays "". */
23
+ export function normalizeConfigPath(value) {
24
+ const raw = String(value || "").trim();
25
+ if (!raw) return "";
26
+ if (raw === "~") return homedir();
27
+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
28
+ return resolvePath(raw);
29
+ }
30
+
31
+ /**
32
+ * The credential files every harness must watch: the two `OPENVIKING_*_FILE`
33
+ * overrides and the two default locations under `~/.openviking`.
34
+ */
35
+ export function defaultCredentialPaths(env = process.env) {
36
+ return [
37
+ normalizeConfigPath(env.OPENVIKING_CLI_CONFIG_FILE),
38
+ normalizeConfigPath(env.OPENVIKING_CONFIG_FILE),
39
+ join(homedir(), ".openviking", "ovcli.conf"),
40
+ join(homedir(), ".openviking", "ov.conf"),
41
+ ].filter(Boolean);
42
+ }
43
+
44
+ /**
45
+ * Resolve the actor peer header for a long-lived MCP proxy process.
46
+ *
47
+ * MCP servers may start in the plugin directory rather than the active
48
+ * workspace, so their process cwd is not a reliable peer identity — and unlike
49
+ * a hook, a long-lived proxy cannot re-derive one per turn. Broad recall
50
+ * intentionally spans the authenticated user's peer workspaces and therefore
51
+ * leaves the actor header unset. Actor-scoped recall needs an explicit peer so
52
+ * isolation never depends on the proxy's launch directory.
53
+ *
54
+ * A missing one degrades to broad recall with a warning rather than refusing to
55
+ * start: the proxy is what carries every memory tool, and taking those away
56
+ * because a scope preference cannot be honoured costs the user far more than
57
+ * the wider search does. Only the harness whose parent process injects the peer
58
+ * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
59
+ */
60
+ export function resolveMcpActorPeerId({
61
+ peerId = "",
62
+ recallPeerScope = "all",
63
+ onWarn = null,
64
+ } = {}) {
65
+ if (recallPeerScope !== "actor") return "";
66
+
67
+ const explicitPeerId = String(peerId || "").trim();
68
+ if (explicitPeerId) return explicitPeerId;
69
+
70
+ const message = "OpenViking MCP: actor-scoped recall needs an explicit peer id, which an MCP proxy cannot "
71
+ + "derive from its launch directory. Falling back to broad recall across every peer under this user. "
72
+ + "Set actor_peer_id in ovcli.conf, or OPENVIKING_PEER_ID in the MCP server environment, to scope it.";
73
+ if (typeof onWarn === "function") onWarn(message);
74
+ else process.stderr.write(`${message}\n`);
75
+ return "";
76
+ }
77
+
78
+ function uniq(values) {
79
+ return [...new Set(values.filter(Boolean))];
80
+ }
81
+
82
+ /**
83
+ * Shape a harness's loaded config into the object `createOpenVikingMcpProxy`
84
+ * expects.
85
+ *
86
+ * `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
87
+ * user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
88
+ * harness's own extra files; the shared defaults are appended and the result
89
+ * deduplicated.
90
+ */
91
+ export function buildMcpProxyConfig({
92
+ baseUrl = "",
93
+ mcpUrl = "",
94
+ apiKey = "",
95
+ account = "",
96
+ user = "",
97
+ peerId = "",
98
+ userAgent = "",
99
+ timeoutMs,
100
+ debug = false,
101
+ debugLogPath = "",
102
+ credentialSource = "auto",
103
+ credentialPath = "",
104
+ watchedPaths = [],
105
+ env = process.env,
106
+ } = {}) {
107
+ return {
108
+ mcpUrl: mcpUrl || `${trimSlash(baseUrl)}/mcp`,
109
+ apiKey: apiKey || "",
110
+ account: account || "",
111
+ user: user || "",
112
+ peerId: peerId || "",
113
+ userAgent: userAgent || "",
114
+ timeoutMs: Math.max(
115
+ MIN_PROXY_TIMEOUT_MS,
116
+ Number(timeoutMs) || DEFAULT_PROXY_TIMEOUT_MS,
117
+ ),
118
+ debug: debug === true,
119
+ debugLogPath,
120
+ credentialSource: credentialSource || "auto",
121
+ credentialPath: credentialPath || "",
122
+ watchedPaths: uniq([...watchedPaths, ...defaultCredentialPaths(env)]),
123
+ };
124
+ }
@@ -292,10 +292,22 @@ export function createOpenVikingMcpProxy({
292
292
  );
293
293
  }
294
294
  const msg = err instanceof Error ? err.message : String(err);
295
+ if (err && err.name === "AbortError") {
296
+ // Client-side timeout, not an outage: the server may be healthy and
297
+ // still computing (rerank-inclusive find/search can legitimately take
298
+ // longer than the default budget). Keep -32001 for genuine
299
+ // connection failures so the two are not misdiagnosed as each other.
300
+ return errorResponse(
301
+ id,
302
+ -32004,
303
+ `OpenViking MCP request timed out after ${proxyConfig.timeoutMs}ms (${proxyConfig.mcpUrl}). The server may still be processing (rerank can be slow) — check /health or raise OPENVIKING_TIMEOUT_MS.`,
304
+ { timeoutMs: proxyConfig.timeoutMs, mcpUrl: proxyConfig.mcpUrl, cause: msg },
305
+ );
306
+ }
295
307
  return errorResponse(
296
308
  id,
297
309
  -32001,
298
- `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that 'ov serve' is running.`,
310
+ `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that the OpenViking server (\`openviking-server\`) is reachable.`,
299
311
  { cause: msg },
300
312
  );
301
313
  }
@@ -409,6 +409,17 @@ export async function replayPending(fetchJSON, log) {
409
409
  res = { ok: false };
410
410
  }
411
411
 
412
+ if (entry.type === "commitSession") {
413
+ log("pending-queue", {
414
+ action: "commit-replay",
415
+ sessionId: entry.sessionId,
416
+ ok: Boolean(res?.ok),
417
+ status: res?.result?.status || res?.status,
418
+ trace_id: res?.traceId || res?.result?.trace_id,
419
+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
420
+ });
421
+ }
422
+
412
423
  if (res?.ok) {
413
424
  await dequeue(claimedFilename);
414
425
  replayed++;
@@ -86,10 +86,16 @@ export function repairDigestUris(digest, validUris = []) {
86
86
  lines.push(line);
87
87
  continue;
88
88
  }
89
+ let tokenized = line;
90
+ for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
91
+ if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
92
+ }
89
93
  let dropped = false;
90
- const repaired = line.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
91
- if (validSet.has(uri)) return uri;
92
- const nearest = nearestUri(uri, valid);
94
+ const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
95
+ let decoded = uri;
96
+ try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
97
+ if (validSet.has(decoded)) return decoded;
98
+ const nearest = nearestUri(decoded, valid);
93
99
  if (nearest) return nearest;
94
100
  dropped = true;
95
101
  return uri;
@@ -149,6 +155,7 @@ async function writeCache(path, value) {
149
155
  export async function compressRecallContext({
150
156
  query,
151
157
  rendered,
158
+ shortContext = rendered,
152
159
  entries = [],
153
160
  cfg = {},
154
161
  runCompressor,
@@ -158,7 +165,9 @@ export async function compressRecallContext({
158
165
  const input = String(rendered || "").trim();
159
166
  if (!input) return { status: COMPRESS_EMPTY, context: "" };
160
167
  const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
161
- if (input.length < minChars) return { status: COMPRESS_OK, context: input };
168
+ if (input.length < minChars) {
169
+ return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
170
+ }
162
171
 
163
172
  const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
164
173
  const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
@@ -171,7 +180,8 @@ export async function compressRecallContext({
171
180
  });
172
181
  const cached = await readCache(cachePath);
173
182
  if (cached?.key === key && typeof cached.digest === "string") {
174
- return { status: COMPRESS_OK, context: cached.digest };
183
+ const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
184
+ if (digest) return { status: COMPRESS_OK, context: digest };
175
185
  }
176
186
 
177
187
  const prompt = buildRecallCompressionPrompt({
@@ -185,9 +195,10 @@ export async function compressRecallContext({
185
195
  if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
186
196
 
187
197
  const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
188
- const digest = repairDigestUris(normalized, validUris.length
198
+ const repaired = repairDigestUris(normalized, validUris.length
189
199
  ? validUris
190
200
  : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
201
+ const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
191
202
  if (!digest) return { status: COMPRESS_FAILED, context: "" };
192
203
 
193
204
  await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
14
14
  ]);
15
15
  const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
16
16
  const SOURCES = [
17
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
18
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
17
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
18
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
19
19
  ];
20
20
  const DEFAULT_CONTEXT_LIMIT = 10;
21
21
  const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -164,10 +164,9 @@ export function contextRequestTimeoutMs(cfg = {}, body = {}) {
164
164
  // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
165
165
  // takes the expansion fuse back out of the budget.
166
166
  const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
167
- if (!wantsRewrite && !wantsExpansion) return undefined;
168
-
169
167
  const configured = Number(cfg.recallContextTimeoutMs);
170
168
  if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
169
+ if (!wantsRewrite && !wantsExpansion) return undefined;
171
170
  const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
172
171
  return Math.max(Number(cfg.timeoutMs) || 0, floor);
173
172
  }
@@ -272,6 +271,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
272
271
 
273
272
  async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
274
273
  const trimmed = targetUri.trim().replace(/\/+$/, "");
274
+ // viking://~ is the home alias: the server expands it to the caller's own user
275
+ // space, so it needs no client-side rewrite.
276
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
277
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
278
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
275
279
  const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
276
280
  if (!m) return trimmed;
277
281
  const rawRest = (m[1] ?? "").trim();
@@ -413,6 +417,31 @@ export async function markContextFaceLegacy(path = stateFile("context-face.json"
413
417
  await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
414
418
  }
415
419
 
420
+ /**
421
+ * A `peer_scope` the server rejects is remembered the same way, but unlike the
422
+ * context face this one is not a silent capability probe: dropping the field
423
+ * widens recall from the caller's own peer to the whole user root, so doctor
424
+ * reads this file back and warns.
425
+ */
426
+ export function peerScopeMemoPath() {
427
+ return stateFile("peer-scope.json");
428
+ }
429
+
430
+ export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
431
+ const cached = await readJsonFile(path);
432
+ if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
433
+ return cached;
434
+ }
435
+
436
+ export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
437
+ await writeJsonFile(path, {
438
+ legacyUntil: now + LEGACY_CACHE_TTL_MS,
439
+ scope: String(scope || ""),
440
+ status: Number(status) || 0,
441
+ at: now,
442
+ });
443
+ }
444
+
416
445
  function looksLikeUnknownField(res) {
417
446
  const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
418
447
  return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
@@ -421,7 +450,7 @@ function looksLikeUnknownField(res) {
421
450
  function wrapContext(body) {
422
451
  return [
423
452
  "<openviking-context>",
424
- "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",
453
+ "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
425
454
  body,
426
455
  "</openviking-context>",
427
456
  ].join("\n");
@@ -554,7 +583,15 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =
554
583
  export async function postRecall(fetchJSON, body, opts = {}) {
555
584
  const actorPeerId = opts.actorPeerId || "";
556
585
  const log = opts.log || (() => {});
586
+ const memoPath = opts.peerScopeMemoPath;
557
587
  const request = { ...body };
588
+
589
+ // A remembered downgrade is still a downgrade: recall runs wider than the
590
+ // caller asked for, so the memo doubles as the doctor's evidence.
591
+ if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
592
+ delete request.peer_scope;
593
+ }
594
+
558
595
  const res = await fetchJSON("/api/v1/search/recall", {
559
596
  method: "POST",
560
597
  body: JSON.stringify(request),
@@ -562,9 +599,17 @@ export async function postRecall(fetchJSON, body, opts = {}) {
562
599
  if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {
563
600
  return res;
564
601
  }
602
+ // Only an unknown-field rejection means "this server predates peer_scope".
603
+ // Retrying every other 400/422 without it silently widens the search from
604
+ // the caller's own peer to the whole user root.
605
+ if (!looksLikeUnknownField(res)) {
606
+ log("recall_peer_scope_error", { status: res.status || 0 });
607
+ return res;
608
+ }
565
609
 
566
610
  const downgraded = { ...request };
567
611
  delete downgraded.peer_scope;
612
+ await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
568
613
  log("recall_peer_scope_downgrade", { status: res.status || 0 });
569
614
  return fetchJSON("/api/v1/search/recall", {
570
615
  method: "POST",
@@ -572,7 +617,31 @@ export async function postRecall(fetchJSON, body, opts = {}) {
572
617
  }, { actorPeerId });
573
618
  }
574
619
 
620
+ /**
621
+ * Recall, plus whatever is still filed under the peer this workspace used
622
+ * before the identity rule changed.
623
+ *
624
+ * Under the default `peer_scope: "all"` this costs nothing: the server's own
625
+ * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
626
+ * `"actor"` that sweep is off by definition, so the old peer is asked for
627
+ * separately — as itself, which is both cheaper and wider than a bare
628
+ * cross-peer read (that would need the user id, and reaches memories only).
629
+ */
575
630
  export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
631
+ const primary = await recallForPeer(fetchJSON, cfg, query, options);
632
+
633
+ const legacyPeerId = String(options.legacyPeerId || "").trim();
634
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
635
+ if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
636
+
637
+ const log = options.log || (() => {});
638
+ const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
639
+ if (!legacy) return primary;
640
+ log("recall_legacy_peer_hit", { legacyPeerId });
641
+ return primary ? `${primary}\n${legacy}` : legacy;
642
+ }
643
+
644
+ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
576
645
  const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
577
646
  const log = options.log || (() => {});
578
647
  const trimmed = String(query || "").trim();
@@ -39,14 +39,17 @@ export async function runSetupWizard({
39
39
  output = process.stdout,
40
40
  env = process.env,
41
41
  } = {}) {
42
- const { cliPath } = loadCredentialFiles(env);
43
- const current = readJsonSafe(cliPath);
42
+ // cliPath is empty until the file exists; first-run writes go to the candidate
43
+ // path (OPENVIKING_CLI_CONFIG_FILE, else ~/.openviking/ovcli.conf).
44
+ const { cliPath, cliPathCandidate } = loadCredentialFiles(env);
45
+ const targetPath = cliPath || cliPathCandidate;
46
+ const current = readJsonSafe(targetPath);
44
47
  const rl = createInterface({ input, output });
45
48
  const say = (line = "") => output.write(`${line}\n`);
46
49
 
47
50
  try {
48
51
  say("OpenViking memory plugin setup");
49
- say(`Config file: ${cliPath}`);
52
+ say(`Config file: ${targetPath}`);
50
53
  say("");
51
54
  say("Current values:");
52
55
  say(` url: ${current.url || "(not set)"}`);
@@ -89,22 +92,22 @@ export async function runSetupWizard({
89
92
  const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();
90
93
  if (confirm === "n" || confirm === "no") {
91
94
  say("Aborted; nothing written.");
92
- return { written: false, path: cliPath };
95
+ return { written: false, path: targetPath };
93
96
  }
94
97
 
95
- mkdirSync(dirname(cliPath), { recursive: true });
96
- if (existsSync(cliPath)) {
97
- copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);
98
+ mkdirSync(dirname(targetPath), { recursive: true });
99
+ if (existsSync(targetPath)) {
100
+ copyFileSync(targetPath, `${targetPath}.bak.${Date.now()}`);
98
101
  }
99
- writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
102
+ writeFileSync(targetPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
100
103
  try {
101
- chmodSync(cliPath, 0o600);
104
+ chmodSync(targetPath, 0o600);
102
105
  } catch {
103
106
  /* best effort on platforms without chmod semantics */
104
107
  }
105
- say(`Written: ${cliPath}`);
108
+ say(`Written: ${targetPath}`);
106
109
  say("The stdio MCP proxy and hooks pick this up on the next harness start.");
107
- return { written: true, path: cliPath };
110
+ return { written: true, path: targetPath };
108
111
  } finally {
109
112
  rl.close();
110
113
  }
@@ -14,30 +14,52 @@ export function normalizeToolName(value) {
14
14
  return String(value || "").trim().toLowerCase();
15
15
  }
16
16
 
17
- export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {
17
+ // Arguments that carry file CONTENT rather than a location. The sweep below
18
+ // looks past the known path keys so an unusual one (`paths`, a nested target)
19
+ // is still caught, but text a tool is asked to WRITE is not a path: a local
20
+ // `write` whose body merely mentions viking://user/default/ was denied, and no
21
+ // file was created. Skipped by name at any depth.
22
+ const DEFAULT_CONTENT_KEYS = [
23
+ "content",
24
+ "contents",
25
+ "text",
26
+ "body",
27
+ "old_string",
28
+ "oldString",
29
+ "new_string",
30
+ "newString",
31
+ "old_str",
32
+ "new_str",
33
+ "file_text",
34
+ "insert_line",
35
+ "replacement",
36
+ ];
37
+
38
+ export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_KEYS) {
18
39
  if (!args || typeof args !== "object") return null;
19
40
  for (const key of keys) {
20
41
  const uri = findVikingUriInValue(args[key]);
21
42
  if (uri) return uri;
22
43
  }
23
- return findVikingUriInValue(args);
44
+ return findVikingUriInValue(args, new Set(contentKeys));
24
45
  }
25
46
 
26
- export function findVikingUriInValue(value) {
47
+ export function findVikingUriInValue(value, skipKeys) {
27
48
  if (typeof value === "string") {
28
49
  const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);
29
50
  return match?.[0] || null;
30
51
  }
31
52
  if (Array.isArray(value)) {
32
53
  for (const item of value) {
33
- const uri = findVikingUriInValue(item);
54
+ const uri = findVikingUriInValue(item, skipKeys);
34
55
  if (uri) return uri;
35
56
  }
36
57
  return null;
37
58
  }
38
59
  if (value && typeof value === "object") {
39
- for (const item of Object.values(value)) {
40
- const uri = findVikingUriInValue(item);
60
+ for (const [key, item] of Object.entries(value)) {
61
+ if (skipKeys?.has(key)) continue;
62
+ const uri = findVikingUriInValue(item, skipKeys);
41
63
  if (uri) return uri;
42
64
  }
43
65
  }