Skip to content

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

feat(plugins): add OpenViking memory for DSH (#3993)

t0sakid7ab37c76e22
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 8e6949d73..e31b244c7 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -28,6 +28,8 @@ jobs:
# 24+: the pi extension tests import .ts glue directly via native type stripping.
node-version: '24'
+ - run: npm ci --prefix examples/dsh-memory-plugin
+
- name: Run memory plugin tests
run: |
node --test \
@@ -61,6 +63,7 @@ jobs:
examples/memory-plugin-shared/recall-core.test.mjs \
examples/memory-plugin-shared/workspace-peer.test.mjs \
examples/memory-plugin-shared/uri-guard.test.mjs \
+ examples/dsh-memory-plugin/*.test.mjs \
examples/opencode-plugin/tests/*.test.mjs \
examples/opencode-plugin/servers/mcp-proxy.test.mjs \
examples/pi-coding-agent-extension/tests/*.test.mjs \
diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.md
new file mode 100644
index 000000000..d9f00d692
--- /dev/null
+++ b/examples/dsh-memory-plugin/README.md
@@ -0,0 +1,129 @@
+# OpenViking Memory for DeepSeek Harness
+
+An installable DeepSeek Harness bundle that adds OpenViking auto-recall, session capture, `viking://` URI protection, and model-invocable memory tools.
+
+## Requirements
+
+- `@deepseek-ai/dsh` `0.1.0-rc.6`
+- Node.js `^22.19.0` or `>=24`
+- A reachable OpenViking server
+
+The bundle has no runtime npm dependencies. Its tool and message structures
+come from the DSH constructors (`defineTool` from `@deepseek-ai/dsh-tools`,
+`createUserMessage` from `@deepseek-ai/dsh-llm`) behind exact-pinned
+peerDependencies that DSH exposes through its profile fallback at boot time, so
+the definitions track DSH's contracts instead of hand-built object shapes.
+It is tested against `0.1.0-rc.6`; install that exact DSH release because
+prerelease package dist-tags are not synchronized across the package family.
+
+## Why injection uses pre-step user messages, not the system prompt
+
+Recall and profile context enter through the `agent/pre-step` waterfall as
+durable, source-attributed user messages (`source: { kind: 'plugin', … }`).
+They are deliberately **not** added to the system prompt: a DSH preset whose
+persona declares `complete: true` (the stock `minimal` preset does) restores
+that persona as the sole prompt section after assembly, silently discarding
+every other contribution — a system-prompt-based memory plugin loses its
+context under such presets with no error. Pre-step injection also makes each
+injection a session event that replays, is visible to compaction, and never
+reaches `request/header`.
+
+## Install
+
+From the OpenViking repository:
+
+```bash
+dsh plugin --profile default add ./examples/dsh-memory-plugin
+```
+
+Or install the published package:
+
+```bash
+dsh plugin --profile default add @openviking/dsh-memory-plugin
+```
+
+Confirm that the profile includes the bundle:
+
+```bash
+dsh --profile default --dump-config
+```
+
+The package patch mounts the runtime inside a Cordis group with an isolated `openvikingMemory` service.
+
+## Configuration
+
+OpenViking credentials use the same resolution order as the other memory plugins:
+
+1. `OPENVIKING_*` environment variables
+2. `~/.openviking/ovcli.conf`
+3. `~/.openviking/ov.conf`
+
+Common environment variables:
+
+| Variable | Purpose |
+| --- | --- |
+| `OPENVIKING_URL` / `OPENVIKING_BASE_URL` | OpenViking server endpoint |
+| `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN` | Bearer credential |
+| `OPENVIKING_ACCOUNT` | Trusted-mode account |
+| `OPENVIKING_USER` | Trusted-mode user |
+| `OPENVIKING_PEER_ID` | Explicit actor peer |
+| `OPENVIKING_WORKSPACE_PEER` | Derive a peer from each DSH session workspace by default |
+| `OPENVIKING_RECALL_PEER_SCOPE` | `all` for cross-workspace recall or `actor` for isolation |
+
+The patch can also carry plugin config:
+
+```yaml
+- insert:
+ - id: openviking-memory
+ name: '@deepseek-ai/cordis-plugin-group'
+ group: true
+ isolate:
+ openvikingMemory: true
+ config:
+ - id: openviking-memory-runtime
+ name: '@openviking/dsh-memory-plugin'
+ config:
+ endpoint: http://127.0.0.1:1933
+ recallTokenBudget: 2000
+ scoreThreshold: 0.35
+ captureToolResults: false
+ commitTokenThreshold: 20000
+```
+
+## Behavior
+
+- `agent/session-start` injects the OpenViking profile and available-memory index through `agent.inject()`.
+- `agent/pre-step` retrieves with the current step input and appends a durable plugin message to that same step.
+- `session/event` captures user, assistant, and optionally tool-result messages without scraping a transcript.
+- `turn/end` checks the OpenViking pending-token threshold and commits when required.
+- Failed writes enter the shared OpenViking pending queue for replay at the next session start.
+- `tools/pre-execute` blocks DSH filesystem and shell tools from treating `viking://` URIs as local paths.
+
+Each DSH session maps to `dsh-<session-id>` in OpenViking. Workspace-derived actor peers are resolved per session and sent on every session-specific request.
+
+## Tools
+
+The bundle registers:
+
+- `viking_search`
+- `viking_read`
+- `viking_browse`
+- `viking_remember`
+- `viking_forget`
+- `viking_add_resource`
+- `viking_archive_expand`
+
+`viking_forget` performs permanent deletion. The calling model should use it only when the user explicitly requests deletion.
+
+## Testing
+
+```bash
+npm ci # installs the exact-pinned dsh devDependencies the tests exercise
+npm test # node --test *.test.mjs — runs in the repo's PR workflow
+```
+
+`live-recall.test.mjs` is an opt-in end-to-end gate against a real OpenViking
+server: it stores a sentinel memory through a session commit, waits for
+extraction, and asserts recall returns that sentinel — the property no stub
+can certify. Enable it with `OPENVIKING_E2E=1` plus the normal credential
+chain; it skips otherwise (including in CI until a server secret exists).
diff --git a/examples/dsh-memory-plugin/bundle.test.mjs b/examples/dsh-memory-plugin/bundle.test.mjs
new file mode 100644
index 000000000..c234501f2
--- /dev/null
+++ b/examples/dsh-memory-plugin/bundle.test.mjs
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { readFile, readdir } from "node:fs/promises";
+import { dirname, join, relative } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url));
+const FORBIDDEN_IDENTIFIER = ["tra", "ex"].join("");
+const FORBIDDEN_PATTERN = new RegExp(FORBIDDEN_IDENTIFIER, "i");
+
+test("bundle uses neutral DSH naming, exact-pinned peers, and an isolated service", async () => {
+ const manifest = JSON.parse(await readFile(
+ new URL("./package.json", import.meta.url),
+ "utf8",
+ ));
+ const patch = await readFile(new URL("./cordis.patch.yml", import.meta.url), "utf8");
+
+ assert.equal(manifest.name, "@openviking/dsh-memory-plugin");
+ assert.equal(manifest.dependencies, undefined);
+ // dsh constructors (defineTool / createUserMessage) come from peers the
+ // installation heals at runtime; exact pins because dsh rc subpackages
+ // have stale `latest` dist-tags. devDependencies mirror the pins so CI
+ // tests exercise the same dsh surface a pin bump would ship.
+ for (const [name, version] of Object.entries(manifest.peerDependencies)) {
+ assert.match(version, /^\d+\.\d+\.\d+(-rc\.\d+)?$/, `${name} must be exact-pinned`);
+ assert.equal(manifest.devDependencies[name], version, `${name} devDependency must mirror the peer pin`);
+ }
+ assert.ok(manifest.peerDependencies["@deepseek-ai/dsh-tools"]);
+ assert.ok(manifest.peerDependencies["@deepseek-ai/dsh-llm"]);
+ assert.equal(manifest.dsh.bundle.patch, "./cordis.patch.yml");
+ assert.match(patch, /name: '@deepseek-ai\/cordis-plugin-group'/);
+ assert.match(patch, /openvikingMemory: true/);
+ assert.match(patch, /name: '@openviking\/dsh-memory-plugin'/);
+ assert.doesNotMatch(JSON.stringify(manifest), FORBIDDEN_PATTERN);
+ assert.doesNotMatch(patch, FORBIDDEN_PATTERN);
+});
+
+test("plugin source tree contains no product-specific identifier", async () => {
+ for (const file of await sourceFiles(PLUGIN_DIR)) {
+ const path = relative(PLUGIN_DIR, file);
+ assert.doesNotMatch(path, FORBIDDEN_PATTERN);
+ assert.doesNotMatch(await readFile(file, "utf8"), FORBIDDEN_PATTERN, path);
+ }
+});
+
+async function sourceFiles(dir) {
+ const files = [];
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ if (entry.name === "node_modules") continue;
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) files.push(...await sourceFiles(path));
+ else files.push(path);
+ }
+ return files;
+}
diff --git a/examples/dsh-memory-plugin/capture.mjs b/examples/dsh-memory-plugin/capture.mjs
new file mode 100644
index 000000000..abe0e90d1
--- /dev/null
+++ b/examples/dsh-memory-plugin/capture.mjs
@@ -0,0 +1,104 @@
+import {
+ extractPartsFromPayload,
+ extractTextFromPayload,
+ shouldCaptureText,
+} from "./shared/capture-utils.mjs";
+
+export const OPENVIKING_PLUGIN_SOURCE = "openviking-memory";
+
+export function captureEvent(event, config, toolNames = new Map()) {
+ if (!event || typeof event !== "object") return null;
+ if (event.type === "tool/call") {
+ if (config.captureToolResults === true) {
+ toolNames.set(String(event.data.callId), event.data.name);
+ }
+ return null;
+ }
+
+ const message = eventMessage(event);
+ if (!message) return null;
+ const toolCallId = event.type === "tool/result"
+ ? String(message.source?.callId || message.content?.[0]?.toolCallId || "")
+ : "";
+ try {
+ return captureMessage(event, message, config, toolNames);
+ } finally {
+ if (toolCallId) toolNames.delete(toolCallId);
+ }
+}
+
+function captureMessage(event, message, config, toolNames) {
+ // Whitelist by source: plugin-injected user messages (this plugin's recall
+ // blocks, time-context snapshots, any other plugin's context) are model
+ // input, not human input — mirroring them would launder synthetic text
+ // into memory as if a person said it.
+ if (message.source?.kind === "plugin") return null;
+ if (message.role === "assistant" && config.captureAssistantTurns === false) {
+ return null;
+ }
+ if (message.source?.kind === "tool" && config.captureToolResults !== true) {
+ return null;
+ }
+
+ const role = message.role === "assistant" ? "assistant" : "user";
+ const toolNameById = Object.fromEntries(toolNames);
+ const rawText = extractTextFromPayload(message, {
+ toolMaxChars: config.captureToolMaxChars,
+ });
+ const parts = extractPartsFromPayload(message, {
+ toolMaxChars: config.captureToolMaxChars,
+ toolNameById,
+ });
+ const decision = shouldCaptureText(rawText, role, config);
+ const structuredParts = parts.filter(part => part?.type !== "text");
+ if (!decision.shouldCapture && structuredParts.length === 0) return null;
+
+ const hasTextPart = parts.some(part => part?.type === "text");
+ const bodyParts = [
+ ...(hasTextPart && decision.shouldCapture && decision.text
+ ? [{ type: "text", text: decision.text }]
+ : []),
+ ...structuredParts,
+ ];
+ const payload = bodyParts.length > 0
+ ? { role, parts: bodyParts }
+ : { role, content: decision.text };
+ const createdAt = eventCreatedAt(event);
+ if (createdAt) payload.created_at = createdAt;
+ if (config.peerId) payload.peer_id = config.peerId;
+ return payload;
+}
+
+export function promptText(messages) {
+ return (messages || [])
+ .filter(message => !(
+ message?.source?.kind === "plugin"
+ && message.source.plugin === OPENVIKING_PLUGIN_SOURCE
+ ))
+ .map(message => extractTextFromPayload(message))
+ .filter(Boolean)
+ .join("\n\n")
+ .trim();
+}
+
+function eventMessage(event) {
+ switch (event.type) {
+ case "user/message":
+ return event.data;
+ case "assistant/message":
+ case "tool/result":
+ return event.data?.message;
+ default:
+ return null;
+ }
+}
+
+function eventCreatedAt(event) {
+ const time = Number(event?.time);
+ if (!Number.isFinite(time) || time < 0) return "";
+ try {
+ return new Date(time).toISOString();
+ } catch {
+ return "";
+ }
+}
diff --git a/examples/dsh-memory-plugin/capture.test.mjs b/examples/dsh-memory-plugin/capture.test.mjs
new file mode 100644
index 000000000..44d43579e
--- /dev/null
+++ b/examples/dsh-memory-plugin/capture.test.mjs
@@ -0,0 +1,141 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { captureEvent, promptText } from "./capture.mjs";
+
+const CONFIG = {
+ captureAssistantTurns: true,
+ captureToolResults: true,
+ captureToolMaxChars: 1000000,
+ captureMaxLength: 24000,
+ captureMode: "semantic",
+ peerId: "workspace-a",
+};
+
+test("captures DSH message events without recapturing injected context", () => {
+ const user = captureEvent({
+ type: "user/message",
+ data: {
+ role: "user",
+ content: [{ type: "text", text: "Remember that deployment uses blue." }],
+ source: { kind: "user" },
+ },
+ }, CONFIG);
+ assert.deepEqual(user, {
+ role: "user",
+ parts: [{ type: "text", text: "Remember that deployment uses blue." }],
+ peer_id: "workspace-a",
+ });
+
+ const injected = captureEvent({
+ type: "user/message",
+ data: {
+ role: "user",
+ content: [{ type: "text", text: "<openviking-context>blue</openviking-context>" }],
+ source: { kind: "plugin", plugin: "openviking-memory", form: "recall" },
+ },
+ }, CONFIG);
+ assert.equal(injected, null);
+
+ // Every plugin's injections stay out of memory, not just this plugin's:
+ // synthetic context mirrored as human input would poison extraction.
+ const otherPlugin = captureEvent({
+ type: "user/message",
+ data: {
+ role: "user",
+ content: [{ type: "text", text: "Time sampled while preparing turn 3" }],
+ source: { kind: "plugin", plugin: "time-context", form: "snapshot" },
+ },
+ }, CONFIG);
+ assert.equal(otherPlugin, null);
+});
+
+test("preserves DSH tool call identity in captured tool results", () => {
+ const names = new Map();
+ assert.equal(captureEvent({
+ type: "tool/call",
+ data: { callId: "call-1", name: "bash", arguments: "{\"command\":\"pwd\"}" },
+ }, CONFIG, names), null);
+
+ const captured = captureEvent({
+ type: "tool/result",
+ data: {
+ message: {
+ role: "user",
+ content: [{
+ type: "tool-result",
+ toolCallId: "call-1",
+ content: [{ type: "text", text: "/workspace" }],
+ }],
+ source: { kind: "tool", callId: "call-1" },
+ },
+ },
+ }, CONFIG, names);
+
+ assert.equal(captured.role, "user");
+ assert.equal(captured.parts[0].type, "tool");
+ assert.equal(captured.parts[0].tool_id, "call-1");
+ assert.equal(captured.parts[0].tool_name, "bash");
+ assert.match(captured.parts[0].tool_output, /workspace/);
+ assert.equal(names.size, 0);
+});
+
+test("does not retain tool call names when tool-result capture is disabled", () => {
+ const names = new Map();
+ const config = { ...CONFIG, captureToolResults: false };
+ captureEvent({
+ type: "tool/call",
+ data: { callId: "call-disabled", name: "bash" },
+ }, config, names);
+ assert.equal(names.size, 0);
+});
+
+test("releases tool call names even when a tool result has no capturable content", () => {
+ const names = new Map([["call-empty", "bash"]]);
+ const captured = captureEvent({
+ type: "tool/result",
+ data: {
+ message: {
+ role: "user",
+ content: [],
+ source: { kind: "tool", callId: "call-empty" },
+ },
+ },
+ }, CONFIG, names);
+
+ assert.equal(captured, null);
+ assert.equal(names.size, 0);
+});
+
+test("preserves DSH event time so identical offline messages do not deduplicate", () => {
+ const captured = captureEvent({
+ type: "user/message",
+ time: 1_786_681_234_567,
+ data: {
+ role: "user",
+ content: [{ type: "text", text: "Repeat this exact fact." }],
+ source: { kind: "user" },
+ },
+ }, CONFIG);
+
+ assert.equal(captured.created_at, "2026-08-14T04:20:34.567Z");
+});
+
+test("builds recall queries from current input while excluding its own context", () => {
+ assert.equal(promptText([
+ {
+ role: "user",
+ content: [{ type: "text", text: "Current question" }],
+ source: { kind: "user" },
+ },
+ {
+ role: "user",
+ content: [{ type: "text", text: "old recall" }],
+ source: { kind: "plugin", plugin: "openviking-memory" },
+ },
+ {
+ role: "user",
+ content: [{ type: "text", text: "background job completed" }],
+ source: { kind: "plugin", plugin: "job-controller", form: "notice", summary: "done" },
+ },
+ ]), "Current question\n\nbackground job completed");
+});
diff --git a/examples/dsh-memory-plugin/client.mjs b/examples/dsh-memory-plugin/client.mjs
new file mode 100644
index 000000000..78b5dc3c7
--- /dev/null
+++ b/examples/dsh-memory-plugin/client.mjs
@@ -0,0 +1,206 @@
+export class OpenVikingClient {
+ constructor(config) {
+ this.config = config;
+ this.connected = false;
+ }
+
+ headers(options = {}) {
+ const headers = { "Content-Type": "application/json" };
+ if (this.config.apiKey) headers.Authorization = `Bearer ${this.config.apiKey}`;
+ if (this.config.account) headers["X-OpenViking-Account"] = this.config.account;
+ if (this.config.user) headers["X-OpenViking-User"] = this.config.user;
+ const actorPeerId = options.actorPeerId ?? this.config.peerId;
+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
+ if (this.config.userAgent) headers["User-Agent"] = this.config.userAgent;
+ return headers;
+ }
+
+ async fetchJSON(path, init = {}, options = {}) {
+ const timeoutMs = options.timeoutMs ?? this.config.requestTimeoutMs;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await fetch(`${this.config.endpoint}${path}`, {
+ ...init,
+ headers: {
+ ...this.headers(options),
+ ...(init.headers || {}),
+ },
+ signal: controller.signal,
+ });
+ const body = await response.json().catch(() => ({}));
+ const traceId = body?.result?.trace_id
+ || body?.error?.trace_id
+ || body?.trace_id
+ || undefined;
+ if (!response.ok || body?.status === "error") {
+ return {
+ ok: false,
+ result: null,
+ status: response.status,
+ error: body?.error || { message: `HTTP ${response.status}` },
+ traceId,
+ };
+ }
+ return {
+ ok: true,
+ result: body?.result ?? body,
+ status: response.status,
+ traceId,
+ };
+ } catch (error) {
+ return {
+ ok: false,
+ result: null,
+ status: 0,
+ error: { message: error instanceof Error ? error.message : String(error) },
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ async health() {
+ return (await this.healthResult()).ok;
+ }
+
+ async healthResult() {
+ const response = await this.fetchJSON("/health", {}, { timeoutMs: 5000 });
+ this.connected = response.ok;
+ return response;
+ }
+
+ async ensureSession(sessionId, actorPeerId) {
+ const response = await this.ensureSessionResult(sessionId, actorPeerId);
+ return response.ok
+ || (response.status === 409 && response.error?.code === "ALREADY_EXISTS");
+ }
+
+ async ensureSessionResult(sessionId, actorPeerId) {
+ const response = await this.fetchJSON("/api/v1/sessions", {
+ method: "POST",
+ body: JSON.stringify({ session_id: sessionId }),
+ }, { actorPeerId });
+ return response;
+ }
+
+ async getSession(sessionId, actorPeerId) {
+ const response = await this.fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}`,
+ {},
+ { timeoutMs: 5000, actorPeerId },
+ );
+ return response.ok ? response.result : null;
+ }
+
+ async getSessionArchive(sessionId, archiveId, actorPeerId) {
+ const response = await this.fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/archives/${encodeURIComponent(archiveId)}`,
+ {},
+ { actorPeerId },
+ );
+ return response.ok ? response.result : null;
+ }
+
+ async addMessage(sessionId, payload, actorPeerId) {
+ return this.fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
+ {
+ method: "POST",
+ body: JSON.stringify(payload),
+ },
+ { actorPeerId },
+ );
+ }
+
+ async commitSession(sessionId, actorPeerId, options = {}) {
+ return this.fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
+ {
+ method: "POST",
+ body: JSON.stringify({ keep_recent_count: this.config.commitKeepRecentCount }),
+ },
+ { timeoutMs: options.timeoutMs ?? 30000, actorPeerId },
+ );
+ }
+
+ async find(query, options = {}) {
+ const body = { query };
+ if (options.targetUri) body.target_uri = options.targetUri;
+ if (options.limit) body.limit = options.limit;
+ if (options.scoreThreshold !== undefined) body.score_threshold = options.scoreThreshold;
+ const response = await this.fetchJSON("/api/v1/search/find", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId: options.actorPeerId });
+ if (!response.ok || !response.result) return [];
+
+ const results = [];
+ for (const bucket of ["memories", "resources", "skills"]) {
+ const entries = response.result[bucket];
+ if (!Array.isArray(entries)) continue;
+ for (const entry of entries) {
+ results.push({
+ uri: entry?.uri || "",
+ contextType: entry?.context_type
+ || (bucket === "memories" ? "memory" : bucket === "skills" ? "skill" : "resource"),
+ score: Number(entry?.score || 0),
+ abstract: entry?.abstract || "",
+ overview: entry?.overview || null,
+ });
+ }
+ }
+ return results;
+ }
+
+ async read(uri, level, actorPeerId) {
+ const endpoint = level === "abstract"
+ ? "abstract"
+ : level === "overview"
+ ? "overview"
+ : "read";
+ const response = await this.fetchJSON(
+ `/api/v1/content/${endpoint}?uri=${encodeURIComponent(uri)}`,
+ {},
+ { actorPeerId },
+ );
+ return response.ok ? response.result : null;
+ }
+
+ async list(uri, actorPeerId) {
+ const response = await this.fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ return response.ok && Array.isArray(response.result) ? response.result : [];
+ }
+
+ async stat(uri, actorPeerId) {
+ const response = await this.fetchJSON(
+ `/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,
+ {},
+ { actorPeerId },
+ );
+ return response.ok ? response.result : null;
+ }
+
+ async forget(uri, recursive = false, actorPeerId) {
+ const response = await this.fetchJSON(
+ `/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=${recursive}`,
+ { method: "DELETE" },
+ { actorPeerId },
+ );
+ return response.ok;
+ }
+
+ async addResource(path, reason, actorPeerId) {
+ const body = { path };
+ if (reason) body.reason = reason;
+ const response = await this.fetchJSON("/api/v1/resources", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { timeoutMs: 30000, actorPeerId });
+ return response.ok ? response.result : null;
+ }
+}
diff --git a/examples/dsh-memory-plugin/client.test.mjs b/examples/dsh-memory-plugin/client.test.mjs
new file mode 100644
index 000000000..b427eef4b
--- /dev/null
+++ b/examples/dsh-memory-plugin/client.test.mjs
@@ -0,0 +1,181 @@
+import assert from "node:assert/strict";
+import { afterEach, test } from "node:test";
+import { OpenVikingClient } from "./client.mjs";
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+test("client sends OpenViking identity headers and preserves response trace ids", async () => {
+ let seen;
+ globalThis.fetch = async (url, init) => {
+ seen = { url, init };
+ return new Response(JSON.stringify({
+ status: "ok",
+ result: { trace_id: "trace-123", archive_uri: "viking://session/x" },
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "secret",
+ account: "account-a",
+ user: "user-a",
+ peerId: "peer-a",
+ userAgent: "openviking-memory-dsh/0.1.0",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+ const response = await client.commitSession("dsh-1");
+
+ assert.equal(response.ok, true);
+ assert.equal(response.traceId, "trace-123");
+ assert.equal(seen.url, "http://127.0.0.1:1933/api/v1/sessions/dsh-1/commit");
+ assert.equal(seen.init.headers.Authorization, "Bearer secret");
+ assert.equal(seen.init.headers["X-OpenViking-Account"], "account-a");
+ assert.equal(seen.init.headers["X-OpenViking-User"], "user-a");
+ assert.equal(seen.init.headers["X-OpenViking-Actor-Peer"], "peer-a");
+});
+
+test("per-session actor peer overrides the process default", async () => {
+ let headers;
+ globalThis.fetch = async (_url, init) => {
+ headers = init.headers;
+ return new Response(JSON.stringify({ status: "ok", result: {} }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "process-peer",
+ userAgent: "",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+
+ await client.ensureSession("dsh-2", "workspace-peer");
+ assert.equal(headers["X-OpenViking-Actor-Peer"], "workspace-peer");
+});
+
+test("existing OpenViking sessions are reusable on DSH resume", async () => {
+ globalThis.fetch = async () => new Response(JSON.stringify({
+ status: "error",
+ error: { code: "ALREADY_EXISTS", message: "session exists" },
+ }), {
+ status: 409,
+ headers: { "Content-Type": "application/json" },
+ });
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "",
+ userAgent: "",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+
+ assert.equal(await client.ensureSession("dsh-resume"), true);
+});
+
+test("directory listing requests the raw array contract", async () => {
+ let seenUrl;
+ globalThis.fetch = async (url) => {
+ seenUrl = url;
+ return new Response(JSON.stringify({
+ status: "ok",
+ result: [{ name: "notes.md", isDir: false }],
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "",
+ userAgent: "",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+
+ assert.deepEqual(await client.list("viking://resources"), [
+ { name: "notes.md", isDir: false },
+ ]);
+ assert.equal(
+ seenUrl,
+ "http://127.0.0.1:1933/api/v1/fs/ls?uri=viking%3A%2F%2Fresources&output=original",
+ );
+});
+
+test("archive lookup uses the dedicated session archive endpoint", async () => {
+ let seenUrl;
+ globalThis.fetch = async (url) => {
+ seenUrl = url;
+ return new Response(JSON.stringify({
+ status: "ok",
+ result: { archive_id: "archive_001", messages: [] },
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "",
+ userAgent: "",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+
+ assert.deepEqual(
+ await client.getSessionArchive("dsh session", "archive/001"),
+ { archive_id: "archive_001", messages: [] },
+ );
+ assert.equal(
+ seenUrl,
+ "http://127.0.0.1:1933/api/v1/sessions/dsh%20session/archives/archive%2F001",
+ );
+});
+
+test("client normalizes non-2xx OpenViking envelopes", async () => {
+ globalThis.fetch = async () => new Response(JSON.stringify({
+ status: "error",
+ error: { code: "FAILED", message: "nope", trace_id: "trace-error" },
+ }), {
+ status: 503,
+ headers: { "Content-Type": "application/json" },
+ });
+
+ const client = new OpenVikingClient({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "",
+ userAgent: "",
+ requestTimeoutMs: 1000,
+ commitKeepRecentCount: 10,
+ });
+ const response = await client.fetchJSON("/probe");
+
+ assert.equal(response.ok, false);
+ assert.equal(response.status, 503);
+ assert.equal(response.error.code, "FAILED");
+ assert.equal(response.traceId, "trace-error");
+});
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
new file mode 100644
index 000000000..aa9e577cd
--- /dev/null
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -0,0 +1,161 @@
+import { buildUserAgent, resolveOpenVikingCredentials } from "./shared/credentials.mjs";
+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
+
+export const PLUGIN_VERSION = "0.1.0";
+
+const DEFAULT_CONFIG = Object.freeze({
+ endpoint: "http://127.0.0.1:1933",
+ apiKey: "",
+ account: "",
+ user: "",
+ peerId: "",
+ userAgent: "",
+ workspacePeer: true,
+ recallPeerScope: "all",
+ recallQueryExpansion: "auto",
+ recallQueryExpansionConfigured: false,
+ syncTurns: true,
+ recallTokenBudget: 2000,
+ recallMaxContentChars: 500,
+ recallPreferAbstract: true,
+ recallLimit: 10,
+ recallLimitConfigured: false,
+ scoreThreshold: 0.35,
+ minQueryLength: 3,
+ profileTokenBudget: 10000,
+ commitTokenThreshold: 20000,
+ commitKeepRecentCount: 10,
+ captureToolResults: false,
+ captureMode: "semantic",
+ captureMaxLength: 24000,
+ captureToolMaxChars: 1000000,
+ captureAssistantTurns: true,
+ requestTimeoutMs: 10000,
+});
+
+export function resolveConfig(input = {}, env = process.env, cwd = process.cwd()) {
+ const credentials = resolveOpenVikingCredentials(env);
+ const explicitPeerId = input.peerId || credentials.peerId;
+ const config = {
+ ...DEFAULT_CONFIG,
+ ...input,
+ endpoint: input.endpoint || credentials.baseUrl || DEFAULT_CONFIG.endpoint,
+ apiKey: input.apiKey || credentials.apiKey,
+ account: input.account || credentials.account,
+ user: input.user || credentials.user,
+ peerId: explicitPeerId,
+ explicitPeerId,
+ userAgent: buildUserAgent("dsh", PLUGIN_VERSION),
+ recallLimitConfigured: Object.prototype.hasOwnProperty.call(input, "recallLimit"),
+ recallQueryExpansionConfigured: Object.prototype.hasOwnProperty.call(input, "recallQueryExpansion"),
+ };
+
+ if (env.OPENVIKING_WORKSPACE_PEER !== undefined) {
+ config.workspacePeer = environmentBoolean(
+ env.OPENVIKING_WORKSPACE_PEER,
+ config.workspacePeer,
+ );
+ }
+ if (env.OPENVIKING_RECALL_PEER_SCOPE) {
+ config.recallPeerScope = env.OPENVIKING_RECALL_PEER_SCOPE;
+ }
+ if (env.OPENVIKING_RECALL_QUERY_EXPANSION) {
+ config.recallQueryExpansion = env.OPENVIKING_RECALL_QUERY_EXPANSION;
+ config.recallQueryExpansionConfigured = true;
+ }
+ if (env.OPENVIKING_RECALL_LIMIT) {
+ config.recallLimit = env.OPENVIKING_RECALL_LIMIT;
+ config.recallLimitConfigured = true;
+ }
+
+ config.endpoint = String(config.endpoint || DEFAULT_CONFIG.endpoint).replace(/\/+$/, "");
+ config.workspacePeer = config.workspacePeer !== false;
+ config.peerId = resolveEffectivePeerId({ cfg: config, cwd }).peerId;
+ config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all";
+ config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto";
+ config.recallLimit = clampInteger(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);
+ config.recallMaxContentChars = clampInteger(
+ config.recallMaxContentChars,
+ 100,
+ 5000,
+ DEFAULT_CONFIG.recallMaxContentChars,
+ );
+ config.recallTokenBudget = clampInteger(
+ config.recallTokenBudget,
+ 200,
+ 50000,
+ DEFAULT_CONFIG.recallTokenBudget,
+ );
+ config.scoreThreshold = clampNumber(
+ config.scoreThreshold,
+ 0,
+ 1,
+ DEFAULT_CONFIG.scoreThreshold,
+ );
+ config.minQueryLength = clampInteger(
+ config.minQueryLength,
+ 1,
+ 64,
+ DEFAULT_CONFIG.minQueryLength,
+ );
+ config.profileTokenBudget = clampInteger(
+ config.profileTokenBudget,
+ 500,
+ 50000,
+ DEFAULT_CONFIG.profileTokenBudget,
+ );
+ config.commitTokenThreshold = clampInteger(
+ config.commitTokenThreshold,
+ 1000,
+ 1000000,
+ DEFAULT_CONFIG.commitTokenThreshold,
+ );
+ config.commitKeepRecentCount = clampInteger(
+ config.commitKeepRecentCount,
+ 0,
+ 1000,
+ DEFAULT_CONFIG.commitKeepRecentCount,
+ );
+ config.captureMaxLength = clampInteger(
+ config.captureMaxLength,
+ 200,
+ 100000,
+ DEFAULT_CONFIG.captureMaxLength,
+ );
+ config.captureToolMaxChars = clampInteger(
+ config.captureToolMaxChars,
+ 200,
+ 1000000,
+ DEFAULT_CONFIG.captureToolMaxChars,
+ );
+ config.requestTimeoutMs = clampInteger(
+ config.requestTimeoutMs,
+ 1000,
+ 120000,
+ DEFAULT_CONFIG.requestTimeoutMs,
+ );
+ config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";
+ config.syncTurns = config.syncTurns !== false;
+ config.captureAssistantTurns = config.captureAssistantTurns !== false;
+ config.captureToolResults = config.captureToolResults === true;
+ return config;
+}
+
+function environmentBoolean(value, fallback) {
+ const normalized = String(value || "").trim().toLowerCase();
+ if (["0", "false", "no", "off"].includes(normalized)) return false;
+ if (["1", "true", "yes", "on"].includes(normalized)) return true;
+ return fallback;
+}
+
+function clampInteger(value, minimum, maximum, fallback) {
+ const number = Math.round(Number(value));
+ if (!Number.isFinite(number)) return fallback;
+ return Math.max(minimum, Math.min(maximum, number));
+}
+
+function clampNumber(value, minimum, maximum, fallback) {
+ const number = Number(value);
+ if (!Number.isFinite(number)) return fallback;
+ return Math.max(minimum, Math.min(maximum, number));
+}
diff --git a/examples/dsh-memory-plugin/config.test.mjs b/examples/dsh-memory-plugin/config.test.mjs
new file mode 100644
index 000000000..9daabbbcf
--- /dev/null
+++ b/examples/dsh-memory-plugin/config.test.mjs
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { resolveConfig } from "./config.mjs";
+
+test("behavior environment overrides are applied and normalized", () => {
+ const config = resolveConfig({}, {
+ OPENVIKING_URL: "http://127.0.0.1:19464/",
+ OPENVIKING_WORKSPACE_PEER: "0",
+ OPENVIKING_RECALL_PEER_SCOPE: "actor",
+ OPENVIKING_RECALL_QUERY_EXPANSION: "off",
+ OPENVIKING_RECALL_LIMIT: "7",
+ }, "/workspace/project");
+
+ assert.equal(config.endpoint, "http://127.0.0.1:19464");
+ assert.equal(config.workspacePeer, false);
+ assert.equal(config.peerId, "");
+ assert.equal(config.recallPeerScope, "actor");
+ assert.equal(config.recallQueryExpansion, "off");
+ assert.equal(config.recallQueryExpansionConfigured, true);
+ assert.equal(config.recallLimit, 7);
+ assert.equal(config.recallLimitConfigured, true);
+});
+
+test("explicit plugin config overrides credential files", () => {
+ const config = resolveConfig({
+ endpoint: "http://plugin.local",
+ apiKey: "plugin-key",
+ account: "plugin-account",
+ user: "plugin-user",
+ peerId: "plugin-peer",
+ }, {
+ OPENVIKING_URL: "http://env.local",
+ OPENVIKING_API_KEY: "env-key",
+ OPENVIKING_ACCOUNT: "env-account",
+ OPENVIKING_USER: "env-user",
+ OPENVIKING_PEER_ID: "env-peer",
+ }, "/workspace/project");
+
+ assert.equal(config.endpoint, "http://plugin.local");
+ assert.equal(config.apiKey, "plugin-key");
+ assert.equal(config.account, "plugin-account");
+ assert.equal(config.user, "plugin-user");
+ assert.equal(config.peerId, "plugin-peer");
+});
diff --git a/examples/dsh-memory-plugin/cordis.patch.yml b/examples/dsh-memory-plugin/cordis.patch.yml
new file mode 100644
index 000000000..b5d5a8f48
--- /dev/null
+++ b/examples/dsh-memory-plugin/cordis.patch.yml
@@ -0,0 +1,9 @@
+- insert:
+ - id: openviking-memory
+ name: '@deepseek-ai/cordis-plugin-group'
+ group: true
+ isolate:
+ openvikingMemory: true
+ config:
+ - id: openviking-memory-runtime
+ name: '@openviking/dsh-memory-plugin'
diff --git a/examples/dsh-memory-plugin/index.mjs b/examples/dsh-memory-plugin/index.mjs
new file mode 100644
index 000000000..c17d51ccf
--- /dev/null
+++ b/examples/dsh-memory-plugin/index.mjs
@@ -0,0 +1,56 @@
+import { OpenVikingClient } from "./client.mjs";
+import { resolveConfig } from "./config.mjs";
+import { injectStartupProfile } from "./lifecycle.mjs";
+import { OpenVikingRuntime } from "./runtime.mjs";
+import { registerOpenVikingTools } from "./tools.mjs";
+import { guardVikingUri } from "./uri-guard.mjs";
+
+export const name = "openviking-memory";
+export const inject = ["agents", "sessions", "tools"];
+
+export function apply(ctx, input = {}) {
+ const config = resolveConfig(input);
+ const client = new OpenVikingClient(config);
+ const runtime = new OpenVikingRuntime(client, config, ctx.logger);
+ ctx.provide("openvikingMemory", runtime);
+ ctx.effect(
+ () => () => runtime.disposeAll(),
+ "openvikingMemory.disposeAll()",
+ );
+
+ registerOpenVikingTools(ctx, client, runtime);
+
+ ctx.on("agent/session-start", ({ agent }) => {
+ agent.ctx.effect(
+ () => () => runtime.dispose(agent.session),
+ "openvikingMemory.disposeSession()",
+ );
+ return injectStartupProfile(agent, runtime);
+ });
+
+ // prepend: downstream waterfall listeners run first, so this plugin sees
+ // the final claimed batch and appends after every other contributor.
+ ctx.on("agent/pre-step", async ({ agent, messages, signal }, next) => {
+ const decision = await next();
+ if (decision.kind !== "enter" || signal.aborted) return decision;
+ const profile = await runtime.profileMessage(agent);
+ if (signal.aborted) return decision;
+ const recall = await runtime.recallMessage(agent, decision.messages);
+ if (signal.aborted) return decision;
+ const additions = [profile, recall].filter(Boolean);
+ return additions.length > 0
+ ? { kind: "enter", messages: [...decision.messages, ...additions] }
+ : decision;
+ }, { prepend: true });
+
+ ctx.on("session/event", (session, event) => {
+ runtime.capture(session, event);
+ runtime.maybeCommit(session, event);
+ });
+
+ ctx.on("session/flush", async session => {
+ await runtime.flush(session);
+ });
+
+ ctx.on("tools/pre-execute", guardVikingUri);
+}
diff --git a/examples/dsh-memory-plugin/index.test.mjs b/examples/dsh-memory-plugin/index.test.mjs
new file mode 100644
index 000000000..a77a1ee36
--- /dev/null
+++ b/examples/dsh-memory-plugin/index.test.mjs
@@ -0,0 +1,82 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { apply } from "./index.mjs";
+
+test("pre-step recalls from the final downstream message batch", async () => {
+ const handlers = new Map();
+ const ctx = {
+ logger: { debug() {} },
+ provide() {},
+ effect(execute) {
+ execute();
+ return async () => {};
+ },
+ tools: { register() {} },
+ on(name, handler) {
+ handlers.set(name, handler);
+ },
+ };
+ apply(ctx, {
+ endpoint: "http://127.0.0.1:1933",
+ workspacePeer: false,
+ });
+
+ const agent = {
+ session: { id: "dsh-final-batch", header: { cwd: "/workspace" } },
+ ctx: {
+ effect(execute) {
+ execute();
+ return async () => {};
+ },
+ },
+ };
+ const runtime = handlers.get("agent/session-start");
+ assert.equal(typeof runtime, "function");
+
+ const preStep = handlers.get("agent/pre-step");
+ const initial = [message("initial input")];
+ const downstream = [message("downstream replacement")];
+ const seen = [];
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url, init) => {
+ const path = new URL(url).pathname;
+ if (path === "/health") return response({});
+ if (path === "/api/v1/sessions") return response({});
+ if (path === "/api/v1/search/search") {
+ seen.push(JSON.parse(init.body).query);
+ return response({ rendered: "" });
+ }
+ if (path === "/api/v1/fs/ls") return response([]);
+ return response({}, 404);
+ };
+
+ try {
+ await preStep({
+ agent,
+ messages: initial,
+ signal: new AbortController().signal,
+ }, async () => ({ kind: "enter", messages: downstream }));
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+
+ assert.deepEqual(seen, ["downstream replacement"]);
+});
+
+function message(text) {
+ return {
+ role: "user",
+ content: [{ type: "text", text }],
+ source: { kind: "user" },
+ };
+}
+
+function response(result, status = 200) {
+ return new Response(JSON.stringify({
+ status: status < 400 ? "ok" : "error",
+ ...(status < 400 ? { result } : { error: { code: "NOT_FOUND" } }),
+ }), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
diff --git a/examples/dsh-memory-plugin/lifecycle.mjs b/examples/dsh-memory-plugin/lifecycle.mjs
new file mode 100644
index 000000000..c8a69d604
--- /dev/null
+++ b/examples/dsh-memory-plugin/lifecycle.mjs
@@ -0,0 +1,8 @@
+export async function injectStartupProfile(agent, runtime) {
+ await runtime.initialize(agent);
+ if (agent.status !== "idle") return false;
+ const profile = await runtime.profileMessage(agent);
+ if (!profile) return false;
+ agent.inject(profile);
+ return true;
+}
diff --git a/examples/dsh-memory-plugin/lifecycle.test.mjs b/examples/dsh-memory-plugin/lifecycle.test.mjs
new file mode 100644
index 000000000..0684c2976
--- /dev/null
+++ b/examples/dsh-memory-plugin/lifecycle.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { injectStartupProfile } from "./lifecycle.mjs";
+
+test("startup injection leaves profile ownership to pre-step after a turn starts", async () => {
+ let release;
+ const initialized = new Promise(resolve => {
+ release = resolve;
+ });
+ const injected = [];
+ const agent = {
+ status: "idle",
+ inject(message) {
+ injected.push(message);
+ },
+ };
+ let claimed = 0;
+ const runtime = {
+ async initialize() {
+ await initialized;
+ },
+ async profileMessage() {
+ claimed += 1;
+ return { profile: true };
+ },
+ };
+
+ const pending = injectStartupProfile(agent, runtime);
+ agent.status = "running";
+ release();
+
+ assert.equal(await pending, false);
+ assert.equal(claimed, 0);
+ assert.deepEqual(injected, []);
+});
+
+test("startup injection claims and injects a profile while the agent remains idle", async () => {
+ const injected = [];
+ const agent = {
+ status: "idle",
+ inject(message) {
+ injected.push(message);
+ },
+ };
+ const runtime = {
+ async initialize() {},
+ async profileMessage() {
+ return { profile: true };
+ },
+ };
+
+ assert.equal(await injectStartupProfile(agent, runtime), true);
+ assert.deepEqual(injected, [{ profile: true }]);
+});
diff --git a/examples/dsh-memory-plugin/live-recall.test.mjs b/examples/dsh-memory-plugin/live-recall.test.mjs
new file mode 100644
index 000000000..ecd2d8973
--- /dev/null
+++ b/examples/dsh-memory-plugin/live-recall.test.mjs
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import test from "node:test";
+import { OpenVikingClient } from "./client.mjs";
+import { resolveConfig } from "./config.mjs";
+import { buildRecallBlock } from "./shared/recall-core.mjs";
+
+// Real-backend recall gate: proves recall returns a genuine hit for content
+// this test itself stored — the one property no stub or mock can certify.
+// Opt-in because it needs a reachable OpenViking server with a working
+// vector backend: set OPENVIKING_E2E=1 plus the usual credential chain
+// (OPENVIKING_* env / ovcli.conf). Skipped otherwise, including in repo CI
+// until a server secret is configured there.
+const enabled = process.env.OPENVIKING_E2E === "1";
+
+test("live recall returns a hit for a memory stored by this test", { skip: !enabled, timeout: 300_000 }, async () => {
+ // keepRecentCount 0: with the default (10) a single-message session keeps
+ // its whole tail verbatim and extraction has nothing to mine.
+ const config = resolveConfig({ workspacePeer: false, scoreThreshold: 0.1, commitKeepRecentCount: 0 });
+ const client = new OpenVikingClient(config);
+ assert.equal(await client.health(), true, "OpenViking server must be reachable");
+
+ const sentinel = `live-e2e-${randomUUID()}`;
+ const sessionId = `dsh-live-e2e-${Date.now()}`;
+ assert.equal(await client.ensureSession(sessionId), true);
+ const added = await client.addMessage(sessionId, {
+ role: "user",
+ content: `Remember this fact: the deployment codename is ${sentinel}. It unlocks the staging cluster.`,
+ });
+ assert.equal(added.ok, true, "message append must succeed");
+ const committed = await client.commitSession(sessionId);
+ assert.equal(committed.ok, true, "commit must succeed");
+
+ // Memory extraction is asynchronous server-side; wait for the queue, then
+ // poll recall until the sentinel surfaces or the deadline passes.
+ await client.fetchJSON("/api/v1/system/wait", {
+ method: "POST",
+ body: JSON.stringify({ timeout: 120 }),
+ }, { timeoutMs: 125_000 });
+
+ const deadline = Date.now() + 120_000;
+ let block = null;
+ while (Date.now() < deadline) {
+ block = await buildRecallBlock(
+ (path, init, options) => client.fetchJSON(path, init, options),
+ config,
+ `what is the deployment codename ${sentinel}`,
+ {},
+ );
+ if (block !== null && block.includes(sentinel)) break;
+ await new Promise(resolve => setTimeout(resolve, 5000));
+ }
+ assert.ok(block !== null && block.includes(sentinel),
+ `recall block must contain the sentinel; got: ${block === null ? "null" : block.slice(0, 400)}`);
+});
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
new file mode 100644
index 000000000..8bd508a9f
--- /dev/null
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -0,0 +1,272 @@
+{
+ "name": "@openviking/dsh-memory-plugin",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@openviking/dsh-memory-plugin",
+ "version": "0.1.0",
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@deepseek-ai/dsh-llm": "0.1.0-rc.6",
+ "@deepseek-ai/dsh-tools": "0.1.0-rc.6"
+ },
+ "engines": {
+ "node": "^22.19.0 || >=24"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/dsh-llm": "0.1.0-rc.6",
+ "@deepseek-ai/dsh-tools": "0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/cordis": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.1.tgz",
+ "integrity": "sha512-YBdskTU2Po1kru3GgcUWUbkTsPMA9LkSQDAY8rBkFJeajdgcQad3QPJZE26JyK99Xb6HaASvoXg2DSUTeN/0Nw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@deepseek-ai/cosmokit": "^1.8.2",
+ "@standard-schema/spec": "^1.1.0"
+ },
+ "bin": {
+ "cordis": "bin.js"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis-plugin-include": "^1.0.6",
+ "@deepseek-ai/cordis-plugin-loader": "^1.0.2"
+ },
+ "peerDependenciesMeta": {
+ "@deepseek-ai/cordis-plugin-include": {
+ "optional": true
+ },
+ "@deepseek-ai/cordis-plugin-loader": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@deepseek-ai/cosmokit": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.2.tgz",
+ "integrity": "sha512-muBOKtSrUKU5m/xpq8ZXWL6hQ/jgd4PhU2PqH97bcxIiLEJfNwZOGQEx4t/aS/GgxRAR+ra9pMHPMtTHU4sqqA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@deepseek-ai/dsh-agent": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.1.0-rc.6.tgz",
+ "integrity": "sha512-vtqq2pWTrzn0dKfj5kREZRpP82AwtGjGx9V1lYnKvF+Uc/a8zyWbSvjDE7V1d3YQAQJzs2cWO31hURWDekDXIA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-scope": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-typert-protocol": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-attachment": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-attachment/-/dsh-attachment-0.1.0-rc.6.tgz",
+ "integrity": "sha512-3P6N17NQ8jqSQGzeCs+svCIqArU8oq0YmgEAo+axN9aVuUDferWU4DLRSX59UGpmyldX4LQn81toA+c+DqMcHg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-brand": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-brand": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.1.0-rc.6.tgz",
+ "integrity": "sha512-E8j9Nby24qP4rfrdcfc7bpt1CHpGT3tYmycOJJkEOH4ptIdT1m2ro9nmnSd5CWYukTr64A77vjm2WGqHRI92UA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-code-runtime": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-code-runtime/-/dsh-code-runtime-0.1.0-rc.6.tgz",
+ "integrity": "sha512-aw8D4IOeMo11A3uxQeE4LFoW3bvaQnVkGFqqtS+lsINDARrOCJHXLUgecoKpys+Lc5erZZ4UQDnymJmL4OCcKA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-invariants": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-invariants/-/dsh-invariants-0.1.0-rc.6.tgz",
+ "integrity": "sha512-WfEfOi99a4cpOugRAHTBSTnesLieu3ist1q9PXDXFBHX++K1rAl9+sB7YrdnbB8LH0UOY532gS9xJUYU6w0SLw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@deepseek-ai/schemastery": "^3.18.1"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-llm": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.1.0-rc.6.tgz",
+ "integrity": "sha512-kuFGC8bHlzGTwlRxQhXjf3CYWl8M4NzH+EYIkrW8rri4iMc9W53xrdvkil5No/DUlMm8g1u7GdeiWYFy0TMvtA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@deepseek-ai/schemastery": "^3.18.1"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-attachment": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-brand": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-timeout": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-scope": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.1.0-rc.6.tgz",
+ "integrity": "sha512-UlDLV4syLoJinNg9imhXrSAHrdaTa5Ff8gg46rzjFJGPUOhAk3DZff0hryT5OhrBi0A5Tj92qVpg2pRVvxnUzQ==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-session": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.1.0-rc.6.tgz",
+ "integrity": "sha512-8tu8I6VWC7050GAUXWhcEWQw4pakALQc8TlhKr52m7Y4+kIKeNt3FBgP86PaGPBtpK0p5zUPRQNkFpzZbBdxyw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-brand": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-scope": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-typert-protocol": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-system-prompt": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-system-prompt/-/dsh-system-prompt-0.1.0-rc.6.tgz",
+ "integrity": "sha512-E7g+XChh4q4/wX++v56z1pV4SA1Rtz42xkznLPPi9FlXrrzJxwHMOUzBZ9Rz3Y1kLhQ++HJG3ZatmNx3rjFilg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@deepseek-ai/schemastery": "^3.18.1"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-scope": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-timeout": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.1.0-rc.6.tgz",
+ "integrity": "sha512-CUean0fAnfsJVszFEip7PsU/S26W+JfDFfsza2dCtlw8n6xlkbHA9Gjxdk2aTwqDGCgXEPkRW7mYkdJ0n6FR7w==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-tools": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-tools/-/dsh-tools-0.1.0-rc.6.tgz",
+ "integrity": "sha512-Tu08EPK3JyK0iNjH4FGzu/1uADynNSS6SmwOLdfytUN0YNqwNuKFSt2OJUg19famNlTgy992DcHfDu0T+gLXFg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@deepseek-ai/schemastery": "^3.18.1"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-code-runtime": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-scope": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-user-approval": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-typert-protocol": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.1.0-rc.6.tgz",
+ "integrity": "sha512-weWzN8r01YCkoDCAM7BsKw2YhRrD4zL8N2SAZu9hovYtXSq8xHXsP4Zh8RLYIlYcuotjyff/6hic+0TJPd14YA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/dsh-user-approval": {
+ "version": "0.1.0-rc.6",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-user-approval/-/dsh-user-approval-0.1.0-rc.6.tgz",
+ "integrity": "sha512-9rnkSDGOpu2XUeGwbPeTzVUTFWTND1PMPM5L/ZQPptV5yyZlQiNxM2rCC6OdL+ZVerwxEqrRhZIQn/KVtQfKag==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@deepseek-ai/schemastery": "^3.18.1"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "^4.0.1",
+ "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-brand": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-scope": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.6",
+ "@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6"
+ }
+ },
+ "node_modules/@deepseek-ai/schemastery": {
+ "version": "3.18.1",
+ "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.1.tgz",
+ "integrity": "sha512-Qn0FCSwCQnpnj6SB31I6i2sIKgKWnkbJM8O0EU91Gv2UsYVvtZTl6IA0sCwk2e2MZf5S8w5hpq9QkeVvK9qwxg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@deepseek-ai/cosmokit": "^1.8.2",
+ "@standard-schema/spec": "^1.1.0"
+ }
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
new file mode 100644
index 000000000..d0ec0cceb
--- /dev/null
+++ b/examples/dsh-memory-plugin/package.json
@@ -0,0 +1,60 @@
+{
+ "name": "@openviking/dsh-memory-plugin",
+ "version": "0.1.0",
+ "description": "OpenViking memory and context bundle for DeepSeek Harness",
+ "type": "module",
+ "main": "index.mjs",
+ "exports": {
+ ".": "./index.mjs"
+ },
+ "files": [
+ "index.mjs",
+ "client.mjs",
+ "config.mjs",
+ "capture.mjs",
+ "lifecycle.mjs",
+ "runtime.mjs",
+ "tools.mjs",
+ "uri-guard.mjs",
+ "shared/",
+ "cordis.patch.yml",
+ "README.md"
+ ],
+ "dsh": {
+ "bundle": {
+ "patch": "./cordis.patch.yml"
+ }
+ },
+ "scripts": {
+ "test": "node --test *.test.mjs"
+ },
+ "peerDependencies": {
+ "@deepseek-ai/dsh-llm": "0.1.0-rc.6",
+ "@deepseek-ai/dsh-tools": "0.1.0-rc.6"
+ },
+ "devDependencies": {
+ "@deepseek-ai/dsh-llm": "0.1.0-rc.6",
+ "@deepseek-ai/dsh-tools": "0.1.0-rc.6"
+ },
+ "engines": {
+ "node": "^22.19.0 || >=24"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/volcengine/OpenViking.git",
+ "directory": "examples/dsh-memory-plugin"
+ },
+ "keywords": [
+ "deepseek-harness",
+ "dsh",
+ "openviking",
+ "memory",
+ "context",
+ "auto-recall",
+ "auto-capture"
+ ],
+ "license": "Apache-2.0"
+}
diff --git a/examples/dsh-memory-plugin/runtime.mjs b/examples/dsh-memory-plugin/runtime.mjs
new file mode 100644
index 000000000..1061466ec
--- /dev/null
+++ b/examples/dsh-memory-plugin/runtime.mjs
@@ -0,0 +1,316 @@
+import { createUserMessage } from "@deepseek-ai/dsh-llm";
+import { buildProfileBlock } from "./shared/profile-inject.mjs";
+import { buildRecallBlock } from "./shared/recall-core.mjs";
+import { deriveHarnessSessionId } from "./shared/session-model.mjs";
+import {
+ dequeue,
+ enqueue,
+ listPending,
+ replayPending,
+} from "./shared/pending-queue.mjs";
+import { isRetryableFailure } from "./shared/retryable.mjs";
+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
+import {
+ captureEvent,
+ OPENVIKING_PLUGIN_SOURCE,
+ promptText,
+} from "./capture.mjs";
+
+export class OpenVikingRuntime {
+ constructor(client, config, logger = console) {
+ this.client = client;
+ this.config = config;
+ this.logger = logger;
+ this.states = new Map();
+ }
+
+ stateFor(session) {
+ let state = this.states.get(session.id);
+ if (state) return state;
+ const cwd = session.header?.cwd || process.cwd();
+ const peerId = resolveEffectivePeerId({
+ cfg: {
+ peerId: this.config.explicitPeerId,
+ workspacePeer: this.config.workspacePeer,
+ },
+ cwd,
+ }).peerId;
+ state = {
+ dshSessionId: String(session.id),
+ ovSessionId: deriveHarnessSessionId("dsh-", String(session.id)),
+ config: { ...this.config, peerId },
+ ready: false,
+ profileBlock: "",
+ profileDelivered: false,
+ toolNames: new Map(),
+ writes: Promise.resolve(),
+ initializationRetryable: false,
+ hasPendingWrites: false,
+ pendingCreatedAt: 0,
+ disposing: null,
+ };
+ this.states.set(session.id, state);
+ return state;
+ }
+
+ async initialize(agent) {
+ const state = this.stateFor(agent.session);
+ return this.ensureState(state);
+ }
+
+ async ensureState(state) {
+ if (state.ready) return state;
+ if (state.initializing) return state.initializing;
+ state.initializing = this.initializeState(state).finally(() => {
+ state.initializing = null;
+ });
+ return state.initializing;
+ }
+
+ async initializeState(state) {
+ state.initializationRetryable = false;
+ const health = await this.client.healthResult();
+ if (!health.ok) {
+ state.initializationRetryable = isRetryableFailure(health);
+ return state;
+ }
+ const ensured = await this.client.ensureSessionResult(
+ state.ovSessionId,
+ state.config.peerId,
+ );
+ if (
+ !ensured.ok
+ && !(ensured.status === 409 && ensured.error?.code === "ALREADY_EXISTS")
+ ) {
+ state.initializationRetryable = isRetryableFailure(ensured);
+ return state;
+ }
+ await replayPending(
+ (path, init) => this.client.fetchJSON(path, init),
+ (stage, data) => this.log(stage, data),
+ );
+ await this.refreshPendingState(state);
+ const profile = await buildProfileBlock(
+ (path, init, options) => this.client.fetchJSON(path, init, options),
+ state.config.profileTokenBudget,
+ state.config.peerId,
+ );
+ state.profileBlock = profile?.block
+ ? [
+ '<openviking-context source="profile">',
+ profile.block,
+ "</openviking-context>",
+ ].join("\n")
+ : "";
+ state.ready = true;
+ return state;
+ }
+
+ async profileMessage(agent) {
+ const state = await this.initialize(agent);
+ if (!state.ready || !state.profileBlock || state.profileDelivered) return null;
+ state.profileDelivered = true;
+ return pluginMessage(state.profileBlock, "instructions");
+ }
+
+ async recallMessage(agent, messages) {
+ const state = await this.initialize(agent);
+ if (!state.ready) return null;
+ const query = promptText(messages);
+ if (query.length < state.config.minQueryLength) return null;
+ const block = await buildRecallBlock(
+ (path, init, options) => this.client.fetchJSON(path, init, options),
+ state.config,
+ query,
+ {
+ actorPeerId: state.config.peerId,
+ sessionId: state.ovSessionId,
+ log: (stage, data) => this.log(stage, data),
+ },
+ );
+ return block ? pluginMessage(block, "recall") : null;
+ }
+
+ capture(session, event) {
+ const state = this.stateFor(session);
+ if (!state.config.syncTurns) return;
+ const payload = captureEvent(event, state.config, state.toolNames);
+ if (!payload) return;
+ this.enqueueWrite(state, async () => {
+ if (state.hasPendingWrites) {
+ await this.enqueuePendingMessage(state, payload);
+ return;
+ }
+ if (!state.ready && !(await this.ensureState(state)).ready) {
+ if (state.initializationRetryable) {
+ await this.enqueuePendingMessage(state, payload);
+ }
+ return;
+ }
+ if (state.hasPendingWrites) {
+ await this.enqueuePendingMessage(state, payload);
+ return;
+ }
+ const response = await this.client.addMessage(
+ state.ovSessionId,
+ payload,
+ state.config.peerId,
+ );
+ if (isRetryableFailure(response)) {
+ await this.enqueuePendingMessage(state, payload);
+ }
+ });
+ }
+
+ maybeCommit(session, event) {
+ if (event.type !== "turn/end") return;
+ const state = this.stateFor(session);
+ this.enqueueWrite(state, async () => {
+ if (state.hasPendingWrites) return;
+ if (!state.ready && !(await this.ensureState(state)).ready) return;
+ const metadata = await this.client.getSession(
+ state.ovSessionId,
+ state.config.peerId,
+ );
+ if (Number(metadata?.pending_tokens || 0) < state.config.commitTokenThreshold) return;
+ const response = await this.client.commitSession(
+ state.ovSessionId,
+ state.config.peerId,
+ );
+ this.log("commit", {
+ sessionId: state.ovSessionId,
+ ok: response.ok,
+ trace_id: response.result?.trace_id || response.traceId,
+ error: response.ok ? undefined : response.error?.message || response.error?.code,
+ });
+ if (isRetryableFailure(response)) {
+ await this.enqueueFinalCommit(state, {
+ keep_recent_count: state.config.commitKeepRecentCount,
+ });
+ }
+ });
+ }
+
+ dispose(session) {
+ const state = this.states.get(session.id);
+ if (!state) return;
+ if (state.disposing) return state.disposing;
+ state.disposing = (async () => {
+ this.enqueueWrite(state, async () => {
+ const commitPayload = {
+ keep_recent_count: state.config.commitKeepRecentCount,
+ };
+ if (state.hasPendingWrites) {
+ await this.enqueueFinalCommit(state, commitPayload);
+ return;
+ }
+ if (!state.ready && !(await this.ensureState(state)).ready) return;
+ const response = await this.client.commitSession(
+ state.ovSessionId,
+ state.config.peerId,
+ { timeoutMs: Math.min(3000, Number(state.config.requestTimeoutMs) || 3000) },
+ );
+ this.log("shutdown_commit", {
+ sessionId: state.ovSessionId,
+ ok: response.ok,
+ trace_id: response.result?.trace_id || response.traceId,
+ });
+ if (isRetryableFailure(response)) {
+ await this.enqueueFinalCommit(state, commitPayload);
+ }
+ });
+ try {
+ await state.writes;
+ } finally {
+ if (this.states.get(session.id) === state) this.states.delete(session.id);
+ }
+ })();
+ return state.disposing;
+ }
+
+ async disposeAll() {
+ await Promise.all([...this.states.values()].map(state => this.dispose({
+ id: state.dshSessionId,
+ })));
+ }
+
+ enqueueWrite(state, operation) {
+ state.writes = state.writes
+ .then(operation)
+ .catch(error => this.log("write_error", {
+ sessionId: state.ovSessionId,
+ error: error instanceof Error ? error.message : String(error),
+ }));
+ }
+
+ async enqueuePending(state, type, payload) {
+ const createdAt = Math.max(Date.now(), state.pendingCreatedAt + 1);
+ state.pendingCreatedAt = createdAt;
+ const result = await enqueue(type, state.ovSessionId, payload, { createdAt });
+ if (result.ok) state.hasPendingWrites = true;
+ if (!result.ok) {
+ this.log("pending_enqueue_error", {
+ sessionId: state.ovSessionId,
+ type,
+ error: result.error,
+ });
+ }
+ return result;
+ }
+
+ async enqueueFinalCommit(state, payload) {
+ await this.removePendingCommits(state);
+ return this.enqueuePending(state, "commitSession", payload);
+ }
+
+ async enqueuePendingMessage(state, payload) {
+ const result = await this.enqueuePending(state, "addMessage", payload);
+ if (result.ok) await this.removePendingCommits(state);
+ return result;
+ }
+
+ async removePendingCommits(state) {
+ const pending = await listPending();
+ for (const item of pending) {
+ if (
+ item.entry?.type === "commitSession"
+ && item.entry.sessionId === state.ovSessionId
+ ) {
+ await dequeue(item.filename);
+ }
+ }
+ }
+
+ async refreshPendingState(state) {
+ const pending = (await listPending()).filter(
+ item => item.entry?.sessionId === state.ovSessionId,
+ );
+ state.hasPendingWrites = pending.length > 0;
+ state.pendingCreatedAt = pending.reduce(
+ (latest, item) => Math.max(latest, Number(item.entry?.createdAt || 0)),
+ state.pendingCreatedAt,
+ );
+ }
+
+ async flush(session) {
+ const state = this.states.get(session.id);
+ if (state) await state.writes;
+ }
+
+ log(stage, data) {
+ this.logger?.debug?.(`[openviking:dsh] ${stage} ${JSON.stringify(data)}`);
+ }
+}
+
+function pluginMessage(content, form) {
+ // dsh's own constructor: identity, normalization, and any future Message
+ // invariants come from the pinned peer instead of a hand-built object.
+ return createUserMessage({
+ content: [{ type: "text", text: content }],
+ source: {
+ kind: "plugin",
+ plugin: OPENVIKING_PLUGIN_SOURCE,
+ form,
+ },
+ });
+}
diff --git a/examples/dsh-memory-plugin/runtime.test.mjs b/examples/dsh-memory-plugin/runtime.test.mjs
new file mode 100644
index 000000000..bbd9e5f78
--- /dev/null
+++ b/examples/dsh-memory-plugin/runtime.test.mjs
@@ -0,0 +1,251 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, test } from "node:test";
+import { enqueue, listPending } from "./shared/pending-queue.mjs";
+import { OpenVikingRuntime } from "./runtime.mjs";
+
+const originalPendingDir = process.env.OPENVIKING_PENDING_DIR;
+const tempDirs = [];
+
+afterEach(async () => {
+ if (originalPendingDir === undefined) delete process.env.OPENVIKING_PENDING_DIR;
+ else process.env.OPENVIKING_PENDING_DIR = originalPendingDir;
+ await Promise.all(tempDirs.splice(0).map(dir => rm(dir, { recursive: true, force: true })));
+});
+
+test("capture queues retryable failures but drops permanent client errors", async () => {
+ for (const [status, expectedPending] of [[400, 0], [503, 1]]) {
+ const pendingDir = await mkdtemp(join(tmpdir(), `dsh-memory-${status}-`));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+
+ const runtime = new OpenVikingRuntime({
+ async addMessage() {
+ return { ok: false, status, error: { code: "FAILED" } };
+ },
+ }, config(), { debug() {} });
+ const session = { id: `session-${status}`, header: { cwd: "/workspace" } };
+ runtime.stateFor(session).ready = true;
+
+ runtime.capture(session, userEvent(`Remember the ${status} behavior.`));
+ await runtime.flush(session);
+
+ assert.equal((await listPending()).length, expectedPending, `HTTP ${status}`);
+ }
+});
+
+test("initialization queues capture only when the failure is retryable", async () => {
+ for (const [status, expectedPending] of [[401, 0], [503, 1]]) {
+ const pendingDir = await mkdtemp(join(tmpdir(), `dsh-memory-init-${status}-`));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+
+ const runtime = new OpenVikingRuntime({
+ async healthResult() {
+ return { ok: false, status, error: { code: "FAILED" } };
+ },
+ }, config(), { debug() {} });
+ const session = { id: `init-${status}`, header: { cwd: "/workspace" } };
+
+ runtime.capture(session, userEvent(`Remember the init ${status} behavior.`));
+ await runtime.flush(session);
+
+ assert.equal((await listPending()).length, expectedPending, `HTTP ${status}`);
+ }
+});
+
+test("a retryable threshold commit failure is queued", async () => {
+ const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-commit-"));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+ const runtime = new OpenVikingRuntime({
+ async getSession() {
+ return { pending_tokens: 20000 };
+ },
+ async commitSession() {
+ return { ok: false, status: 503, error: { code: "UNAVAILABLE" } };
+ },
+ }, config(), { debug() {} });
+ const session = { id: "commit-failure", header: { cwd: "/workspace" } };
+ runtime.stateFor(session).ready = true;
+
+ runtime.maybeCommit(session, { type: "turn/end" });
+ await runtime.flush(session);
+
+ assert.deepEqual((await listPending()).map(item => item.entry.type), [
+ "commitSession",
+ ]);
+});
+
+test("once a write is queued, later messages and the final commit stay ordered on disk", async () => {
+ const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-order-"));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+ let addCalls = 0;
+ let commitCalls = 0;
+ const runtime = new OpenVikingRuntime({
+ async addMessage() {
+ addCalls += 1;
+ return { ok: false, status: 503, error: { code: "UNAVAILABLE" } };
+ },
+ async commitSession() {
+ commitCalls += 1;
+ return { ok: true };
+ },
+ }, config(), { debug() {} });
+ const session = { id: "ordered", header: { cwd: "/workspace" } };
+ runtime.stateFor(session).ready = true;
+
+ runtime.capture(session, userEvent("First queued message."));
+ runtime.capture(session, userEvent("Second queued message."));
+ runtime.maybeCommit(session, { type: "turn/end" });
+ await runtime.flush(session);
+ assert.deepEqual((await listPending()).map(item => item.entry.type), [
+ "addMessage",
+ "addMessage",
+ ]);
+ await runtime.dispose(session);
+
+ const pending = await listPending();
+ assert.deepEqual(pending.map(item => item.entry.type), [
+ "addMessage",
+ "addMessage",
+ "commitSession",
+ ]);
+ assert.deepEqual(
+ pending.map(item => (
+ item.entry.payload.parts?.[0]?.text
+ || item.entry.payload.content
+ || item.entry.payload.keep_recent_count
+ )),
+ ["First queued message.", "Second queued message.", 10],
+ );
+ assert.deepEqual(
+ pending.map(item => item.entry.createdAt),
+ [...pending.map(item => item.entry.createdAt)].sort((left, right) => left - right),
+ );
+ assert.equal(addCalls, 1);
+ assert.equal(commitCalls, 0);
+});
+
+test("new queued messages move an older pending commit behind them", async () => {
+ const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-reorder-"));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+ await enqueue("commitSession", "dsh-reorder", { keep_recent_count: 10 });
+ const runtime = new OpenVikingRuntime({
+ async healthResult() {
+ return { ok: true };
+ },
+ async ensureSessionResult() {
+ return { ok: true };
+ },
+ async fetchJSON() {
+ return { ok: false, status: 503, error: { code: "UNAVAILABLE" } };
+ },
+ }, config(), { debug() {} });
+ const session = { id: "reorder", header: { cwd: "/workspace" } };
+
+ runtime.capture(session, userEvent("Message after an offline commit."));
+ await runtime.flush(session);
+ assert.deepEqual((await listPending()).map(item => item.entry.type), [
+ "addMessage",
+ ]);
+
+ await runtime.dispose(session);
+ assert.deepEqual((await listPending()).map(item => item.entry.type), [
+ "addMessage",
+ "commitSession",
+ ]);
+});
+
+test("flush waits only for the requested session", async () => {
+ const runtime = new OpenVikingRuntime({}, config(), { debug() {} });
+ const first = { id: "first", header: { cwd: "/workspace/first" } };
+ const second = { id: "second", header: { cwd: "/workspace/second" } };
+ let releaseSecond;
+ runtime.stateFor(first).writes = Promise.resolve();
+ runtime.stateFor(second).writes = new Promise(resolve => {
+ releaseSecond = resolve;
+ });
+
+ await runtime.flush(first);
+ releaseSecond();
+ await runtime.flush(second);
+});
+
+test("dispose waits for the final commit before deleting session state", async () => {
+ let releaseCommit;
+ let commitOptions;
+ const committed = new Promise(resolve => {
+ releaseCommit = resolve;
+ });
+ const runtime = new OpenVikingRuntime({
+ async commitSession(_sessionId, _peerId, options) {
+ commitOptions = options;
+ await committed;
+ return { ok: true, result: { trace_id: "shutdown" } };
+ },
+ }, config(), { debug() {} });
+ const session = { id: "dispose", header: { cwd: "/workspace" } };
+ runtime.stateFor(session).ready = true;
+
+ let settled = false;
+ const disposing = runtime.dispose(session).then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+
+ assert.equal(settled, false);
+ assert.equal(runtime.states.has(session.id), true);
+ assert.deepEqual(commitOptions, { timeoutMs: 3000 });
+ releaseCommit();
+ await disposing;
+ assert.equal(runtime.states.has(session.id), false);
+});
+
+test("disposeAll drains every live session", async () => {
+ const committed = [];
+ const runtime = new OpenVikingRuntime({
+ async commitSession(sessionId) {
+ committed.push(sessionId);
+ return { ok: true };
+ },
+ }, config(), { debug() {} });
+ for (const id of ["one", "two"]) {
+ runtime.stateFor({ id, header: { cwd: `/workspace/${id}` } }).ready = true;
+ }
+
+ await runtime.disposeAll();
+
+ assert.deepEqual(committed.sort(), ["dsh-one", "dsh-two"]);
+ assert.equal(runtime.states.size, 0);
+});
+
+function config() {
+ return {
+ explicitPeerId: "",
+ workspacePeer: false,
+ peerId: "",
+ syncTurns: true,
+ captureAssistantTurns: true,
+ captureToolResults: false,
+ captureToolMaxChars: 1000000,
+ captureMaxLength: 24000,
+ captureMode: "semantic",
+ commitKeepRecentCount: 10,
+ };
+}
+
+function userEvent(text) {
+ return {
+ type: "user/message",
+ data: {
+ role: "user",
+ content: [{ type: "text", text }],
+ source: { kind: "user" },
+ },
+ };
+}
diff --git a/examples/dsh-memory-plugin/shared/capture-utils.mjs b/examples/dsh-memory-plugin/shared/capture-utils.mjs
new file mode 100644
index 000000000..3e078db47
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/capture-utils.mjs
@@ -0,0 +1,515 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);
+const TOOL_CALL_TYPES = new Set([
+ "tool_call",
+ "toolcall",
+ "tool_use",
+ "tooluse",
+ "function_call",
+ "functioncall",
+]);
+const TOOL_RESULT_TYPES = new Set([
+ "tool_result",
+ "toolresult",
+ "tool_output",
+ "tooloutput",
+ "function_call_output",
+ "functioncalloutput",
+]);
+
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
+const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
+const METADATA_KEYS = [
+ "session_id",
+ "sessionid",
+ "sessionkey",
+ "conversation_id",
+ "conversationid",
+ "channel",
+ "sender",
+ "user_id",
+ "userid",
+ "agent_id",
+ "agentid",
+ "timestamp",
+ "timezone",
+ "cwd",
+ "model",
+ "permission_mode",
+];
+
+function normalizeType(value) {
+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");
+}
+
+function isToolCallBlock(block) {
+ const type = normalizeType(block?.type || block?.kind || block?.role);
+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);
+}
+
+function isToolResultBlock(block) {
+ const type = normalizeType(block?.type || block?.kind || block?.role);
+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";
+}
+
+function oneLine(text) {
+ return String(text || "").replace(/\s+/g, " ").trim();
+}
+
+export function truncateCaptureText(text, maxChars = 2000) {
+ const value = String(text || "").trim();
+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;
+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;
+}
+
+function stringifyCompact(value, maxChars) {
+ if (value == null) return "";
+ if (typeof value === "string") return truncateCaptureText(value, maxChars);
+ try {
+ return truncateCaptureText(JSON.stringify(value), maxChars);
+ } catch {
+ return truncateCaptureText(String(value), maxChars);
+ }
+}
+
+function parseMaybeJson(value) {
+ if (value == null || typeof value !== "string") return value;
+ const trimmed = value.trim();
+ if (!trimmed) return value;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return value;
+ }
+}
+
+function blockText(block) {
+ if (!block || typeof block !== "object") return "";
+ if (typeof block.text === "string") return block.text;
+ if (typeof block.output_text === "string") return block.output_text;
+ if (typeof block.input_text === "string") return block.input_text;
+ if (typeof block.content === "string") return block.content;
+ return "";
+}
+
+function toolName(block) {
+ return oneLine(
+ block?.name ||
+ block?.tool_name ||
+ block?.toolName ||
+ block?.tool ||
+ block?.function?.name ||
+ block?.call?.name ||
+ "",
+ );
+}
+
+function toolPayload(block, kind) {
+ if (!block || typeof block !== "object") return "";
+ if (kind === "call") {
+ return block.input ??
+ block.state?.input ??
+ block.arguments ??
+ block.args ??
+ block.params ??
+ block.function?.arguments ??
+ block.command ??
+ block.call?.input ??
+ block.call?.arguments ??
+ "";
+ }
+ return block.output ??
+ block.state?.output ??
+ block.result ??
+ block.error ??
+ block.state?.error ??
+ block.data ??
+ block.content ??
+ block.text ??
+ "";
+}
+
+function toolId(block) {
+ return oneLine(
+ block?.call_id ||
+ block?.callId ||
+ block?.callID ||
+ block?.tool_call_id ||
+ block?.toolCallId ||
+ block?.tool_use_id ||
+ block?.toolUseId ||
+ block?.function_call_id ||
+ block?.functionCallId ||
+ block?.id ||
+ "",
+ );
+}
+
+function toolStatus(block, kind) {
+ if (kind === "call") return "running";
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
+ return status || "completed";
+}
+
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
+ const id = toolId(block);
+ const name = toolName(block) || (id ? toolNameById[id] : "");
+ const payload = toolPayload(block, kind);
+ const part = {
+ type: "tool",
+ tool_id: id || undefined,
+ tool_name: name || undefined,
+ tool_status: toolStatus(block, kind),
+ };
+ if (kind === "call") {
+ setToolInput(part, payload);
+ } else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
+ part.tool_output = stringifyCompact(payload, toolMaxChars);
+ }
+ return part;
+}
+
+function formatToolBlock(block, kind, maxChars) {
+ const name = toolName(block);
+ const payload = toolPayload(block, kind);
+ const body = oneLine(stringifyCompact(payload, maxChars));
+ const label = kind === "call" ? "tool-call" : "tool-result";
+ return body
+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`
+ : `[${label}${name ? ` ${name}` : ""}]`;
+}
+
+function blockToText(block, options) {
+ if (!block) return "";
+ if (typeof block === "string") return block;
+ if (Array.isArray(block)) return extractTextFromContent(block, options);
+ if (typeof block !== "object") return "";
+
+ if (block.item && typeof block.item === "object") {
+ const itemText = blockToText(block.item, options);
+ if (itemText) return itemText;
+ }
+
+ const type = normalizeType(block.type || block.kind || block.role);
+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);
+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);
+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);
+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);
+ if (!type) return blockText(block);
+ return "";
+}
+
+export function extractTextFromContent(content, options = {}) {
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
+ if (!content) return "";
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ return content
+ .map((block) => blockToText(block, opts))
+ .filter(Boolean)
+ .join("\n\n");
+ }
+ if (typeof content === "object") {
+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);
+ }
+ return "";
+}
+
+export function extractTextFromPayload(payload, options = {}) {
+ if (!payload || typeof payload !== "object") return "";
+ const chunks = [];
+ const directType = normalizeType(payload.type || payload.kind || payload.role);
+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
+ if (direct) return direct;
+ }
+
+ if (payload.message && typeof payload.message === "object") {
+ const messageText = extractTextFromPayload(payload.message, options);
+ if (messageText) chunks.push(messageText);
+ } else if (payload.content !== undefined) {
+ const contentText = extractTextFromContent(payload.content, options);
+ if (contentText) chunks.push(contentText);
+ }
+
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ const toolText = extractTextFromContent(value, options);
+ if (toolText) chunks.push(toolText);
+ }
+
+ if (chunks.length === 0) {
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
+ if (direct) chunks.push(direct);
+ }
+
+ return chunks.join("\n\n");
+}
+
+function collectToolNamesByIdFromEntries(entries) {
+ const map = {};
+ for (const entry of entries || []) {
+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;
+ collectToolNamesByIdFromPayload(payload, map);
+ }
+ return map;
+}
+
+function collectToolNamesByIdFromPayload(payload, out) {
+ if (!payload || typeof payload !== "object") return;
+ if (payload.message && typeof payload.message === "object") {
+ collectToolNamesByIdFromPayload(payload.message, out);
+ }
+ const candidates = [];
+ if (Array.isArray(payload.content)) candidates.push(...payload.content);
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ if (Array.isArray(value)) candidates.push(...value);
+ else candidates.push(value);
+ }
+ if (isToolCallBlock(payload)) candidates.push(payload);
+ for (const block of candidates) {
+ if (!block || typeof block !== "object") continue;
+ if (!isToolCallBlock(block)) continue;
+ const id = toolId(block);
+ const name = toolName(block);
+ if (id && name) out[id] = name;
+ }
+}
+
+function extractPartsFromContent(content, options = {}) {
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
+ const parts = [];
+ if (!content) return parts;
+ if (typeof content === "string") {
+ if (content.trim()) parts.push({ type: "text", text: content });
+ return parts;
+ }
+ if (!Array.isArray(content)) {
+ const text = blockToText(content, opts);
+ if (text.trim()) parts.push({ type: "text", text });
+ return parts;
+ }
+ for (const block of content) {
+ if (!block || typeof block !== "object") continue;
+ if (isToolCallBlock(block)) {
+ parts.push(buildToolPart(block, "call", opts));
+ } else if (isToolResultBlock(block)) {
+ parts.push(buildToolPart(block, "result", opts));
+ } else {
+ const text = blockToText(block, opts);
+ if (text.trim()) parts.push({ type: "text", text });
+ }
+ }
+ return parts;
+}
+
+export function extractPartsFromPayload(payload, options = {}) {
+ if (!payload || typeof payload !== "object") return [];
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
+ if (payload.message && typeof payload.message === "object") {
+ return extractPartsFromPayload(payload.message, opts);
+ }
+
+ const directType = normalizeType(payload.type || payload.kind || payload.role);
+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {
+ return [buildToolPart(payload, "call", opts)];
+ }
+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {
+ return [buildToolPart(payload, "result", opts)];
+ }
+
+ const parts = [];
+ if (payload.content !== undefined) {
+ parts.push(...extractPartsFromContent(payload.content, opts));
+ }
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ if (Array.isArray(value)) {
+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));
+ } else {
+ parts.push(...extractPartsFromPayload(value, opts));
+ }
+ }
+ return parts;
+}
+
+export function extractCaptureTurns(rolloutEntries, cfg = {}) {
+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);
+ const turns = [];
+ for (const entry of rolloutEntries || []) {
+ if (!entry || typeof entry !== "object") continue;
+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;
+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;
+ const rawRole = message?.role || payload.role || payload.type || payload.kind;
+ const role = normalizeCaptureRole(rawRole);
+ if (!role) continue;
+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;
+
+ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });
+ const parts = extractPartsFromPayload(payload, {
+ toolMaxChars: cfg.captureToolMaxChars,
+ toolNameById,
+ });
+ const decision = shouldCaptureText(rawText, role, cfg);
+ if (!decision.shouldCapture && parts.length === 0) continue;
+ const text = decision.shouldCapture ? decision.text : "";
+ turns.push({ role, text, parts });
+ }
+ return turns;
+}
+
+export function normalizeCaptureRole(role) {
+ const value = normalizeType(role);
+ if (value === "user") return "user";
+ if (value === "assistant") return "assistant";
+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {
+ return "user";
+ }
+ if (value === "tool_call" || value === "function_call") return "assistant";
+ return null;
+}
+
+export function isAssistantSideCaptureRole(role) {
+ const value = normalizeType(role);
+ return value === "assistant" ||
+ value === "tool" ||
+ value === "tool_result" ||
+ value === "tool_call" ||
+ value === "function" ||
+ value === "function_call" ||
+ value === "function_call_output";
+}
+
+function stripMetadataFences(text) {
+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {
+ const lower = body.toLowerCase();
+ let hits = 0;
+ for (const key of METADATA_KEYS) {
+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");
+ if (re.test(lower)) hits += 1;
+ }
+ return hits >= 3 ? "" : match;
+ });
+}
+
+function stripInjectedDigestBlocks(text) {
+ const lines = String(text || "").split(/\r?\n/);
+ const out = [];
+ let skipping = false;
+ let skipUntilMcpHint = false;
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (/^OpenViking session archive digest:/i.test(trimmed)) {
+ skipping = true;
+ skipUntilMcpHint = true;
+ continue;
+ }
+ if (/^OpenViking memory digest:/i.test(trimmed)) {
+ skipping = true;
+ skipUntilMcpHint = false;
+ continue;
+ }
+ if (skipping) {
+ if (skipUntilMcpHint) {
+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {
+ skipping = false;
+ skipUntilMcpHint = false;
+ }
+ continue;
+ }
+ if (!trimmed) {
+ skipping = false;
+ continue;
+ }
+ if (
+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||
+ /^\s{2,}\S/.test(line)
+ ) {
+ continue;
+ }
+ skipping = false;
+ }
+ out.push(line);
+ }
+
+ return out.join("\n");
+}
+
+export function sanitizeCapturedText(text) {
+ let value = String(text || "");
+ value = value
+ .replace(/\u0000/g, "")
+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")
+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")
+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")
+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")
+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")
+ .replace(/^\s*\d{10,13}\s+/gm, "");
+ value = stripMetadataFences(value);
+ value = stripInjectedDigestBlocks(value);
+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");
+ return value
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+function hasEnoughSignal(text) {
+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;
+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;
+ return cjk >= 4 || alnum >= 6 || text.length >= 12;
+}
+
+function isPunctuationOnly(text) {
+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);
+}
+
+export function shouldCaptureText(text, role, cfg = {}) {
+ const maxLength = cfg.captureMaxLength || 24000;
+ const sanitized = sanitizeCapturedText(text);
+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
+
+ const capped = truncateCaptureText(sanitized, maxLength);
+ const compact = oneLine(capped);
+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);
+
+ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {
+ return { shouldCapture: false, reason: "slash_command", text: "" };
+ }
+ if (!isToolSummary && ACK_RE.test(compact)) {
+ return { shouldCapture: false, reason: "ack", text: "" };
+ }
+ if (!isToolSummary && isPunctuationOnly(compact)) {
+ return { shouldCapture: false, reason: "punctuation", text: "" };
+ }
+ if (!isToolSummary && !hasEnoughSignal(compact)) {
+ return { shouldCapture: false, reason: "too_short", text: "" };
+ }
+ if (/^\[openviking-memory\]/i.test(compact)) {
+ return { shouldCapture: false, reason: "plugin_status", text: "" };
+ }
+
+ return { shouldCapture: true, reason: "ok", text: capped };
+}
diff --git a/examples/dsh-memory-plugin/shared/credentials.mjs b/examples/dsh-memory-plugin/shared/credentials.mjs
new file mode 100644
index 000000000..30d5401f2
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/credentials.mjs
@@ -0,0 +1,228 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
+
+function str(val, fallback = "") {
+ if (typeof val === "string" && val.trim()) return val.trim();
+ return fallback;
+}
+
+function normalizePath(value) {
+ const raw = str(value, "");
+ if (!raw) return "";
+ if (raw === "~") return homedir();
+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
+ return resolvePath(raw);
+}
+
+function tryLoadJson(path) {
+ if (!path) return null;
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build the User-Agent every harness plugin sends on OpenViking-bound requests.
+ * Shape is `name/semver` so downstream stats layers can parse it as one token.
+ */
+export function buildUserAgent(harness, version) {
+ return `openviking-memory-${harness}/${str(version, "") || "0.0.0"}`;
+}
+
+/**
+ * Read a plugin manifest's `version` field. Accepts a path or a URL (so callers
+ * can resolve relative to import.meta.url). Returns "" when unreadable so the
+ * User-Agent falls back to 0.0.0 instead of throwing inside a short-lived hook.
+ */
+export function readManifestVersion(manifest) {
+ try {
+ return str(JSON.parse(readFileSync(manifest, "utf-8")).version, "");
+ } catch {
+ return "";
+ }
+}
+
+function looksLikeOvcli(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ if (obj.server && typeof obj.server === "object") return false;
+ return Boolean(
+ typeof obj.url === "string" ||
+ typeof obj.api_key === "string" ||
+ typeof obj.account === "string" ||
+ typeof obj.account_id === "string" ||
+ typeof obj.user === "string" ||
+ typeof obj.user_id === "string" ||
+ typeof obj.actor_peer_id === "string",
+ );
+}
+
+function hasCredentialFields(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ return [
+ "url",
+ "api_key",
+ "account",
+ "account_id",
+ "user",
+ "user_id",
+ "actor_peer_id",
+ "peer_id",
+ ].some((key) => typeof obj[key] === "string");
+}
+
+export function loadCredentialFiles(env = process.env) {
+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;
+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;
+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));
+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));
+
+ let cliFile = tryLoadJson(cliPathCandidate);
+ let cliPath = cliFile ? cliPathCandidate : "";
+ let ovFile = tryLoadJson(ovPathCandidate);
+ let ovPath = ovFile ? ovPathCandidate : "";
+
+ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for
+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.
+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {
+ cliFile = ovFile;
+ cliPath = ovPath;
+ ovFile = null;
+ ovPath = "";
+ }
+
+ return {
+ cliFile: cliFile || {},
+ cliPath,
+ cliPathCandidate,
+ ovFile: ovFile || {},
+ ovPath,
+ };
+}
+
+function sourceMode(env) {
+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
+ .toLowerCase();
+ if (raw === "env" || raw === "environment") return "env";
+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";
+ return "auto";
+}
+
+function hasEnvCredentialFields(env) {
+ return Boolean(
+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
+ str(env.OPENVIKING_MCP_URL, "") ||
+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(env.OPENVIKING_USER, "") ||
+ str(env.OPENVIKING_PEER_ID, ""),
+ );
+}
+
+function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const cliUrl = str(cliFile.url, "");
+
+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
+ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
+
+ const server = ovFile.server || {};
+ const ovUrl = str(server.url, "");
+ if (ovUrl) return ovUrl.replace(/\/+$/, "");
+
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
+export function resolveOpenVikingCredentials(env = process.env) {
+ const files = loadCredentialFiles(env);
+ const mode = sourceMode(env);
+ const envHasCredentials = hasEnvCredentialFields(env);
+ const useCli = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
+ const cx = files.ovFile.codex || {};
+ const server = files.ovFile.server || {};
+
+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+
+ const apiKey = useCli
+ ? str(files.cliFile.api_key, "")
+ : (
+ str(env.OPENVIKING_BEARER_TOKEN, "") ||
+ str(env.OPENVIKING_API_KEY, "") ||
+ str(files.cliFile.api_key, "") ||
+ str(cx.apiKey, "") ||
+ str(server.root_api_key, "")
+ );
+
+ const account = useCli
+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ : (
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ str(cx.accountId, "")
+ );
+
+ const user = useCli
+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ : (
+ str(env.OPENVIKING_USER, "") ||
+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ str(cx.userId, "")
+ );
+
+ const peerId = useCli
+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
+ : (
+ str(env.OPENVIKING_PEER_ID, "") ||
+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
+ str(cx.peerId, str(cx.peer_id, ""))
+ );
+
+ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
+
+ return {
+ ...files,
+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ baseUrl,
+ mcpUrl,
+ apiKey,
+ account,
+ user,
+ peerId,
+ hasApiKey: Boolean(apiKey),
+ };
+}
+
+function main() {
+ const cmd = process.argv[2] || "";
+ if (cmd === "mcp-url") {
+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
+ return;
+ }
+ if (cmd === "has-api-key") {
+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
+ return;
+ }
+ if (cmd === "has-peer-id") {
+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
+ return;
+ }
+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
+ process.exitCode = 2;
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+ main();
+}
diff --git a/examples/dsh-memory-plugin/shared/debug-log.mjs b/examples/dsh-memory-plugin/shared/debug-log.mjs
new file mode 100644
index 000000000..73855cf6d
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/debug-log.mjs
@@ -0,0 +1,58 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared structured debug logger for OpenViking memory plugin hook scripts.
+ *
+ * Harness-specific wrappers load config and pass {debug, debugLogPath}. This
+ * module stays path-agnostic so it can be vendored into each plugin snapshot.
+ */
+
+import { appendFileSync, mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+function ensureDir(filePath) {
+ try {
+ mkdirSync(dirname(filePath), { recursive: true });
+ } catch { /* best effort */ }
+}
+
+function writeLine(filePath, obj) {
+ try {
+ appendFileSync(filePath, JSON.stringify(obj) + "\n");
+ } catch { /* best effort */ }
+}
+
+function localISO() {
+ const d = new Date();
+ const off = d.getTimezoneOffset();
+ const sign = off <= 0 ? "+" : "-";
+ const abs = Math.abs(off);
+ const local = new Date(d.getTime() - off * 60000);
+ return local.toISOString().replace(
+ "Z",
+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`,
+ );
+}
+
+const noop = () => {};
+
+export function createLogger(hookName, overrideCfg) {
+ const c = overrideCfg || {};
+ if (!c.debug) return { log: noop, logError: noop };
+
+ const logPath = c.debugLogPath;
+ if (!logPath) return { log: noop, logError: noop };
+ ensureDir(logPath);
+
+ function log(stage, data) {
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });
+ }
+
+ function logError(stage, err) {
+ const error = err instanceof Error
+ ? { message: err.message, stack: err.stack }
+ : String(err);
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });
+ }
+
+ return { log, logError };
+}
diff --git a/examples/dsh-memory-plugin/shared/pending-queue.mjs b/examples/dsh-memory-plugin/shared/pending-queue.mjs
new file mode 100644
index 000000000..4b3836a4b
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/pending-queue.mjs
@@ -0,0 +1,451 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Local pending queue for offline resilience.
+ *
+ * When the OpenViking server is temporarily unreachable, write operations
+ * (addMessage, commitSession) serialize their payloads to
+ * `~/.openviking/pending/` as JSON files. On the next session-start, the
+ * queue is replayed in small batches. This is a session-start-triggered retry
+ * path with maxRetries/TTL, not a long-running background worker.
+ *
+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }
+ *
+ * Config (env vars):
+ * OPENVIKING_PENDING_DIR pending queue directory
+ * (default: ~/.openviking/pending)
+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)
+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup
+ * (default: 7)
+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start
+ * (default: 50)
+ */
+
+import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { join } from "node:path";
+import { homedir } from "node:os";
+import { isRetryableFailure } from "./retryable.mjs";
+
+const DEFAULT_MAX_RETRIES = 3;
+const DEFAULT_TTL_DAYS = 7;
+const DEFAULT_REPLAY_LIMIT = 50;
+const PROCESSING_STALE_MS = 10 * 60 * 1000;
+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");
+
+// Pending queue files may contain raw memory payload / transcript content.
+// Use restrictive permissions explicitly so we don't depend on umask.
+// - dir: 0o700 (owner: rwx; group/other: none)
+// - file: 0o600 (owner: rw; group/other: none)
+const PENDING_DIR_MODE = 0o700;
+const PENDING_FILE_MODE = 0o600;
+
+/**
+ * Ensure the pending directory exists with 0o700 permissions. If the
+ * directory was created by a previous version of this code (or by hand)
+ * with looser permissions, best-effort chmod it on first use.
+ */
+async function ensurePendingDir(dir) {
+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });
+ try {
+ await chmod(dir, PENDING_DIR_MODE);
+ } catch {
+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.
+ }
+}
+
+function getPendingDir() {
+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();
+}
+
+function getMaxRetries() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;
+}
+
+function getTTLDays() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;
+}
+
+function getReplayLimit() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;
+}
+
+function stableStringify(value) {
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
+}
+
+function makeDedupKey(type, sessionId, payload) {
+ return createHash("sha256")
+ .update(type)
+ .update("\n")
+ .update(sessionId)
+ .update("\n")
+ .update(stableStringify(payload))
+ .digest("hex");
+}
+
+function pendingFilename(dedupKey, retries = 0) {
+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;
+}
+
+function retryFilename(filename, retries) {
+ const bare = filename.replace(/\.(json|processing)$/, "");
+ const nextBare = /_\d+$/.test(bare)
+ ? bare.replace(/_\d+$/, `_${retries}`)
+ : `${bare}_${retries}`;
+ return `${nextBare}.json`;
+}
+
+function processingFilename(filename) {
+ return filename.replace(/\.json$/, ".processing");
+}
+
+function pendingFromProcessingFilename(filename) {
+ return filename.replace(/\.processing$/, ".json");
+}
+
+function isRetryableReplayFailure(res) {
+ return isRetryableFailure(res);
+}
+
+async function readEntry(dir, filename) {
+ const raw = await readFile(join(dir, filename), "utf-8");
+ return JSON.parse(raw);
+}
+
+async function findExistingByDedupKey(dir, dedupKey) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return null;
+ }
+
+ // Fast path: filenames are `${dedupKey}_${retries}.json` (or
+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey
+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.
+ // Filter on prefix BEFORE opening the file to avoid readFile +
+ // JSON.parse on every entry in the directory on every enqueue call —
+ // the previous implementation was O(n²) in queue size. Worst case here
+ // is O(n) readdir entries, but only the (typically single) prefix
+ // match actually gets opened and parsed.
+ const prefix = `${dedupKey}_`;
+
+ for (const f of files) {
+ if (!f.startsWith(prefix)) continue;
+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };
+ } catch {
+ // Corrupted file - ignore for dedup lookup.
+ }
+ }
+ return null;
+}
+
+async function recoverStaleProcessing(dir) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return 0;
+ }
+
+ const now = Date.now();
+ let recovered = 0;
+ for (const f of files) {
+ if (!f.endsWith(".processing")) continue;
+ const from = join(dir, f);
+ try {
+ const s = await stat(from);
+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;
+ const to = join(dir, pendingFromProcessingFilename(f));
+ await rename(from, to);
+ recovered++;
+ } catch {
+ // Best effort. A concurrent process may have already handled it.
+ }
+ }
+ return recovered;
+}
+
+/**
+ * Enqueue a failed operation to local disk.
+ *
+ * @param {string} type - "addMessage" or "commitSession"
+ * @param {string} sessionId - OV session ID
+ * @param {object} payload - the data that failed to send
+ * @param {object} options
+ * @param {number} options.createdAt - optional queue timestamp override
+ */
+export async function enqueue(type, sessionId, payload, options = {}) {
+ const dir = getPendingDir();
+ const now = Number.isFinite(options.createdAt) ? options.createdAt : Date.now();
+ const dedupKey = makeDedupKey(type, sessionId, payload);
+ const filename = pendingFilename(dedupKey, 0);
+ const entry = {
+ type,
+ sessionId,
+ payload,
+ createdAt: now,
+ retries: 0,
+ dedupKey,
+ };
+
+ try {
+ await ensurePendingDir(dir);
+ } catch (err) {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+
+ const existing = await findExistingByDedupKey(dir, dedupKey);
+ if (existing) {
+ return { ok: true, path: existing.filename, deduped: true, dedupKey };
+ }
+
+ try {
+ await writeFile(join(dir, filename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ return { ok: true, path: filename, dedupKey };
+ } catch (err) {
+ if (err?.code !== "EEXIST") {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+ }
+
+ const duplicate = await findExistingByDedupKey(dir, dedupKey);
+ if (duplicate) {
+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };
+ }
+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };
+}
+
+/**
+ * List all pending queue entries.
+ * Returns array of { filename, entry } sorted by createdAt ascending.
+ */
+export async function listPending() {
+ const dir = getPendingDir();
+ let files;
+ try {
+ await recoverStaleProcessing(dir);
+ files = await readdir(dir);
+ } catch {
+ return [];
+ }
+
+ const entries = [];
+ for (const f of files) {
+ if (!f.endsWith(".json")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ entries.push({ filename: f, entry });
+ } catch {
+ // Corrupted file - skip.
+ }
+ }
+
+ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));
+ return entries;
+}
+
+/**
+ * Atomically claim a pending file for replay. Only the process that successfully
+ * renames the file may send the HTTP replay.
+ */
+export async function claimForReplay(filename) {
+ if (!filename.endsWith(".json")) return null;
+ const dir = getPendingDir();
+ const claimed = processingFilename(filename);
+ try {
+ await rename(join(dir, filename), join(dir, claimed));
+ return claimed;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Remove a pending entry after successful replay.
+ */
+export async function dequeue(filename) {
+ const dir = getPendingDir();
+ try {
+ await unlink(join(dir, filename));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Increment retry count on a pending entry. Returns false if max retries exceeded.
+ */
+export async function incrementRetry(filename, entry) {
+ const dir = getPendingDir();
+ const maxRetries = getMaxRetries();
+ entry.retries = (entry.retries || 0) + 1;
+
+ if (entry.retries > maxRetries) {
+ try {
+ await unlink(join(dir, filename));
+ } catch {
+ // Best effort.
+ }
+ return false;
+ }
+
+ const newFilename = retryFilename(filename, entry.retries);
+ // Atomic write: write to a unique temp file in the same directory, then
+ // rename into place. Avoids leaving a half-written JSON if the process
+ // crashes mid-write.
+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ await rename(join(dir, tmpFilename), join(dir, newFilename));
+ await unlink(join(dir, filename)).catch(() => {});
+ return true;
+ } catch {
+ await unlink(join(dir, tmpFilename)).catch(() => {});
+ return false;
+ }
+}
+
+/**
+ * Clean up stale entries older than TTL.
+ */
+export async function cleanStale() {
+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;
+ const now = Date.now();
+ const pending = await listPending();
+ let cleaned = 0;
+
+ for (const { filename, entry } of pending) {
+ const age = now - (entry.createdAt || 0);
+ if (age > ttlMs) {
+ await dequeue(filename);
+ cleaned++;
+ }
+ }
+ return cleaned;
+}
+
+/**
+ * Replay pending entries. Call this during session-start when the server is
+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so
+ * a just-recovered server is not hit with an unbounded replay burst.
+ *
+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON
+ * @param {Function} log - logger function
+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
+ */
+export async function replayPending(fetchJSON, log) {
+ const pending = await listPending();
+
+ if (pending.length === 0) {
+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };
+ }
+
+ const replayLimit = getReplayLimit();
+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });
+
+ let replayed = 0;
+ let failed = 0;
+ let skipped = 0;
+ let deferred = 0;
+ let processed = 0;
+
+ for (const { filename, entry } of pending) {
+ if (processed >= replayLimit) {
+ deferred++;
+ continue;
+ }
+
+ if ((entry.retries || 0) >= getMaxRetries()) {
+ await dequeue(filename);
+ skipped++;
+ continue;
+ }
+
+ const claimedFilename = await claimForReplay(filename);
+ if (!claimedFilename) {
+ skipped++;
+ continue;
+ }
+ processed++;
+
+ let res;
+ try {
+ const encodedSid = encodeURIComponent(entry.sessionId);
+ if (entry.type === "addMessage") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {
+ method: "POST",
+ body: JSON.stringify(entry.payload),
+ });
+ } else if (entry.type === "commitSession") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {
+ method: "POST",
+ body: JSON.stringify(entry.payload || {}),
+ });
+ } else {
+ await dequeue(claimedFilename);
+ skipped++;
+ continue;
+ }
+ } catch {
+ res = { ok: false };
+ }
+
+ if (entry.type === "commitSession") {
+ log("pending-queue", {
+ action: "commit-replay",
+ sessionId: entry.sessionId,
+ ok: Boolean(res?.ok),
+ status: res?.result?.status || res?.status,
+ trace_id: res?.traceId || res?.result?.trace_id,
+ error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
+ });
+ }
+
+ if (res?.ok) {
+ await dequeue(claimedFilename);
+ replayed++;
+ } else if (!isRetryableReplayFailure(res)) {
+ await dequeue(claimedFilename);
+ skipped++;
+ } else {
+ await incrementRetry(claimedFilename, entry);
+ failed++;
+ if (entry.type === "addMessage") {
+ deferred += Math.max(0, pending.length - processed);
+ break;
+ }
+ }
+ }
+
+ const cleaned = await cleanStale();
+
+ log("pending-queue", {
+ action: "replay-done",
+ replayed,
+ failed,
+ skipped,
+ deferred,
+ cleaned,
+ });
+
+ return { replayed, failed, skipped, deferred };
+}
diff --git a/examples/dsh-memory-plugin/shared/plugin-config.mjs b/examples/dsh-memory-plugin/shared/plugin-config.mjs
new file mode 100644
index 000000000..9f68d58bd
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/plugin-config.mjs
@@ -0,0 +1,90 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Per-harness plugin settings from ovcli.conf.
+ *
+ * ovcli.conf carried connection fields only, so every harness had to keep its
+ * tuning knobs in ov.conf's harness section — a server-side file that a
+ * client-side plugin has no business editing. The `plugin` section fixes that:
+ * shared keys apply to every harness that reads them, and a per-harness object
+ * overrides them.
+ *
+ * {
+ * "url": "...", "api_key": "...",
+ * "plugin": {
+ * "recallQueryExpansion": "off",
+ * "recallCompress": "auto"
+ * }
+ * }
+ *
+ * Resolution stays env → ovcli.conf plugin.<harness> → ovcli.conf plugin →
+ * ov.conf harness section (legacy) → defaults.
+ *
+ * Consumers: Claude Code and Codex only. The other harnesses ship this module
+ * through `sync.mjs` but still read their knobs from the environment, so a
+ * `plugin` entry named after them is inert. `HARNESS_KEYS` lists what a harness
+ * loader actually consumes today — add a key here as its loader starts calling
+ * `loadPluginSettings`, not before, so the section never promises a knob that
+ * silently does nothing.
+ */
+
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+
+const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
+
+export const HARNESS_KEYS = {
+ claudeCode: "claude_code",
+ codex: "codex",
+};
+
+function tryLoadJson(path) {
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Merge the shared plugin section with the harness-specific override.
+ * Returns a flat settings object; unknown keys pass through untouched so a
+ * harness can add its own knobs without touching this module.
+ */
+export function loadPluginSettings(harness, env = process.env) {
+ const path = resolvePath(
+ (env.OPENVIKING_CLI_CONFIG_FILE || DEFAULT_OVCLI_CONF_PATH).replace(/^~/, homedir()),
+ );
+ const file = tryLoadJson(path);
+ const plugin = file && typeof file.plugin === "object" && file.plugin ? file.plugin : {};
+
+ const shared = {};
+ for (const [key, value] of Object.entries(plugin)) {
+ if (value && typeof value === "object" && !Array.isArray(value)) continue;
+ shared[key] = value;
+ }
+ const scoped = harness && plugin[harness] && typeof plugin[harness] === "object"
+ ? plugin[harness]
+ : {};
+
+ return { ...shared, ...scoped };
+}
+
+const REWRITE_MODES = new Set(["off", "client", "server", "auto"]);
+
+/**
+ * Normalize the tri-state rewrite knob.
+ *
+ * off — never compress
+ * client — always compress locally through the host CLI
+ * server — always ask the server for a digest
+ * auto — prefer local (cost lands on the user's own subscription), fall back
+ * to the server when no healthy host CLI is available
+ */
+export function normalizeRewriteMode(value, fallback = "off") {
+ const raw = String(value ?? "").trim().toLowerCase();
+ if (REWRITE_MODES.has(raw)) return raw;
+ if (raw === "1" || raw === "true" || raw === "yes") return "auto";
+ if (raw === "0" || raw === "false" || raw === "no") return "off";
+ return fallback;
+}
diff --git a/examples/dsh-memory-plugin/shared/profile-inject.mjs b/examples/dsh-memory-plugin/shared/profile-inject.mjs
new file mode 100644
index 000000000..3f601844a
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/profile-inject.mjs
@@ -0,0 +1,294 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Session-start profile injection helper.
+ *
+ * Builds a <user-profile> + <available-memories> block from
+ * viking://user/<space>/memories/profile.md
+ * viking://user/<space>/memories/preferences/ (ls with abstracts)
+ * viking://user/<space>/memories/entities/ (ls with abstracts)
+ *
+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=
+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so
+ * callers (e.g. session-start.mjs) can log token counts that match what
+ * the budget logic actually sees.
+ *
+ * Returned block is the *inner* content only (no outer <openviking-context>);
+ * session-start.mjs composes the outer wrapper so the archive block can sit
+ * alongside in a single context envelope.
+ */
+
+const USER_RESERVED_DIRS = new Set(["memories"]);
+let _userSpaceCache = null;
+
+/**
+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).
+ * Duplicated rather than imported to avoid coupling session-start to
+ * auto-recall's module-level fetchJSON closure.
+ */
+async function resolveUserSpace(fetchJSON, actorPeerId = "") {
+ if (_userSpaceCache) return _userSpaceCache;
+
+ let fallbackSpace = "default";
+ const status = await fetchJSON("/api/v1/system/status");
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
+ fallbackSpace = status.result.user.trim();
+ }
+
+ const lsRes = await fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
+ const spaces = lsRes.result
+ .filter((e) => e?.isDir)
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
+ if (spaces.length > 0) {
+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }
+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }
+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }
+ }
+ }
+ _userSpaceCache = fallbackSpace;
+ return fallbackSpace;
+}
+
+/**
+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a
+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and
+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.
+ *
+ * Rule:
+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK
+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical
+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same
+ * ballpark).
+ * - everything else → chars/4 (the standard English-ish heuristic).
+ *
+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK
+ * by ~10-20% in the worst case (some common Chinese phrases compress better
+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.
+ */
+export function estimateTokens(text) {
+ if (!text) return 0;
+ let cjk = 0;
+ for (let i = 0; i < text.length; i++) {
+ if (text.charCodeAt(i) >= 0x3000) cjk++;
+ }
+ const other = text.length - cjk;
+ return Math.ceil(cjk * 1.5 + other / 4);
+}
+
+/**
+ * Convert a token budget to a max-chars budget that respects this content's
+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap
+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).
+ *
+ * For an empty/missing string, returns 0.
+ */
+function tokensToCharsBudget(content, maxTokens) {
+ if (!content) return 0;
+ let cjk = 0;
+ for (let i = 0; i < content.length; i++) {
+ if (content.charCodeAt(i) >= 0x3000) cjk++;
+ }
+ const ratio = cjk / content.length;
+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;
+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));
+}
+
+async function readProfile(fetchJSON, profileUri, actorPeerId = "") {
+ const res = await fetchJSON(
+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,
+ {},
+ { actorPeerId },
+ );
+ if (!res.ok || typeof res.result !== "string") return null;
+ const trimmed = res.result.trim();
+ return trimmed || null;
+}
+
+/**
+ * Recursive ls of a memory directory, flattening to .md leaves.
+ *
+ * Memory layout under preferences/ and entities/ is two-level:
+ * <dir>/<owner_name>/<topic>.md
+ * so we use the server's recursive=true flag and filter to leaf .md files.
+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name
+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.
+ */
+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {
+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;
+ const res = await fetchJSON(url, {}, { actorPeerId });
+ if (!res.ok || !Array.isArray(res.result)) return [];
+ return res.result
+ .filter((e) => !e.isDir)
+ .map((e) => {
+ const rel = typeof e.rel_path === "string" && e.rel_path
+ ? e.rel_path
+ : (typeof e.name === "string" ? e.name : "");
+ return {
+ name: rel,
+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",
+ };
+ })
+ .filter((e) => e.name && e.name.endsWith(".md"))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/**
+ * When profile exceeds its sub-cap, keep the head (identity block + first
+ * timeline events) and the tail (most-recent events), drop the middle. This
+ * preserves both stable identity facts (top of file) and most-recent activity
+ * (bottom of file) — only the noisy middle timeline is sacrificed.
+ *
+ * Layout:
+ * <first HEAD_LINES lines>
+ * ... [profile middle elided] ...
+ * <as many trailing lines as fit in remaining budget>
+ *
+ * Falls back to head-only truncate when the file is too short to elide
+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit
+ * both head and a useful tail.
+ */
+function elideProfile(content, maxTokens) {
+ // Compute char budget from token budget using *this* content's CJK density,
+ // not chars/4 — otherwise the truncated string can still blow the token cap
+ // for CJK-heavy profiles (Copilot review point).
+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));
+ if (estimateTokens(content) <= maxTokens) return content;
+
+ const HEAD_LINES = 8;
+ const ELLIPSIS = "\n... [profile middle elided] ...\n";
+ const lines = content.split("\n");
+
+ const fallbackHeadTruncate = () =>
+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";
+
+ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();
+
+ const head = lines.slice(0, HEAD_LINES).join("\n");
+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;
+ if (reserveForTail < 200) return fallbackHeadTruncate();
+
+ let tailChars = 0;
+ let tailStart = lines.length;
+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {
+ const lineLen = lines[i].length + 1;
+ if (tailChars + lineLen > reserveForTail) break;
+ tailChars += lineLen;
+ tailStart = i;
+ }
+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();
+
+ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;
+}
+
+function formatListing(headerUri, entries, budgetTokens) {
+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };
+ // Header is the full directory URI; child lines are relative paths so the
+ // agent can reconstruct each leaf's full URI by concatenation while the
+ // listing itself stays compact.
+ const header = ` ${headerUri}/`;
+ const headerTokens = estimateTokens(header);
+ // If the header alone busts the budget, emit just a one-line stub instead
+ // of silently violating the cap (Copilot review point).
+ if (headerTokens > budgetTokens) {
+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;
+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };
+ }
+ const lines = [header];
+ let used = headerTokens;
+ for (let i = 0; i < entries.length; i++) {
+ const e = entries[i];
+ const desc = e.abstract
+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`
+ : "";
+ const line = ` - ${e.name}${desc}`;
+ const tokens = estimateTokens(line);
+ if (used + tokens > budgetTokens) {
+ const remaining = entries.length - i;
+ const tail = ` ... +${remaining} more, use \`memory_recall\``;
+ const tailTokens = estimateTokens(tail);
+ // Only emit the tail if it fits; otherwise the listing closes silently
+ // rather than violating the cap to advertise its own truncation.
+ if (used + tailTokens <= budgetTokens) {
+ lines.push(tail);
+ return { lines, used: used + tailTokens, dropped: remaining };
+ }
+ return { lines, used, dropped: remaining };
+ }
+ lines.push(line);
+ used += tokens;
+ }
+ return { lines, used, dropped: 0 };
+}
+
+/**
+ * Build the profile injection block.
+ *
+ * Returns null when neither profile.md nor either listing has any content.
+ * The returned `block` is just the inner <user-profile>/<available-memories>
+ * payload — the caller wraps it in <openviking-context source="...">.
+ *
+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure
+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block
+ * @returns {Promise<null | {
+ * block: string, chars: number, tokens: number, profileUri: string,
+ * profileChars: number, prefCount: number, entCount: number,
+ * droppedPref: number, droppedEnt: number,
+ * }>}
+ */
+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
+ const profileUri = `viking://user/${space}/memories/profile.md`;
+ const prefUri = `viking://user/${space}/memories/preferences`;
+ const entUri = `viking://user/${space}/memories/entities`;
+
+ const [profile, prefs, ents] = await Promise.all([
+ readProfile(fetchJSON, profileUri, actorPeerId),
+ lsDir(fetchJSON, prefUri, actorPeerId),
+ lsDir(fetchJSON, entUri, actorPeerId),
+ ]);
+
+ if (!profile && prefs.length === 0 && ents.length === 0) return null;
+
+ // Profile gets up to half the total budget; listings split the rest.
+ // Sub-cap protects against a runaway profile blowing the listing budget.
+ const profileBudget = Math.floor(totalBudgetTokens / 2);
+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;
+ const profileTokens = estimateTokens(profileTrunc || "");
+
+ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);
+ const halfListing = Math.floor(listingBudget / 2);
+ const prefBlock = formatListing(prefUri, prefs, halfListing);
+ const entBudget = Math.max(0, listingBudget - prefBlock.used);
+ const entBlock = formatListing(entUri, ents, entBudget);
+
+ const lines = [];
+ if (profileTrunc) {
+ lines.push(`<user-profile uri="${profileUri}">`);
+ lines.push(profileTrunc);
+ lines.push(`</user-profile>`);
+ }
+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {
+ lines.push(`<available-memories>`);
+ lines.push(...prefBlock.lines);
+ lines.push(...entBlock.lines);
+ lines.push(`</available-memories>`);
+ }
+
+ const block = lines.join("\n");
+ return {
+ block,
+ chars: block.length,
+ tokens: estimateTokens(block),
+ profileUri,
+ profileChars: profile?.length ?? 0,
+ prefCount: prefs.length,
+ entCount: ents.length,
+ droppedPref: prefBlock.dropped,
+ droppedEnt: entBlock.dropped,
+ };
+}
diff --git a/examples/dsh-memory-plugin/shared/recall-compress-core.mjs b/examples/dsh-memory-plugin/shared/recall-compress-core.mjs
new file mode 100644
index 000000000..6f8fe485b
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/recall-compress-core.mjs
@@ -0,0 +1,195 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+
+export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
+export const DIGEST_HEADER = "OpenViking memory digest:";
+const COMPRESS_OK = "ok";
+const COMPRESS_EMPTY = "empty";
+const COMPRESS_FAILED = "failed";
+
+// Medium-constraint prompt: state the goal and two structural floors, but no hard
+// bullet-length contract. Hard per-bullet limits pin the digest to headline
+// density; leaving it unconstrained lets small models rewrite long URIs into dead
+// links, which the URI repair below cleans up.
+export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
+ return `You are a memory relevance compressor utility.
+Do not use any tools. Do not investigate. Only transform the given text.
+
+User query:
+${query}
+
+Retrieved OpenViking context fragments:
+${rendered}
+
+Write a memory digest for a coding agent about to answer that query. Keep the
+concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
+and conversational filler.
+
+Format rules:
+- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
+- Start every bullet with "- ".
+- End every bullet with its source, copied verbatim from the fragments above:
+ "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
+- Output the digest body only. No preamble, no closing remark.
+
+If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
+}
+
+function editDistance(a, b) {
+ if (a === b) return 0;
+ const rows = a.length + 1;
+ const cols = b.length + 1;
+ let prev = Array.from({ length: cols }, (_, i) => i);
+ for (let i = 1; i < rows; i += 1) {
+ const cur = [i];
+ for (let j = 1; j < cols; j += 1) {
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
+ cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
+ }
+ prev = cur;
+ }
+ return prev[cols - 1];
+}
+
+function nearestUri(candidate, validUris) {
+ let best = "";
+ let bestDistance = Infinity;
+ for (const uri of validUris) {
+ const distance = editDistance(candidate, uri);
+ if (distance < bestDistance) {
+ best = uri;
+ bestDistance = distance;
+ }
+ }
+ // Only repair near-misses; an unrelated hallucination is dropped instead.
+ const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
+ return bestDistance <= tolerance ? best : "";
+}
+
+/**
+ * Small models occasionally mangle long URIs. Snap every cited URI back onto the
+ * set the server actually returned, and drop bullets whose citation cannot be
+ * recovered so the digest never carries a dead link.
+ */
+export function repairDigestUris(digest, validUris = []) {
+ const text = String(digest || "");
+ if (!text) return "";
+ const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
+ if (!valid.length) return text;
+ const validSet = new Set(valid);
+
+ const lines = [];
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim().startsWith("- ")) {
+ lines.push(line);
+ continue;
+ }
+ let dropped = false;
+ const repaired = line.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
+ if (validSet.has(uri)) return uri;
+ const nearest = nearestUri(uri, valid);
+ if (nearest) return nearest;
+ dropped = true;
+ return uri;
+ });
+ if (!dropped) lines.push(repaired);
+ }
+ return lines.join("\n").trim();
+}
+
+export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
+ const text = String(raw || "").trim();
+ if (!text) return null;
+ if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
+ const bullets = text.split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
+ .slice(0, Math.max(1, maxBullets))
+ .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
+ if (!bullets.length) return null;
+ return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
+}
+
+export function recallDigestCacheKey({
+ query = "",
+ rendered = "",
+ entries = [],
+ maxInputChars = 18000,
+ maxBullets = 6,
+} = {}) {
+ const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
+ const source = JSON.stringify({
+ version: 2,
+ query: String(query),
+ rendered: String(rendered).slice(0, maxInputChars),
+ uris,
+ maxInputChars,
+ maxBullets,
+ });
+ return createHash("sha256").update(source).digest("hex");
+}
+
+async function readCache(path) {
+ if (!path) return null;
+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
+}
+
+async function writeCache(path, value) {
+ if (!path) return;
+ try {
+ await mkdir(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp`;
+ await writeFile(tmp, JSON.stringify(value));
+ await rename(tmp, path);
+ } catch { /* best effort */ }
+}
+
+export async function compressRecallContext({
+ query,
+ rendered,
+ entries = [],
+ cfg = {},
+ runCompressor,
+ cachePath = "",
+ now = 0,
+}) {
+ const input = String(rendered || "").trim();
+ if (!input) return { status: COMPRESS_EMPTY, context: "" };
+ const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
+ if (input.length < minChars) return { status: COMPRESS_OK, context: input };
+
+ const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
+ const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
+ const key = recallDigestCacheKey({
+ query,
+ rendered: input,
+ entries,
+ maxInputChars,
+ maxBullets,
+ });
+ const cached = await readCache(cachePath);
+ if (cached?.key === key && typeof cached.digest === "string") {
+ return { status: COMPRESS_OK, context: cached.digest };
+ }
+
+ const prompt = buildRecallCompressionPrompt({
+ query,
+ rendered: input.slice(0, maxInputChars),
+ maxBullets,
+ });
+ const raw = await runCompressor(prompt);
+ const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
+ if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
+ if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
+
+ const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
+ const digest = repairDigestUris(normalized, validUris.length
+ ? validUris
+ : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
+ if (!digest) return { status: COMPRESS_FAILED, context: "" };
+
+ await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
+ return { status: COMPRESS_OK, context: digest };
+}
diff --git a/examples/dsh-memory-plugin/shared/recall-core.mjs b/examples/dsh-memory-plugin/shared/recall-core.mjs
new file mode 100644
index 000000000..a6e94eef5
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/recall-core.mjs
@@ -0,0 +1,609 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { compressRecallContext } from "./recall-compress-core.mjs";
+
+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;
+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;
+const STOPWORDS = new Set([
+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",
+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",
+]);
+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
+const SOURCES = [
+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+];
+const DEFAULT_CONTEXT_LIMIT = 10;
+const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
+const DEFAULT_REWRITE_MAX_BULLETS = 6;
+const CODING_QUOTA_WEIGHTS = {
+ events: 1,
+ entities: 2,
+ preferences: 1,
+ experiences: 1,
+ resources: 3,
+ skills: 2,
+};
+
+let userSpaceCache = "";
+
+export function estimateTokens(text) {
+ return text ? Math.ceil(String(text).length / 4) : 0;
+}
+
+function scaleQuotas(limit, weights) {
+ const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
+ const order = Object.keys(weights);
+ const quotas = Object.fromEntries(order.map((key) => [key, 0]));
+ if (slots < order.length) {
+ for (const key of order) quotas[key] = 1;
+ return quotas;
+ }
+
+ for (const key of order) quotas[key] = 1;
+ const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
+ const ideals = Object.fromEntries(
+ order.map((key) => [key, slots * weights[key] / totalWeight]),
+ );
+ while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
+ const key = order.reduce((best, candidate) => (
+ ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
+ ? candidate
+ : best
+ ));
+ quotas[key] += 1;
+ }
+ return quotas;
+}
+
+function legacyMemoryQuotas(limit) {
+ return {
+ ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
+ experiences: 0,
+ };
+}
+
+function codingQuotas(limit) {
+ return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
+}
+
+export function buildRecallEndpointBody(cfg = {}) {
+ const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
+ const body = {
+ query: "",
+ quotas: legacyMemoryQuotas(limit),
+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),
+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
+ render: true,
+ };
+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
+ return body;
+}
+
+/**
+ * Body for the server-side context face. The plugin declares intent (coding
+ * purpose, budget, session) and leaves the mechanics — quota ratios, tier
+ * degradation, cross-turn dedup — to the server's defaults.
+ */
+export function buildContextSearchBody(cfg = {}, options = {}) {
+ const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
+ const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
+ const maxTokens = Math.max(
+ 64,
+ Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
+ );
+ const body = {
+ query: "",
+ mode: "context",
+ purpose: "coding",
+ score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
+ };
+ const limitConfigured = cfg.recallLimitConfigured === true;
+ const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
+ if (limitConfigured) body.quotas = codingQuotas(limit);
+ if (maxTokensConfigured) body.max_tokens = maxTokens;
+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
+
+ const sessionId = String(options.sessionId || "").trim();
+ if (sessionId) {
+ body.session_id = sessionId;
+ const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
+ if (queryExpansionConfigured) {
+ body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
+ }
+ const dedupTurns = Number(cfg.recallDedupTurns);
+ const resolvedDedupTurns = Number.isFinite(dedupTurns)
+ ? Math.max(0, Math.floor(dedupTurns))
+ : 5;
+ if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
+ }
+
+ const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
+ if (excludeUris.length) body.exclude_uris = excludeUris;
+
+ if (rewriteMode === "server") body.rewrite = true;
+ else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
+ const rewriteMaxBullets = Math.max(
+ 1,
+ Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
+ );
+ const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
+ if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
+ body.rewrite_max_bullets = rewriteMaxBullets;
+ }
+ return body;
+}
+
+// The server pipeline is serial and each optional stage has its own fuse. A
+// request is aborted client-side unless its deadline covers every stage it
+// asked for, and aborting discards the whole response rather than just the
+// stage that ran long.
+//
+// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
+// always -> retrieval, body reads, budget planning
+// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
+//
+// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
+// a quarter to spare.
+const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
+const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
+
+/**
+ * HTTP deadline for one context request, or undefined to keep the caller's own.
+ *
+ * Derived from the request body, because the body is what states which server
+ * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
+ * that also spends the expansion or rewrite fuse.
+ */
+export function contextRequestTimeoutMs(cfg = {}, body = {}) {
+ const wantsRewrite = body.rewrite !== undefined;
+ // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
+ // takes the expansion fuse back out of the budget.
+ const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
+ if (!wantsRewrite && !wantsExpansion) return undefined;
+
+ const configured = Number(cfg.recallContextTimeoutMs);
+ if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
+ const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
+ return Math.max(Number(cfg.timeoutMs) || 0, floor);
+}
+
+/**
+ * Strip the context-face fields a pre-context server rejects, converting the
+ * token budget back to v1's character budget.
+ */
+export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
+ const body = buildRecallEndpointBody(cfg);
+ body.query = contextBody.query || "";
+ body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
+ if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
+ return body;
+}
+
+function clampScore(v) {
+ if (typeof v !== "number" || Number.isNaN(v)) return 0;
+ return Math.max(0, Math.min(1, v));
+}
+
+function buildQueryProfile(query) {
+ const text = query.trim();
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
+ return {
+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
+ };
+}
+
+function lexicalOverlapBoost(tokens, text) {
+ if (tokens.length === 0 || !text) return 0;
+ const haystack = ` ${text.toLowerCase()} `;
+ let matched = 0;
+ for (const token of tokens.slice(0, 8)) {
+ if (haystack.includes(token)) matched += 1;
+ }
+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
+}
+
+function rankItem(item, profile) {
+ const base = clampScore(item.score);
+ const abstract = (item.abstract || item.overview || "").trim();
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;
+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;
+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;
+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);
+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;
+}
+
+function isEventOrCaseItem(item) {
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");
+}
+
+function dedupeItems(items) {
+ const seen = new Set();
+ const out = [];
+ for (const item of items) {
+ const key = isEventOrCaseItem(item)
+ ? `uri:${item.uri}`
+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(item);
+ }
+ return out;
+}
+
+async function resolveUserSpace(fetchJSON, actorPeerId = "") {
+ if (userSpaceCache) return userSpaceCache;
+
+ let fallbackSpace = "default";
+ const status = await fetchJSON("/api/v1/system/status");
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
+ fallbackSpace = status.result.user.trim();
+ }
+
+ const lsRes = await fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
+ const spaces = lsRes.result
+ .filter((e) => e?.isDir)
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
+ if (spaces.length > 0) {
+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }
+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }
+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }
+ }
+ }
+ userSpaceCache = fallbackSpace;
+ return fallbackSpace;
+}
+
+async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
+ const trimmed = targetUri.trim().replace(/\/+$/, "");
+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
+ if (!m) return trimmed;
+ const rawRest = (m[1] ?? "").trim();
+ if (!rawRest) return trimmed;
+ const parts = rawRest.split("/").filter(Boolean);
+ if (parts.length === 0) return trimmed;
+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
+ return `viking://user/${space}/${parts.join("/")}`;
+}
+
+async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {
+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);
+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };
+ const res = await fetchJSON("/api/v1/search/find", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId });
+ if (!res.ok) return [];
+ const items = res.result?.[source.bucket] || [];
+ return items.map((item) => ({ ...item, _sourceType: source.type }));
+}
+
+async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {
+ const results = await Promise.all(
+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),
+ );
+ const all = results.flat();
+ log("recall_search_summary", {
+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),
+ total: all.length,
+ });
+ return all;
+}
+
+async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
+ let content;
+
+ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {
+ content = (item.abstract || item.overview).trim();
+ } else if (item.level === 2) {
+ try {
+ const res = await fetchJSON(
+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,
+ {},
+ { actorPeerId },
+ );
+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";
+ content = body || (item.abstract || item.overview || "").trim() || item.uri;
+ } catch {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+ } else {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+
+ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));
+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;
+ return content;
+}
+
+async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
+ if (items.length === 0) return null;
+
+ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const lines = [
+ "<openviking-context>",
+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
+ ];
+ let contentCount = 0;
+ let hintCount = 0;
+
+ for (const item of items) {
+ const score = (clampScore(item.score) * 100).toFixed(0);
+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;
+
+ if (budgetRemaining > 0) {
+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);
+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;
+ const lineTokens = estimateTokens(contentLine);
+
+ if (lineTokens > budgetRemaining && contentCount > 0) {
+ lines.push(uriLine);
+ hintCount++;
+ } else {
+ lines.push(contentLine);
+ budgetRemaining -= lineTokens;
+ contentCount++;
+ }
+ } else {
+ lines.push(uriLine);
+ hintCount++;
+ }
+ }
+
+ lines.push("</openviking-context>");
+
+ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ log("recall_injection_built", {
+ contentItems: contentCount,
+ hintItems: hintCount,
+ budgetUsed,
+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ });
+
+ return lines.join("\n");
+}
+
+const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
+
+function stateFile(name) {
+ const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
+ return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
+}
+
+async function readJsonFile(path) {
+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
+}
+
+async function writeJsonFile(path, value) {
+ try {
+ await mkdir(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp`;
+ await writeFile(tmp, JSON.stringify(value));
+ await rename(tmp, path);
+ } catch { /* best effort */ }
+}
+
+/**
+ * Hooks are one-shot processes, so "this server has no context face" has to be
+ * remembered on disk or every turn pays for a rejected request.
+ */
+export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
+ const cached = await readJsonFile(path);
+ return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
+}
+
+export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
+ await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
+}
+
+function looksLikeUnknownField(res) {
+ const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
+ return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
+}
+
+function wrapContext(body) {
+ return [
+ "<openviking-context>",
+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",
+ body,
+ "</openviking-context>",
+ ].join("\n");
+}
+
+/**
+ * Server-assembled context: the context face when the deployment has it, else
+ * the deprecated /recall preset. Returns the injection block, "" when there was
+ * nothing relevant, or null when no server-side path was usable at all.
+ */
+export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
+ const log = options.log || (() => {});
+
+ const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
+ if (block !== null) return block;
+ return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
+}
+
+/**
+ * Raw server-assembled context, or null when the deployment has no context face.
+ * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
+ * (their own compression, their own envelope) use this instead of the block
+ * builders below.
+ */
+export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId || "";
+ const log = options.log || (() => {});
+ if (await isContextFaceLegacy(options.legacyCachePath)) return null;
+
+ const body = buildContextSearchBody(cfg, options);
+ body.query = query;
+ const res = await fetchJSON("/api/v1/search/search", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
+
+ if (!res.ok) {
+ const status = res.status || 0;
+ if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
+ await markContextFaceLegacy(options.legacyCachePath);
+ log("recall_context_face_unsupported", { status });
+ } else {
+ log("recall_context_face_error", { status });
+ }
+ return null;
+ }
+
+ const result = res.result || {};
+ const stats = result.stats || {};
+ log("recall_context_assembled", {
+ entries: Array.isArray(result.entries) ? result.entries.length : 0,
+ usedTokens: stats.used_tokens || 0,
+ tiers: stats.tier_counts || {},
+ rewrite: stats.rewrite || "off",
+ });
+ return {
+ rendered: String(result.rendered || "").trim(),
+ entries: Array.isArray(result.entries) ? result.entries : [],
+ digest: String(result.digest || "").trim(),
+ stats,
+ };
+}
+
+/**
+ * Entry field compatibility: the context face returns `category`/`text`, while
+ * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
+ */
+export function normalizeContextEntry(entry = {}) {
+ return {
+ uri: String(entry.uri || "").trim(),
+ category: String(entry.category || entry.type || "memory").trim() || "memory",
+ detail: String(entry.detail || entry.mode || "").trim(),
+ score: Number(entry.score) || 0,
+ text: String(
+ entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
+ ).trim(),
+ };
+}
+
+async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
+ const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
+ if (assembled === null) return null;
+
+ const { rendered, entries } = assembled;
+ let digest = assembled.digest;
+ const mode = String(cfg.recallRewrite || "off").toLowerCase();
+ if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
+ log("recall_server_compression", { status: "empty" });
+ return "";
+ }
+ const wantsLocal = mode === "client" || (mode === "auto" && !digest);
+ if (wantsLocal && rendered && typeof options.runCompressor === "function") {
+ try {
+ const compression = await compressRecallContext({
+ query,
+ rendered,
+ entries,
+ cfg,
+ runCompressor: options.runCompressor,
+ cachePath: options.digestCachePath || stateFile("recall-digest.json"),
+ now: Date.now(),
+ });
+ log("recall_local_compression", { status: compression.status });
+ if (compression.status === "ok") digest = compression.context;
+ if (compression.status === "empty") return "";
+ } catch (err) {
+ log("recall_local_compression_failed", { error: String(err?.message || err) });
+ }
+ }
+
+ const injected = digest || rendered;
+ if (!injected) return "";
+ return wrapContext(injected);
+}
+
+async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {
+ const body = buildRecallEndpointBody(cfg);
+ body.query = query;
+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });
+ if (!res.ok) {
+ log("recall_endpoint_fallback", { status: res.status || 0 });
+ return null;
+ }
+ const rendered = String(res.result?.rendered || "").trim();
+ if (!rendered) return "";
+ return wrapContext(rendered);
+}
+
+export async function postRecall(fetchJSON, body, opts = {}) {
+ const actorPeerId = opts.actorPeerId || "";
+ const log = opts.log || (() => {});
+ const request = { ...body };
+ const res = await fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(request),
+ }, { actorPeerId });
+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {
+ return res;
+ }
+
+ const downgraded = { ...request };
+ delete downgraded.peer_scope;
+ log("recall_peer_scope_downgrade", { status: res.status || 0 });
+ return fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(downgraded),
+ }, { actorPeerId });
+}
+
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
+ const log = options.log || (() => {});
+ const trimmed = String(query || "").trim();
+ if (!trimmed) return null;
+
+ // Assembly happens server-side when the deployment offers the context face;
+ // older servers fall through to /recall, then to raw find.
+ const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
+ ...options,
+ actorPeerId,
+ log,
+ });
+ if (serverBlock !== null) return serverBlock || null;
+
+ const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
+ const perSourceLimit = Math.max(recallLimit * 2, 8);
+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
+ if (raw.length === 0) return null;
+
+ const profile = buildQueryProfile(trimmed);
+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);
+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));
+ const picked = dedupeItems(filtered).slice(0, recallLimit);
+ log("recall_picked", {
+ rawCount: raw.length,
+ filteredCount: filtered.length,
+ pickedCount: picked.length,
+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
+ });
+
+ if (picked.length === 0) return null;
+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
+}
diff --git a/examples/dsh-memory-plugin/shared/retryable.mjs b/examples/dsh-memory-plugin/shared/retryable.mjs
new file mode 100644
index 000000000..8be4b14e8
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/retryable.mjs
@@ -0,0 +1,9 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+export function isRetryableFailure(result) {
+ if (!result || result.ok) return false;
+ const status = Number(result.status || 0);
+ if (!status || status === 408 || status === 429 || status >= 500) {
+ return true;
+ }
+ return status === 409 && result.error?.details?.retryable === true;
+}
diff --git a/examples/dsh-memory-plugin/shared/session-model.mjs b/examples/dsh-memory-plugin/shared/session-model.mjs
new file mode 100644
index 000000000..b6496a113
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/session-model.mjs
@@ -0,0 +1,57 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared OpenViking session-id helpers for memory plugin harnesses.
+ */
+
+/**
+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.
+ */
+function globToRe(glob) {
+ let re = "^";
+ for (let i = 0; i < glob.length; i++) {
+ const c = glob[i];
+ if (c === "*") {
+ if (glob[i + 1] === "*") { re += ".*"; i++; }
+ else re += "[^/]*";
+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {
+ re += "\\" + c;
+ } else {
+ re += c;
+ }
+ }
+ re += "$";
+ return new RegExp(re);
+}
+
+export function isBypassed(cfg, { sessionId, cwd } = {}) {
+ if (cfg.bypassSession) return true;
+ const patterns = cfg.bypassSessionPatterns || [];
+ if (patterns.length === 0) return false;
+ const haystacks = [sessionId, cwd].filter(Boolean);
+ for (const pat of patterns) {
+ const re = globToRe(pat);
+ if (haystacks.some((h) => re.test(h))) return true;
+ }
+ return false;
+}
+
+function safeId(value, replacement = "_") {
+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);
+}
+
+export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {
+ if (!prefix || typeof prefix !== "string") {
+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");
+ }
+ if (!sessionId || typeof sessionId !== "string") {
+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");
+ }
+ const base = `${prefix}${sessionId}`;
+ if (!suffix) return base;
+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");
+ return `${base}__${normalized}`;
+}
+
+export function deriveCodexSessionId(codexSessionId) {
+ return `cx-${safeId(codexSessionId, "_")}`;
+}
diff --git a/examples/dsh-memory-plugin/shared/setup-wizard.mjs b/examples/dsh-memory-plugin/shared/setup-wizard.mjs
new file mode 100644
index 000000000..5108f5f2b
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/setup-wizard.mjs
@@ -0,0 +1,111 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.
+ *
+ * Lets a pure-marketplace install (no installer script) configure the server
+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:
+ *
+ * node <plugin>/scripts/setup.mjs
+ *
+ * Conventions: show current values, keep existing secrets on empty input,
+ * merge-write (never drop unknown fields), back up the previous file, 0600.
+ */
+
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
+import { dirname } from "node:path";
+import { createInterface } from "node:readline/promises";
+import { loadCredentialFiles } from "./credentials.mjs";
+
+const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";
+const LOCAL_URL = "http://127.0.0.1:1933";
+
+function maskSecret(value) {
+ const s = String(value || "");
+ if (!s) return "(not set)";
+ if (s.length <= 8) return "****";
+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;
+}
+
+function readJsonSafe(path) {
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return {};
+ }
+}
+
+export async function runSetupWizard({
+ input = process.stdin,
+ output = process.stdout,
+ env = process.env,
+} = {}) {
+ const { cliPath } = loadCredentialFiles(env);
+ const current = readJsonSafe(cliPath);
+ const rl = createInterface({ input, output });
+ const say = (line = "") => output.write(`${line}\n`);
+
+ try {
+ say("OpenViking memory plugin setup");
+ say(`Config file: ${cliPath}`);
+ say("");
+ say("Current values:");
+ say(` url: ${current.url || "(not set)"}`);
+ say(` api_key: ${maskSecret(current.api_key)}`);
+ if (current.account) say(` account: ${current.account}`);
+ if (current.user) say(` user: ${current.user}`);
+ say("");
+
+ const defaultUrl = current.url || LOCAL_URL;
+ say("Where do you connect to OpenViking?");
+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);
+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);
+ say(` 3) Custom URL / keep current [${defaultUrl}]`);
+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();
+ let url = defaultUrl;
+ if (mode === "1") {
+ url = LOCAL_URL;
+ } else if (mode === "2") {
+ url = CLOUD_URL;
+ } else {
+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();
+ if (answer) url = answer;
+ }
+
+ const keyPrompt = current.api_key
+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `
+ : "API key (leave empty for unauthenticated local mode): ";
+ const keyAnswer = await rl.question(keyPrompt);
+ let apiKey = current.api_key || "";
+ if (keyAnswer === "-") apiKey = "";
+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();
+ else if (!current.api_key) apiKey = "";
+
+ const next = { ...current, url, api_key: apiKey };
+
+ say("");
+ say("Changes:");
+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);
+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);
+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();
+ if (confirm === "n" || confirm === "no") {
+ say("Aborted; nothing written.");
+ return { written: false, path: cliPath };
+ }
+
+ mkdirSync(dirname(cliPath), { recursive: true });
+ if (existsSync(cliPath)) {
+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);
+ }
+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
+ try {
+ chmodSync(cliPath, 0o600);
+ } catch {
+ /* best effort on platforms without chmod semantics */
+ }
+ say(`Written: ${cliPath}`);
+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");
+ return { written: true, path: cliPath };
+ } finally {
+ rl.close();
+ }
+}
diff --git a/examples/dsh-memory-plugin/shared/uri-guard.mjs b/examples/dsh-memory-plugin/shared/uri-guard.mjs
new file mode 100644
index 000000000..9505ddb5e
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/uri-guard.mjs
@@ -0,0 +1,56 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+const DEFAULT_URI_KEYS = [
+ "filePath",
+ "file_path",
+ "filepath",
+ "path",
+ "uri",
+ "target_uri",
+ "targetUri",
+ "pattern",
+];
+
+export function normalizeToolName(value) {
+ return String(value || "").trim().toLowerCase();
+}
+
+export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {
+ if (!args || typeof args !== "object") return null;
+ for (const key of keys) {
+ const uri = findVikingUriInValue(args[key]);
+ if (uri) return uri;
+ }
+ return findVikingUriInValue(args);
+}
+
+export function findVikingUriInValue(value) {
+ if (typeof value === "string") {
+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);
+ return match?.[0] || null;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const uri = findVikingUriInValue(item);
+ if (uri) return uri;
+ }
+ return null;
+ }
+ if (value && typeof value === "object") {
+ for (const item of Object.values(value)) {
+ const uri = findVikingUriInValue(item);
+ if (uri) return uri;
+ }
+ }
+ return null;
+}
+
+export function buildGuardMessage(uri, hint = {}) {
+ const tool = hint.tool || "the OpenViking MCP tools";
+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;
+ const lines = [
+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",
+ `Use ${tool} instead.`,
+ ];
+ if (example) lines.push(`Example: ${example}`);
+ return lines.join("\n");
+}
diff --git a/examples/dsh-memory-plugin/shared/workspace-peer.mjs b/examples/dsh-memory-plugin/shared/workspace-peer.mjs
new file mode 100644
index 000000000..6b5cd45ec
--- /dev/null
+++ b/examples/dsh-memory-plugin/shared/workspace-peer.mjs
@@ -0,0 +1,16 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+export function deriveWorkspacePeerId(cwd) {
+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");
+}
+
+export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {
+ const explicit = String(cfg.peerId || "").trim();
+ if (explicit) return { peerId: explicit, source: "explicit" };
+
+ if (cfg.workspacePeer !== false) {
+ const peerId = deriveWorkspacePeerId(cwd);
+ if (peerId) return { peerId, source: "workspace" };
+ }
+
+ return { peerId: "", source: "none" };
+}
diff --git a/examples/dsh-memory-plugin/tools-registration.test.mjs b/examples/dsh-memory-plugin/tools-registration.test.mjs
new file mode 100644
index 000000000..163581b9a
--- /dev/null
+++ b/examples/dsh-memory-plugin/tools-registration.test.mjs
@@ -0,0 +1,45 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { registerOpenVikingTools } from "./tools.mjs";
+
+// Registration-shape gate: every definition flows through the pinned
+// @deepseek-ai/dsh-tools defineTool, so this test fails when a dsh rc pin
+// bump changes the ToolDefinition contract these tools rely on.
+test("all seven tools register as valid dsh ToolDefinitions", () => {
+ const registered = [];
+ const ctx = { tools: { register: definition => registered.push(definition) } };
+ registerOpenVikingTools(ctx, {}, {});
+
+ assert.deepEqual(registered.map(definition => definition.name), [
+ "viking_search",
+ "viking_read",
+ "viking_browse",
+ "viking_remember",
+ "viking_forget",
+ "viking_add_resource",
+ "viking_archive_expand",
+ ]);
+ for (const definition of registered) {
+ assert.equal(typeof definition.execute, "function", `${definition.name} execute`);
+ assert.equal(typeof definition.output.render, "function", `${definition.name} render`);
+ assert.equal(definition.output.schema.type, "string", `${definition.name} output schema`);
+ assert.equal(definition.parameters.type, "object", `${definition.name} parameters`);
+ const VALID_ARGS = {
+ viking_search: { query: "q" },
+ viking_read: { uri: "viking://x", level: "abstract" },
+ viking_browse: { action: "list" },
+ viking_remember: { content: "fact" },
+ viking_forget: { uri: "viking://x" },
+ viking_add_resource: { url: "https://y" },
+ viking_archive_expand: { archive_id: "archive_001" },
+ };
+ const view = definition.presentCall(VALID_ARGS[definition.name]);
+ assert.equal(view.card, "generic", `${definition.name} presentCall card`);
+ assert.ok(["read", "other"].includes(view.kind), `${definition.name} presentCall kind`);
+ assert.equal(typeof view.title, "string", `${definition.name} presentCall title`);
+ }
+
+ const [search] = registered;
+ const rendered = search.output.render({}, "hit one");
+ assert.deepEqual(rendered, [{ type: "text", text: "hit one" }]);
+});
diff --git a/examples/dsh-memory-plugin/tools.mjs b/examples/dsh-memory-plugin/tools.mjs
new file mode 100644
index 000000000..fea5d0f7e
--- /dev/null
+++ b/examples/dsh-memory-plugin/tools.mjs
@@ -0,0 +1,246 @@
+import { defineTool } from "@deepseek-ai/dsh-tools";
+
+export function registerOpenVikingTools(ctx, client, runtime) {
+ ctx.tools.register(textTool({
+ name: "viking_search",
+ description:
+ "Search OpenViking memories, resources, and skills. Use this for prior decisions, preferences, and project knowledge not present in the current context.",
+ parameters: {
+ query: { type: "string", required: true, description: "Semantic search query." },
+ scope: { type: "string", description: "Optional viking:// URI prefix." },
+ limit: { type: "integer", description: "Maximum results, from 1 to 50." },
+ },
+ async execute(args, exec) {
+ const actorPeerId = await peerFor(runtime, exec);
+ const results = await client.find(args.query, {
+ targetUri: args.scope,
+ limit: Math.max(1, Math.min(50, args.limit || 10)),
+ actorPeerId,
+ });
+ if (results.length === 0) return "No results found.";
+ return results.map(result => {
+ const abstract = result.abstract.length > client.config.recallMaxContentChars
+ ? `${result.abstract.slice(0, client.config.recallMaxContentChars)}...`
+ : result.abstract;
+ return `[${result.score.toFixed(2)}] ${result.uri}\n ${abstract}`;
+ }).join("\n\n");
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_read",
+ description:
+ "Read OpenViking content by viking:// URI at abstract, overview, or full detail.",
+ parameters: {
+ uri: { type: "string", required: true, description: "The viking:// URI to read." },
+ level: {
+ type: "string",
+ required: true,
+ enum: ["abstract", "overview", "full"],
+ description: "Detail level.",
+ },
+ },
+ async execute(args, exec) {
+ const content = await client.read(
+ args.uri,
+ args.level,
+ await peerFor(runtime, exec),
+ );
+ return typeof content === "string" && content
+ ? content
+ : `No content at ${args.uri}`;
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_browse",
+ description: "List an OpenViking directory or inspect metadata for a viking:// URI.",
+ parameters: {
+ action: {
+ type: "string",
+ required: true,
+ enum: ["list", "stat"],
+ description: "Browse operation.",
+ },
+ uri: { type: "string", description: "URI to browse. Defaults to viking://." },
+ },
+ async execute(args, exec) {
+ const actorPeerId = await peerFor(runtime, exec);
+ const uri = args.uri || "viking://";
+ if (args.action === "stat") {
+ const info = await client.stat(uri, actorPeerId);
+ return info ? JSON.stringify(info, null, 2) : `Not found: ${uri}`;
+ }
+ const entries = await client.list(uri, actorPeerId);
+ if (entries.length === 0) return `Empty directory: ${uri}`;
+ return entries
+ .map(entry => `${entry.isDir ? "[dir]" : "[file]"} ${entry.name || entry.uri}`)
+ .join("\n");
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_remember",
+ description:
+ "Store an important fact, preference, decision, or gotcha in the current OpenViking session.",
+ parameters: {
+ content: { type: "string", required: true, description: "Fact to remember." },
+ category: {
+ type: "string",
+ description: "Optional category such as preference, decision, entity, event, or pattern.",
+ },
+ },
+ async execute(args, exec) {
+ if (!exec.agent) throw new Error("viking_remember requires a calling agent");
+ const state = await runtime.initialize(exec.agent);
+ if (!state.ready) return "OpenViking server is not reachable.";
+ const category = args.category || "general";
+ const payload = {
+ role: "user",
+ content: `[Remember — ${category}] ${args.content}`,
+ ...(state.config.peerId ? { peer_id: state.config.peerId } : {}),
+ };
+ const response = await client.addMessage(
+ state.ovSessionId,
+ payload,
+ state.config.peerId,
+ );
+ return response.ok
+ ? `Remembered in OpenViking: "${args.content}" (${category})`
+ : `Failed to remember: ${response.error?.message || response.error?.code || "unknown error"}`;
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_forget",
+ description:
+ "Permanently delete an OpenViking item only after the user explicitly asks to forget or delete it. Use an exact URI, or delete the strongest search match above score 0.8.",
+ parameters: {
+ uri: { type: "string", description: "Exact viking:// URI to delete." },
+ query: { type: "string", description: "Search query used when URI is omitted." },
+ },
+ async execute(args, exec) {
+ const actorPeerId = await peerFor(runtime, exec);
+ let uri = args.uri;
+ if (!uri && args.query) {
+ const results = await client.find(args.query, { limit: 1, actorPeerId });
+ if (!results[0] || results[0].score <= 0.8) {
+ return "No strong match found (score > 0.8 required).";
+ }
+ uri = results[0].uri;
+ }
+ if (!uri) return "Provide either uri or query.";
+ return await client.forget(uri, false, actorPeerId)
+ ? `Deleted: ${uri}`
+ : `Failed to delete: ${uri}`;
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_add_resource",
+ description: "Ingest an HTTP(S) or git URL into OpenViking for indexed retrieval.",
+ parameters: {
+ url: { type: "string", required: true, description: "Remote URL to ingest." },
+ reason: { type: "string", description: "Why this resource is relevant." },
+ },
+ async execute(args, exec) {
+ const result = await client.addResource(
+ args.url,
+ args.reason,
+ await peerFor(runtime, exec),
+ );
+ return result?.root_uri
+ ? `Ingested: ${result.root_uri}`
+ : `Failed to ingest: ${args.url}`;
+ },
+ }));
+
+ ctx.tools.register(textTool({
+ name: "viking_archive_expand",
+ description: "Read original messages from one archive in the current DSH session.",
+ parameters: {
+ archive_id: { type: "string", required: true, description: "Archive id such as archive_001." },
+ },
+ async execute(args, exec) {
+ if (!exec.agent) throw new Error("viking_archive_expand requires a calling agent");
+ const state = await runtime.initialize(exec.agent);
+ const archive = await client.getSessionArchive(
+ state.ovSessionId,
+ args.archive_id,
+ state.config.peerId,
+ );
+ if (!archive) return `Archive not found: ${args.archive_id}`;
+ const messages = Array.isArray(archive.messages) ? archive.messages : [];
+ const header = [
+ `## ${archive.archive_id || args.archive_id}`,
+ archive.abstract ? `**Summary**: ${archive.abstract}` : "",
+ `**Messages**: ${messages.length}`,
+ ].filter(Boolean).join("\n");
+ const body = messages.map(formatArchiveMessage).join("\n\n");
+ return body ? `${header}\n\n${body}` : header;
+ },
+ }));
+}
+
+/** Presentation identity per tool: pending-card kind and title verb. */
+const TOOL_PRESENTATION = {
+ viking_search: { kind: "read", title: args => `OpenViking search: ${args.query}` },
+ viking_read: { kind: "read", title: args => `OpenViking read: ${args.uri}` },
+ viking_browse: { kind: "read", title: args => `OpenViking browse: ${args.uri ?? "viking://"}` },
+ viking_remember: { kind: "other", title: () => "OpenViking remember" },
+ viking_forget: { kind: "other", title: args => `OpenViking forget: ${args.uri ?? args.query ?? ""}` },
+ viking_add_resource: { kind: "other", title: args => `OpenViking ingest: ${args.url}` },
+ viking_archive_expand: { kind: "read", title: () => "OpenViking archive expand" },
+};
+
+/**
+ * All seven tools return model-facing text; `defineTool` owns parameter and
+ * output JSON-schema conversion, validation wiring, and reserved-name checks,
+ * so the definitions here stay declarative and track dsh's ToolDefinition
+ * contract through the pinned peer instead of a hand-built structure.
+ */
+function textTool(definition) {
+ const presentation = TOOL_PRESENTATION[definition.name];
+ return defineTool({
+ ...definition,
+ output: {
+ schema: { type: "string" },
+ render: (_args, value) => [{ type: "text", text: value }],
+ },
+ presentCall: args => ({
+ card: "generic",
+ kind: presentation.kind,
+ title: presentation.title(args),
+ rawInput: args,
+ }),
+ });
+}
+
+async function peerFor(runtime, exec) {
+ if (!exec.agent) return undefined;
+ return (await runtime.initialize(exec.agent)).config.peerId;
+}
+
+function formatArchiveMessage(message) {
+ const role = String(message?.role || "unknown");
+ const parts = Array.isArray(message?.parts) ? message.parts : [];
+ const body = parts.map(formatArchivePart).filter(Boolean).join("\n");
+ return `[${role}]: ${body || "(empty)"}`;
+}
+
+function formatArchivePart(part) {
+ if (!part || typeof part !== "object") return "";
+ if (part.type === "text") return String(part.text || "");
+ if (part.type === "context") {
+ return `[Context: ${part.uri || "unknown"}]\n${part.abstract || ""}`.trim();
+ }
+ if (part.type === "tool") {
+ const lines = [`[Tool: ${part.tool_name || "unknown"}]`];
+ if (part.tool_input !== undefined) {
+ lines.push(`Input: ${JSON.stringify(part.tool_input)}`);
+ }
+ if (part.tool_output) lines.push(`Output: ${part.tool_output}`);
+ return lines.join("\n");
+ }
+ return `[${part.type || "unknown"}]: ${JSON.stringify(part)}`;
+}
diff --git a/examples/dsh-memory-plugin/tools.test.mjs b/examples/dsh-memory-plugin/tools.test.mjs
new file mode 100644
index 000000000..91ebf445b
--- /dev/null
+++ b/examples/dsh-memory-plugin/tools.test.mjs
@@ -0,0 +1,103 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { registerOpenVikingTools } from "./tools.mjs";
+import { guardVikingUri } from "./uri-guard.mjs";
+
+test("uri guard blocks every DSH filesystem and shell tool that accepts paths", async () => {
+ const cases = [
+ ["read", { file_path: "viking://user/default/memories/profile.md" }],
+ ["write", { file_path: "viking://user/default/memories/profile.md" }],
+ ["edit", { file_path: "viking://user/default/memories/profile.md" }],
+ ["glob", { path: "viking://user/default/memories" }],
+ ["grep", { path: "viking://user/default/memories", pattern: "profile" }],
+ ["bash", { command: "cat viking://user/default/memories/profile.md" }],
+ ["str_replace_editor", {
+ command: "view",
+ path: "viking://user/default/memories/profile.md",
+ }],
+ ];
+
+ for (const [name, args] of cases) {
+ let delegated = false;
+ const decision = await guardVikingUri({
+ name,
+ arguments: args,
+ }, async () => {
+ delegated = true;
+ return { kind: "allow" };
+ });
+
+ assert.equal(delegated, false, name);
+ assert.equal(decision.kind, "deny", name);
+ assert.match(decision.reason, /viking:\/\/ URIs are OpenViking virtual paths/, name);
+ }
+});
+
+test("uri guard delegates OpenViking tools and ordinary filesystem paths", async () => {
+ const next = async () => ({ kind: "allow", marker: true });
+ assert.deepEqual(
+ await guardVikingUri({ name: "read", arguments: { file_path: "/tmp/a" } }, next),
+ { kind: "allow", marker: true },
+ );
+ assert.deepEqual(
+ await guardVikingUri({
+ name: "viking_read",
+ arguments: { uri: "viking://user/default/memories/profile.md" },
+ }, next),
+ { kind: "allow", marker: true },
+ );
+});
+
+test("archive expansion uses the archive API and renders original messages", async () => {
+ const registered = [];
+ const calls = [];
+ registerOpenVikingTools(
+ { tools: { register: definition => registered.push(definition) } },
+ {
+ async getSessionArchive(sessionId, archiveId, actorPeerId) {
+ calls.push({ sessionId, archiveId, actorPeerId });
+ return {
+ archive_id: archiveId,
+ abstract: "Deployment discussion",
+ messages: [
+ { role: "user", parts: [{ type: "text", text: "Use blue." }] },
+ {
+ role: "assistant",
+ parts: [{
+ type: "tool",
+ tool_name: "bash",
+ tool_input: { command: "deploy blue" },
+ tool_output: "done",
+ }],
+ },
+ ],
+ };
+ },
+ },
+ {
+ async initialize() {
+ return {
+ ovSessionId: "dsh-session",
+ config: { peerId: "workspace-peer" },
+ };
+ },
+ },
+ );
+ const archive = registered.find(tool => tool.name === "viking_archive_expand");
+
+ const rendered = await archive.execute({
+ archive_id: "archive_001",
+ }, { agent: {} });
+
+ assert.deepEqual(calls, [{
+ sessionId: "dsh-session",
+ archiveId: "archive_001",
+ actorPeerId: "workspace-peer",
+ }]);
+ assert.match(rendered, /## archive_001/);
+ assert.match(rendered, /\*\*Messages\*\*: 2/);
+ assert.match(rendered, /\[user\]: Use blue\./);
+ assert.match(rendered, /\[Tool: bash\]/);
+ assert.match(rendered, /deploy blue/);
+ assert.match(rendered, /Output: done/);
+});
diff --git a/examples/dsh-memory-plugin/uri-guard.mjs b/examples/dsh-memory-plugin/uri-guard.mjs
new file mode 100644
index 000000000..f81f21a2b
--- /dev/null
+++ b/examples/dsh-memory-plugin/uri-guard.mjs
@@ -0,0 +1,51 @@
+import { buildGuardMessage, findVikingUri } from "./shared/uri-guard.mjs";
+
+const GUARDED_TOOLS = {
+ read: {
+ tool: "viking_read",
+ example: uri => `viking_read(uri="${uri}", level="overview")`,
+ },
+ glob: {
+ tool: "viking_browse",
+ example: uri => `viking_browse(action="list", uri="${uri}")`,
+ },
+ grep: {
+ tool: "viking_search",
+ example: (uri, args) =>
+ `viking_search(query="${escapeText(args?.pattern)}", scope="${uri}")`,
+ },
+ bash: {
+ tool: "viking_read or viking_search",
+ example: uri => `viking_read(uri="${uri}", level="overview")`,
+ },
+ edit: {
+ tool: "OpenViking tools",
+ example: uri => `viking_read(uri="${uri}", level="full")`,
+ },
+ write: {
+ tool: "OpenViking tools",
+ example: uri => `viking_read(uri="${uri}", level="full")`,
+ },
+ str_replace_editor: {
+ tool: "OpenViking tools",
+ example: uri => `viking_read(uri="${uri}", level="full")`,
+ },
+};
+
+export async function guardVikingUri(exec, next) {
+ const hint = GUARDED_TOOLS[exec.name];
+ if (!hint) return next();
+ const uri = findVikingUri(exec.arguments);
+ if (!uri) return next();
+ return {
+ kind: "deny",
+ reason: buildGuardMessage(uri, {
+ tool: hint.tool,
+ example: hint.example(uri, exec.arguments),
+ }),
+ };
+}
+
+function escapeText(value) {
+ return String(value || "").replaceAll('"', '\\"');
+}
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index 2f6c05d48..45177c3bc 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -32,6 +32,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
+ { dir: join(ROOT, "examples", "dsh-memory-plugin", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
{ dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjs
index 59126b630..cb3841640 100644
--- a/examples/memory-plugin-shared/sync.test.mjs
+++ b/examples/memory-plugin-shared/sync.test.mjs
@@ -29,6 +29,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
+ { dir: join(ROOT, "examples", "dsh-memory-plugin", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
{ dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },