Skip to content

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

feat(opencode-plugin): memwrite & guard grep/glob on viking:// path (#2801)

Zayn Jarvis0829477d5d22
diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.md
index af58c1b7f..a760d2799 100644
--- a/examples/opencode-plugin/INSTALL-ZH.md
+++ b/examples/opencode-plugin/INSTALL-ZH.md
@@ -135,7 +135,7 @@ user/admin API key 的 API_KEY mode 时应留空。
- `memsearch`、`memread`、`membrowse`
- `memgrep`、`memglob`
-- `memadd`、`memremove`、`memqueue`
+- `memadd`、`memwrite`、`memremove`、`memqueue`
- `memcommit`
如果行为异常,先查看运行时文件:
@@ -162,6 +162,7 @@ curl http://localhost:1933/health
- `memgrep`:精确文本或模式搜索,替代原 `ov grep`
- `memglob`:文件 glob 枚举,替代原 `ov glob`
- `memadd`:添加远端 URL 或本地文件资源,替代常见 `ov add-resource` 场景
+- `memwrite`:通过 `/api/v1/content/write` 直接写入 `viking://` 文本文件
- `memremove`:删除资源,替代 `ov rm`
- `memqueue`:查看处理队列,替代 `ov observer queue`
@@ -172,7 +173,9 @@ curl http://localhost:1933/health
- 枚举文件用 `memglob`
- 读取内容用 `memread`
- 探索目录结构用 `membrowse`
+- 持久化笔记或小型文本更新用 `memwrite`;默认是 `create`,避免误覆盖
- 删除前必须先获得用户明确确认,再调用 `memremove` 且传入 `confirm: true`
+- 如果 agent 误用 OpenCode 本地 `read`、`glob`、`grep` 工具访问 `viking://` URI,插件会阻止这次本地文件系统调用,并提示改用 `memread`、`membrowse` 或 `memsearch`。
## `memadd` 本地文件
diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.md
index b11ce847b..d8e11c566 100644
--- a/examples/opencode-plugin/INSTALL.md
+++ b/examples/opencode-plugin/INSTALL.md
@@ -116,7 +116,7 @@ It is recommended to provide the API key through an environment variable instead
export OPENVIKING_API_KEY="your-api-key-here"
```
-`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`. Configure it explicitly when peer-scoped memory routing is needed.
+`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`.
`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `openviking-config.json`.
@@ -130,7 +130,7 @@ In a new OpenCode session, ask the agent to browse OpenViking memory or search f
- `memsearch`, `memread`, `membrowse`
- `memgrep`, `memglob`
-- `memadd`, `memremove`, `memqueue`
+- `memadd`, `memwrite`, `memremove`, `memqueue`
- `memcommit`
If anything looks wrong, check the runtime files:
@@ -157,6 +157,7 @@ The plugin exposes the following tools through the OpenCode `tool` hook:
- `memgrep`: exact text or pattern search, replacing the former `ov grep` use case
- `memglob`: file glob enumeration, replacing the former `ov glob` use case
- `memadd`: add a remote URL or local file resource, replacing common `ov add-resource` scenarios
+- `memwrite`: write text to a `viking://` file through `/api/v1/content/write`
- `memremove`: remove resources, replacing `ov rm`
- `memqueue`: inspect the processing queue, replacing `ov observer queue`
@@ -167,7 +168,9 @@ Usage guidance:
- Use `memglob` to enumerate files.
- Use `memread` to read content.
- Use `membrowse` to explore directory structure.
+- Use `memwrite` for durable notes or small direct text updates; default mode is `create`.
- Before deleting anything, obtain explicit user confirmation first; then call `memremove` with `confirm: true`.
+- If an agent tries to use OpenCode's local `read`, `glob`, or `grep` tools on a `viking://` URI, the plugin blocks that call and points it to `memread`, `membrowse`, or `memsearch`.
## Local Files with `memadd`
diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md
index 430aaddcd..d593408a2 100644
--- a/examples/opencode-plugin/README.md
+++ b/examples/opencode-plugin/README.md
@@ -9,11 +9,12 @@ The new plugin exposes everything through OpenCode tool hooks and talks to OpenV
## What It Does
- Injects indexed `viking://resources/` repositories into the system prompt.
-- Exposes repository search, grep, glob, read, browse, add, remove, and queue status as tools.
+- Exposes repository search, grep, glob, read, browse, add, write, remove, and queue status as tools.
- Maps each OpenCode session to an OpenViking session.
- Captures user and assistant text messages into OpenViking.
- Commits sessions at lifecycle boundaries for memory extraction.
- Automatically recalls relevant memories and injects them as hidden synthetic context for the current user message.
+- Blocks accidental local filesystem reads of `viking://` URIs and points the agent back to `memread`, `membrowse`, or `memsearch`.
## Files
@@ -30,7 +31,9 @@ examples/opencode-plugin/
│ ├── memadd-local.mjs
│ ├── memory-tools.mjs
│ ├── memory-recall.mjs
+│ ├── viking-uri-guard.mjs
│ └── utils.mjs
+├── tests/
└── wrappers/
└── openviking.mjs
```
@@ -133,6 +136,10 @@ precedence over values in this file.
For advanced setups, `OPENVIKING_PLUGIN_CONFIG` can point to another config file path.
+OpenCode's local `read`, `glob`, and `grep` tools cannot read `viking://` URIs.
+When the agent accidentally tries that, the plugin blocks the filesystem tool
+call and points it to `memread`, `membrowse`, or `memsearch`.
+
## Tools
### `memsearch`
@@ -193,6 +200,22 @@ memadd path="file:///home/alice/project/notes.md" reason="project notes"
After adding a resource, the tool also returns `GET /api/v1/observer/queue` status.
+### `memwrite`
+
+Write text content to a `viking://` file through `POST /api/v1/content/write`.
+
+Use this for durable notes, small project memory files, or resource text that
+should be updated directly. The default mode is `create` to avoid accidental
+overwrites. Use `append` to extend an existing file and `replace` only when the
+user explicitly wants to overwrite the file.
+
+Examples:
+
+```text
+memwrite uri="viking://user/memories/project-notes.md" content="# Decision\n\nUse PostgreSQL." wait=true
+memwrite uri="viking://resources/docs/api.md" content="\n\n## New endpoint" mode="append"
+```
+
### `memremove`
Remove a `viking://` URI through `DELETE /api/v1/fs`.
diff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjs
index f08230651..94831bc8a 100644
--- a/examples/opencode-plugin/index.mjs
+++ b/examples/opencode-plugin/index.mjs
@@ -6,6 +6,7 @@ import { createMemorySessionManager } from "./lib/memory-session.mjs"
import { createCodeTools } from "./lib/code-tools.mjs"
import { createMemoryTools } from "./lib/memory-tools.mjs"
import { createMemoryRecall } from "./lib/memory-recall.mjs"
+import { createVikingUriGuard } from "./lib/viking-uri-guard.mjs"
import { initLogger, loadConfig, log, resolveDataDir } from "./lib/utils.mjs"
const pluginRoot = dirname(fileURLToPath(import.meta.url))
@@ -26,6 +27,7 @@ export async function OpenVikingPlugin({ client, directory }) {
const repoContext = createRepoContext({ config })
const sessionManager = createMemorySessionManager({ config, pluginRoot: dataDir })
const recall = createMemoryRecall({ config })
+ const vikingUriGuard = createVikingUriGuard()
const tools = createMemoryTools({ config, sessionManager, projectDirectory: directory })
const codeTools = createCodeTools({ config })
@@ -44,6 +46,8 @@ export async function OpenVikingPlugin({ client, directory }) {
}
},
+ "tool.execute.before": vikingUriGuard,
+
tool: { ...tools, ...codeTools },
"experimental.chat.system.transform": (_input, output) => {
diff --git a/examples/opencode-plugin/lib/memory-tools.mjs b/examples/opencode-plugin/lib/memory-tools.mjs
index da9cecdec..a758e3753 100644
--- a/examples/opencode-plugin/lib/memory-tools.mjs
+++ b/examples/opencode-plugin/lib/memory-tools.mjs
@@ -244,6 +244,43 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })
},
}),
+ memwrite: tool({
+ description:
+ "Write text content to a viking:// file through OpenViking content/write. Use create for new durable notes or resources, append to extend an existing file, and replace only when the user explicitly wants to overwrite existing content.",
+ args: {
+ uri: z.string().describe("Complete viking:// file URI to write, e.g. viking://user/memories/project-notes.md or viking://resources/docs/api.md."),
+ content: z.string().describe("Text content to write."),
+ mode: z.enum(["create", "append", "replace"]).optional().describe("Write mode. Defaults to create to avoid accidental overwrite."),
+ wait: z.boolean().optional().describe("Whether OpenViking should wait for semantic/vector refresh."),
+ timeout: z.number().optional().describe("Timeout seconds when wait=true."),
+ },
+ async execute(args, context) {
+ const validationError = validateVikingUri(args.uri, "memwrite")
+ if (validationError) return validationError
+
+ try {
+ const body = {
+ uri: args.uri,
+ content: args.content,
+ mode: args.mode ?? "create",
+ wait: args.wait ?? false,
+ }
+ if (args.timeout !== undefined) body.timeout = args.timeout
+ const response = await makeRequest(config, {
+ method: "POST",
+ endpoint: "/api/v1/content/write",
+ body,
+ abortSignal: context.abort,
+ actorPeerId,
+ })
+ return JSON.stringify({ write: unwrapResponse(response) }, null, 2)
+ } catch (error) {
+ log("ERROR", "memwrite", "Write failed", { error: error?.message, args: { ...args, content: `[${args.content?.length ?? 0} chars]` } })
+ return `Error: ${error.message}`
+ }
+ },
+ }),
+
memremove: tool({
description:
"Remove a viking:// resource. The user must explicitly confirm deletion before this tool is called. Set confirm=true, otherwise deletion is refused.",
diff --git a/examples/opencode-plugin/lib/viking-uri-guard.mjs b/examples/opencode-plugin/lib/viking-uri-guard.mjs
new file mode 100644
index 000000000..fa5f4cebe
--- /dev/null
+++ b/examples/opencode-plugin/lib/viking-uri-guard.mjs
@@ -0,0 +1,52 @@
+import { log } from "./utils.mjs"
+
+const FILESYSTEM_TOOL_HINTS = {
+ read: {
+ replacement: "memread",
+ example: (uri) => `memread(uri="${uri}", level="auto")`,
+ },
+ glob: {
+ replacement: "membrowse",
+ example: (uri) => `membrowse(uri="${uri}", view="list", recursive=true)`,
+ },
+ grep: {
+ replacement: "memsearch",
+ example: (uri, args) => `memsearch(query="${String(args.pattern ?? "").replaceAll('"', '\\"')}", target_uri="${uri}")`,
+ },
+}
+
+export function createVikingUriGuard() {
+ return async (input, output) => {
+ const toolName = normalizeToolName(input?.tool ?? input?.name)
+ const hint = FILESYSTEM_TOOL_HINTS[toolName]
+ if (!hint) return
+
+ const args = output?.args ?? input?.args ?? {}
+ const uri = findVikingUri(args)
+ if (!uri) return
+
+ log("INFO", "viking-uri-guard", "Blocked filesystem tool for viking URI", {
+ tool: toolName,
+ uri,
+ })
+ throw new Error(
+ [
+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",
+ `Use ${hint.replacement} instead.`,
+ `Example: ${hint.example(uri, args)}`,
+ ].join("\n"),
+ )
+ }
+}
+
+export function findVikingUri(args = {}) {
+ for (const key of ["filePath", "path", "uri"]) {
+ const value = args[key]
+ if (typeof value === "string" && value.startsWith("viking://")) return value
+ }
+ return null
+}
+
+function normalizeToolName(value) {
+ return String(value || "").trim().toLowerCase()
+}
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index 7b29b8b3f..fc99d92aa 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -16,7 +16,7 @@
"INSTALL-ZH.md"
],
"scripts": {
- "check": "node --check index.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memadd-local.mjs && node --check lib/memory-tools.mjs && node --check lib/code-tools.mjs && node --check lib/memory-recall.mjs && node --check lib/utils.mjs && node --check tests/*.test.mjs",
+ "check": "node --check index.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memadd-local.mjs && node --check lib/memory-tools.mjs && node --check lib/code-tools.mjs && node --check lib/memory-recall.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check tests/*.test.mjs",
"test": "node --test tests/*.test.mjs"
},
"dependencies": {
diff --git a/examples/opencode-plugin/tests/memory-tools-write.test.mjs b/examples/opencode-plugin/tests/memory-tools-write.test.mjs
new file mode 100644
index 000000000..987e7d7f5
--- /dev/null
+++ b/examples/opencode-plugin/tests/memory-tools-write.test.mjs
@@ -0,0 +1,18 @@
+import test from "node:test"
+import assert from "node:assert/strict"
+import { readFile } from "node:fs/promises"
+import { fileURLToPath } from "node:url"
+import { dirname, join } from "node:path"
+
+const testDir = dirname(fileURLToPath(import.meta.url))
+const memoryToolsPath = join(testDir, "../lib/memory-tools.mjs")
+
+test("memwrite uses content/write with safe defaults and peer propagation", async () => {
+ const source = await readFile(memoryToolsPath, "utf8")
+
+ assert.match(source, /memwrite: tool\(/)
+ assert.match(source, /endpoint: "\/api\/v1\/content\/write"/)
+ assert.match(source, /mode: args\.mode \?\? "create"/)
+ assert.match(source, /actorPeerId,/)
+ assert.match(source, /mode: z\.enum\(\["create", "append", "replace"\]\)/)
+})
diff --git a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs b/examples/opencode-plugin/tests/viking-uri-guard.test.mjs
new file mode 100644
index 000000000..84d3bb612
--- /dev/null
+++ b/examples/opencode-plugin/tests/viking-uri-guard.test.mjs
@@ -0,0 +1,26 @@
+import test from "node:test"
+import assert from "node:assert/strict"
+import { createVikingUriGuard, findVikingUri } from "../lib/viking-uri-guard.mjs"
+
+test("viking uri guard blocks filesystem tools on virtual URIs", async () => {
+ const guard = createVikingUriGuard()
+
+ assert.equal(findVikingUri({ filePath: "viking://resources/project/file.md" }), "viking://resources/project/file.md")
+ assert.equal(findVikingUri({ path: "/tmp/file.md" }), null)
+
+ await assert.rejects(
+ () => guard({ tool: "read" }, { args: { filePath: "viking://resources/project/file.md" } }),
+ /Use memread instead/,
+ )
+ await assert.rejects(
+ () => guard({ tool: "glob" }, { args: { path: "viking://resources/project/" } }),
+ /Use membrowse instead/,
+ )
+ await assert.rejects(
+ () => guard({ tool: "grep" }, { args: { path: "viking://resources/project/", pattern: "SessionManager" } }),
+ /Use memsearch instead/,
+ )
+
+ await assert.doesNotReject(() => guard({ tool: "read" }, { args: { filePath: "/tmp/file.md" } }))
+ await assert.doesNotReject(() => guard({ tool: "bash" }, { args: { command: "cat viking://resources/project/file.md" } }))
+})