Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(opencode): update plugin (#678)
yangxinxin-7a8dfad048e63
diff --git a/examples/opencode/plugin/README.md b/examples/opencode/plugin/README.mdindex 0a482f4ec..07e4b9f70 100644--- a/examples/opencode/plugin/README.md+++ b/examples/opencode/plugin/README.md@@ -7,7 +7,7 @@ OpenViking plugin for [OpenCode](https://opencode.ai). Injects your indexed codeInstall the latest OpenViking and configure `~/.openviking/ov.conf`:```bash-pip install openviking --upgrade --force-reinstall+pip install openviking --upgrade``````json@@ -39,7 +39,7 @@ For other providers (Volcengine, Anthropic, DeepSeek, Ollama, etc.) see the [OpeBefore starting OpenCode, make sure the OpenViking server is running. If it's not already started:```bash-openviking-server --config ~/.openviking/ov.conf > /tmp/openviking.log 2>&1 &+openviking-server > /tmp/openviking.log 2>&1 &```## Usage in OpenCodediff --git a/examples/opencode/plugin/index.mjs b/examples/opencode/plugin/index.mjsindex a91efe1fa..22db55f84 100644--- a/examples/opencode/plugin/index.mjs+++ b/examples/opencode/plugin/index.mjs@@ -7,7 +7,6 @@ import { fileURLToPath } from "url"const execAsync = promisify(exec)const __dirname = dirname(fileURLToPath(import.meta.url))-const OV_CONF = join(homedir(), ".openviking", "ov.conf")// ── Helpers ───────────────────────────────────────────────────────────────────@@ -26,7 +25,7 @@ async function isHealthy() {async function startServer() {// Start in background, wait up to 30s for healthy- await run("openviking-server --config " + OV_CONF + " > /tmp/openviking.log 2>&1 &")+ await run("openviking-server > /tmp/openviking.log 2>&1 &")for (let i = 0; i < 10; i++) {await new Promise((r) => setTimeout(r, 3000))if (await isHealthy()) return true@@ -34,18 +33,25 @@ async function startServer() {return false}+let initPromise = null++function makeToast(client) {+ return (message, variant = "warning") =>+ client.tui.showToast({+ body: { title: "OpenViking", message, variant, duration: 8000 },+ }).catch(() => {})+}+// ── Skill auto-install ────────────────────────────────────────────────────────function installSkill() {const src = join(__dirname, "skills", "openviking", "SKILL.md")const dest = join(homedir(), ".config", "opencode", "skills", "openviking", "SKILL.md")- try {- if (!existsSync(dirname(dest))) mkdirSync(dirname(dest), { recursive: true })- const content = readFileSync(src, "utf8")- if (!existsSync(dest) || readFileSync(dest, "utf8") !== content) {- writeFileSync(dest, content, "utf8")- }- } catch {}+ mkdirSync(dirname(dest), { recursive: true })+ const content = readFileSync(src, "utf8")+ if (!existsSync(dest) || readFileSync(dest, "utf8") !== content) {+ writeFileSync(dest, content, "utf8")+ }}// ── Repo context cache ────────────────────────────────────────────────────────@@ -80,49 +86,57 @@ async function loadRepos() {// ── Init: check deps, start server if needed ─────────────────────────────────-async function init(client) {- const toast = (message, variant = "warning") =>- client.tui.showToast({- body: { title: "OpenViking", message, variant, duration: 8000 },- }).catch(() => {})+async function _init(client) {+ const toast = makeToast(client)- // 服务已在跑,直接返回+ // server already runningif (await isHealthy()) return true- // 没跑,先看是哪种情况+ // check if ov is installedtry {await run("command -v ov", { timeout: 2000 })} catch {- // command not found → 没装- await toast("openviking 未安装,请运行: pip install openviking", "error")+ await toast("openviking is not installed. Run: pip install openviking", "error")return false}- // 装了但没有配置文件 → 无法启动- if (!existsSync(OV_CONF)) {- await toast("未找到 ~/.openviking/ov.conf,请先配置 API keys 后再启动服务", "warning")+ // installed but no config file — cannot start+ const ovConf = join(homedir(), ".openviking", "ov.conf")+ if (!existsSync(ovConf)) {+ await toast("~/.openviking/ov.conf not found. Please configure API keys before starting the server.", "warning")return false}- // 装了有配置,服务没跑 → 静默自动启动+ // installed + config exists — auto-start silentlyconst started = await startServer()if (!started) {- await toast("openviking 服务启动失败,查看日志: /tmp/openviking.log", "error")+ await toast("Failed to start openviking server. Check logs: /tmp/openviking.log", "error")return false}return true}+async function init(client) {+ if (!initPromise) initPromise = _init(client).finally(() => { initPromise = null })+ return initPromise+}+// ── Plugin export ─────────────────────────────────────────────────────────────/*** @type {import('@opencode-ai/plugin').Plugin}*/export async function OpenVikingPlugin({ client }) {- installSkill()+ const toast = makeToast(client)++ try {+ installSkill()+ } catch (e) {+ await toast(`Failed to install skill: ${e.message}`, "error")+ }- // 后台初始化,不阻塞 opencode 启动+ // init in background — do not block opencode startupPromise.resolve().then(async () => {const ready = await init(client)if (ready) await loadRepos()diff --git a/examples/opencode/plugin/openviking-context.ts b/examples/opencode/plugin/openviking-context.tsdeleted file mode 100644index 1b728ea78..000000000--- a/examples/opencode/plugin/openviking-context.ts+++ /dev/null@@ -1,60 +0,0 @@-import { exec } from "child_process"-import { promisify } from "util"--const execAsync = promisify(exec)--let cachedRepos: string | null = null--async function loadRepos(): Promise<void> {- try {- const { stdout } = await execAsync(- "ov --output json ls viking://resources/ --abs-limit 2000",- { timeout: 8000 }- )- const parsed = JSON.parse(stdout)- const items: Array<{ uri: string; abstract?: string }> = parsed?.result ?? []- const repos = items- .filter((item) => item.uri?.startsWith("viking://resources/"))- .map((item) => {- const name = item.uri.replace("viking://resources/", "").replace(/\/$/, "")- return item.abstract- ? `- **${name}** (${item.uri})\n ${item.abstract}`- : `- **${name}** (${item.uri})`- })- if (repos.length > 0) {- cachedRepos = repos.join("\n")- }- } catch {- // openviking not available — plugin is a no-op- }-}--/**- * @type {import('@opencode-ai/plugin').Plugin}- */-export async function OpenVikingContextPlugin() {- // Fetch repos at startup so the cache is ready before any request- await loadRepos()-- return {- // Inject repo list into every LLM request's system prompt (sync — no await)- "experimental.chat.system.transform": (- _input: unknown,- output: { system: string[] }- ) => {- if (!cachedRepos) return- output.system.push(- `## OpenViking — Indexed Code Repositories\n\n` +- `The following repos are semantically indexed and searchable.\n` +- `When the user asks about any of these projects or their internals, ` +- `you MUST proactively call skill("openviking") before answering.\n\n` +- cachedRepos- )- },-- // Refresh repo list when a new session starts- "session.created": async () => {- await loadRepos()- },- }-}diff --git a/examples/opencode/plugin/package.json b/examples/opencode/plugin/package.jsonindex 8b9705c3b..7795c1bdb 100644--- a/examples/opencode/plugin/package.json+++ b/examples/opencode/plugin/package.json@@ -1,6 +1,6 @@{"name": "openviking-opencode",- "version": "0.3.0",+ "version": "0.3.3","description": "OpenCode plugin for OpenViking — injects indexed repo context into the AI assistant and auto-installs the openviking skill","type": "module","main": "index.mjs",diff --git a/examples/opencode/plugin/skills/openviking/SKILL.md b/examples/opencode/plugin/skills/openviking/SKILL.mdindex 6478b05ef..7de853dee 100644--- a/examples/opencode/plugin/skills/openviking/SKILL.md+++ b/examples/opencode/plugin/skills/openviking/SKILL.md@@ -11,22 +11,7 @@ compatibility: opencode## How OpenViking Organizes Data-OpenViking stores content in a virtual filesystem under the `viking://` namespace, similar to a local directory tree:--```-viking://-└── resources/- ├── fastapi/ ← repo A- │ ├── fastapi/- │ │ ├── routing.py- │ │ └── dependencies/- │ └── tests/- └── requests/ ← repo B- ├── requests/- └── tests/-```--Each directory has AI-generated summaries (`abstract` / `overview`). **The key principle: narrow the URI scope to improve retrieval efficiency.** Instead of searching all repos, lock to a specific repo or subdirectory — this reduces noise and speeds up results significantly.+OpenViking stores content in a virtual filesystem under the `viking://` namespace. Each URI maps to a file or directory, e.g. `viking://resources/fastapi/routing.py`. Each directory has AI-generated summaries (`abstract` / `overview`). **The key principle: narrow the URI scope to improve retrieval efficiency.** Instead of searching all repos, lock to a specific repo or subdirectory — this reduces noise and speeds up results significantly.## Search Commands@@ -34,21 +19,22 @@ Choose the right command based on what you're looking for:| Command | Use when | Example ||---------|----------|---------|-| `ov find` | You know the **concept** but not the exact code | "dependency injection", "rate limiting logic" |+| `ov search` | Semantic search — use for concept/intent based queries | "dependency injection", "how auth works" || `ov grep` | You know the **exact keyword or symbol** | function name, class name, error string || `ov glob` | You want to **enumerate files** by pattern | all `*.py` files, all test files |```bash-# Semantic search — concept/intent based-ov find "dependency injection" --uri viking://resources/fastapi --limit 10-ov find "how tokens are refreshed" --uri viking://resources/fastapi/fastapi/security-ov find "JWT authentication" --limit 10 # across all repos+# Semantic search+ov search "dependency injection" --uri viking://resources/fastapi --limit 10+ov search "how tokens are refreshed" --uri viking://resources/fastapi/fastapi/security+ov search "JWT authentication" --limit 10 # across all repos+ov search "error handling" --limit 5 --threshold 0.7 # filter low-relevance results# Keyword search — exact match or regexov grep "verify_token" --uri viking://resources/fastapiov grep "class.*Session" --uri viking://resources/requests/requests-# File enumeration — by name pattern (--uri is required)+# File enumeration — by name pattern (always specify --uri to scope the search)ov glob "**/*.py" --uri viking://resources/fastapiov glob "**/test_*.py" --uri viking://resources/fastapi/testsov glob "**/*.py" --uri viking://resources/ # across all repos@@ -56,6 +42,13 @@ ov glob "**/*.py" --uri viking://resources/ # across all repos**Narrowing scope:** once you identify a relevant directory, pass it as `--uri` to restrict subsequent searches to that subtree — this is faster and more precise than searching the whole repo.+**Query formulation:** write specific, contextual queries rather than single keywords.+```bash+ov search "API" # too vague+ov search "REST API authentication with JWT tokens" # better+ov search "JWT token refresh flow" --uri viking://resources/backend # best+```+## Read Content```bash@@ -75,14 +68,20 @@ ov read viking://resources/fastapi/fastapi/dependencies/utils.py --offset 100 --```bashov ls viking://resources/ # list all indexed reposov ls viking://resources/fastapi # list repo top-level contents-ov tree viking://resources/fastapi # full directory tree+ov ls viking://resources/fastapi --simple # paths only, no metadata+ov ls viking://resources/fastapi --recursive # list all files recursively+ov tree viking://resources/fastapi # full directory tree (default: 3 levels deep)+ov tree viking://resources/fastapi -L 2 # limit depth to 2 levels+ov tree viking://resources/fastapi -l 200 # truncate abstract column to 200 chars+ov tree viking://resources/fastapi -L 2 -l 200 # combined: 2 levels deep, 200-char summaries```+`-L` controls how many levels deep the tree expands. `-l` controls the length of the AI-generated summary per directory. Use `ov tree -L 2 -l 200` as a good starting point to understand a repo's structure before diving in.+## Add a Repository```bash-ov add-resource https://github.com/owner/repo --to viking://resources/ --timeout 300-ov add-resource /path/to/project --to viking://resources/ --timeout 300+ov add-resource https://github.com/owner/repo --to viking://resources/repo --timeout 300````--timeout` is required (seconds). Use 300 (5 min) for small repos, increase for larger ones.@@ -105,7 +104,7 @@ This permanently deletes the repo and all its indexed content. Confirm with the## Error Handling-**`command not found: ov`** → Tell user: `pip install openviking --upgrade --force-reinstall`. Stop.+**`command not found: ov`** → Tell user: `pip install openviking --upgrade`. Stop.**`url is required` / `CLI_CONFIG` error** → Auto-create config and retry:```bash@@ -115,7 +114,7 @@ mkdir -p ~/.openviking && echo '{"url": "http://localhost:1933"}' > ~/.openvikin**`CONNECTION_ERROR` / failed to connect:**- `~/.openviking/ov.conf` **exists** → auto-start server, wait until healthy, retry:```bash- openviking-server --config ~/.openviking/ov.conf > /tmp/openviking.log 2>&1 &+ openviking-server > /tmp/openviking.log 2>&1 &for i in $(seq 1 10); do ov health 2>/dev/null && break; sleep 3; done```- **Does not exist** → Tell user to configure `~/.openviking/ov.conf` first. Stop.@@ -126,5 +125,5 @@ For other issues or command details, run:```bashov help-ov <command> --help # e.g. ov find --help+ov <command> --help # e.g. ov search --help```