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-plugin): support OpenCode v2 (#5341)
t0saki12076389da96
diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.mdindex a18ec57ce..c0de111a9 100644--- a/docs/en/agent-integrations/10-opencode.md+++ b/docs/en/agent-integrations/10-opencode.md@@ -8,7 +8,7 @@ Tool calls and results are captured as dedicated `tool` parts, and `tool_output`## Prerequisites-- [OpenCode](https://opencode.ai/)+- [OpenCode](https://opencode.ai/) 1.15.7+ or 2.0.15+- Node.js 18+- An OpenViking HTTP server- An OpenViking API key when your server requires authentication@@ -60,6 +60,10 @@ opencodeIf `~/.config/opencode/opencode.json` already exists, do not overwrite it; only merge `"@openviking/opencode-plugin"` into the existing `plugin` array. OpenCode downloads the npm package at startup, and the plugin registers its MCP server automatically.+OpenCode 2 uses the same package. It calls `setup()`, while OpenCode 1 calls `server()`. OpenCode 2 normalizes `"plugin"` to `"plugins"`, so the installer continues to write the v1/v2-compatible `"plugin"` key; do not rewrite an existing config just for v2. There is no OpenCode skill to install.++On OpenCode 2, the plugin sets its MCP server to `codemode: false`, so tools remain directly available as `openviking_*` instead of being folded into Code Mode. OpenCode 2 has no plugin toast API, so service availability notices are written to the plugin log only.+### Source installIf package installation is not available in your environment:@@ -151,6 +155,10 @@ Restart OpenCode after installation. In an OpenCode session, the plugin should e- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`+OpenCode 2 captures the current turn's user message, assistant response, and tool results when each execution ends, and captures the transcript before compaction discards it. It commits at the token threshold, and forces a commit on compaction, session deletion, and plugin cleanup. OpenCode 2 runs cleanup after 60 minutes of inactivity, when the service stops, and when a local plugin is hot-reloaded.++OpenCode 1.15.7 does not call plugin disposal hooks. A short-lived v1 CLI run can also exit before asynchronous capture finishes; this behavior predates v2 support. Keep the v1 service running to let idle capture finish. OpenCode 1.18.32 calls the disposal hook when its instance is disposed.+Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are written to:```bash@@ -162,7 +170,7 @@ Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are| Issue | What to check ||-------|---------------|-| Plugin does not load | Confirm `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or that `~/.config/opencode/plugins/openviking.js` exists for source installs |+| Plugin does not load | Confirm the `plugin` array in `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or that `~/.config/opencode/plugins/openviking.js` exists for source installs || Load fails with a missing `lib/shared/*.mjs` module | The source copy was made without running `sync.mjs` first. Run `node examples/memory-plugin-shared/sync.mjs` from the repository root and copy `lib/` again || MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars; `OPENVIKING_CLI_CONFIG_FILE` points the plugin at a different ovcli.conf || 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex d4a2b315d..ecb0829a1 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -57,7 +57,7 @@| trae / trae-cn | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) | ❌ | ✅ | ❌ || zcode | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) | ❌ | ✅ | ❌ || kimicode | 7 native plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), first successful prompt load | ❌ (PreCompact only captures/commits) | ✅ | ❌ |-| opencode | 8 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) + repo list into the system prompt | ❌ (commits once before and once after compacting) | ✅ | ❌ (toast instead) |+| opencode | dual-stack v1/v2 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200) + repo list into the system prompt | ❌ (commit after compaction only) | ✅ | ❌ || dsh | native Cordis plugin (same process) + MCP proxy + skill | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), once per session | ❌ | ✅ | ❌ || pi | native extension (9 events) | ✅ | ✅ | ❌ | ✅ (10000) + `<available-skills>` (1200), rebuilt into systemPrompt every turn | ✅ **takeover** (on by default) | ✅ | ✅ || openclaw | context-engine plugin (`ownsCompaction:true`) | ✅ | ❌ (goes through `/find`, which has no session_id field) | ❌ | ❌ | ✅ **full ContextEngine takeover** | ❌ failed turns are not replayed | ❌ |@@ -285,7 +285,7 @@ On the server side, `session_id` handling diverges into two distinct execution p| cursor | `beforeSubmitPrompt` | prompt verbatim; deduped by event id and a 500ms window, reusing the cached block for the same promptHash | ✅ `cu-` | A | `additional_context` | ❌ || trae / trae-cn | `UserPromptSubmit` | prompt with prior injection blocks stripped (reads `input.prompt` only) | ✅ `tr-`/`trcn-` | A | `additionalContext` | ❌ || zcode | `UserPromptSubmit` | three kinds of injection block stripped (including `<system-reminder>`) | ✅ `zc-` | A | `additionalContext` (strict JSON) | ❌ |-| opencode | the user message in every `chat.message` | concatenates non-synthetic text parts; skips recall for the turn if the body already contains `<openviking-context` | ✅ `oc-` | A (timeoutMs=30000) | builds a synthetic part and `unshift`s it to the front of parts | ❌ |+| opencode | v1: every `chat.message`; v2: every `prompt` | v1 concatenates non-synthetic text parts; v2 reads prompt text directly | ✅ `oc-` | A (timeoutMs=30000) | v1 prepends a synthetic part; v2 stores message metadata and injects before that user message in the context hook | ❌ || dsh | `agent/pre-step` waterfall (await next first, then append) | every message in the claimed batch (filtering out its own injected content) | ✅ `dsh-` | A | appended to the end of `decision.messages` via `createUserMessage` (source: plugin/openviking-memory) | ❌ || pi | queued during `before_agent_start`; retrieval runs inside the `context` event (this turn's prompt gets this turn's memories) | prompt verbatim | ✅ `pi-` (omitted before the session exists) | A | prepended to the last real user message (idempotency checked via `<openviking-context`) | ❌ || openclaw | context-engine transformContext assemble (7 passthrough gates) | plain text of the last user message, cleaned and cut to 4000 characters | ❌ (`/find` has no such field) | `/find` | prepended into the last user message as `<relevant-memories>` + `Source: openviking-auto-recall` | ❌ |@@ -363,7 +363,7 @@ To prevent injected content from being captured a second time, the injection pro### 3.3.1 Mechanism foundations-- **Write path**: The JS family routes all writes through `batch-send.mjs` (endpoint `POST /messages/batch`, capped at 100 messages per batch to match the server's `max_length=100` limit; on a 404/405 error, it gracefully degrades to sending one message at a time). Incremental cursors are implemented per integration (e.g., `cc` and `codex` compute a cursor from the transcript turn index; `cursor` uses `sha256(index+role+content)`; `zcode` relies on the rollout `turn_id`; `opencode` uses an event-stream Map; `dsh` uses an event allowlist; `pi` uses the branch entry watermark; and `hermes` slices by the current turn).+- **Write path**: The JS family routes all writes through `batch-send.mjs` (endpoint `POST /messages/batch`, capped at 100 messages per batch to match the server's `max_length=100` limit; on a 404/405 error, it gracefully degrades to sending one message at a time). Incremental cursors are implemented per integration (e.g., `cc` and `codex` compute a cursor from the transcript turn index; `cursor` uses `sha256(index+role+content)`; `zcode` relies on the rollout `turn_id`; OpenCode v1 uses an event-stream Map while v2 reads context at execution boundaries and advances by message ID; `dsh` uses an event allowlist; `pi` uses the branch entry watermark; and `hermes` slices by the current turn).- **Commits are client-triggered** (see [§2.3](#_2-3-server-side-session-and-commit-semantics)): The server does not auto-commit by default. Any "threshold/trigger" condition mentioned in the tables below refers strictly to client-side logic.- **Differences in `keep_recent_count`** (determining how much of a "live tail" a commit leaves for the host): The server default is 0. Here is what each integration passes: `cc`/`codex` pass 10 on threshold commits; `cursor`, `trae×2`, and `zcode` send an empty body `{}`, meaning 0 (every commit acts as a full archive); `opencode` and `dsh` pass 10; `pi` passes 10 outside takeover mode and 3 within it (locally, this means "keep 3 user turns," but the server interprets it as a raw message count, so fewer messages are actually retained); `openclaw` passes 10 on an `afterTurn` threshold trigger and 0 on `compact`/`reset`/`memory_store` operations; `hermes` always passes 0.- **Write-path detachment** (`async-writer.mjs`, enabled by default for `cc`/`codex`/`zcode` on `Stop`): The execution flow is drain stdin → spawn detached worker → approve → write payload → unref. *(Note: If spawning fails, approval has not yet occurred, ensuring the synchronous fallback executes exactly once).* The detached worker forms its own process group, immunizing it against terminal signals. This is the crucial mechanism that makes `cc` reliable during shutdown and prevents `zcode` from losing writes upon `Ctrl+C`. **Side effect:** Once detachment is active, `Stop` no longer prints the `appended N turn(s)` notice (to restore this, set `OPENVIKING_WRITE_PATH_ASYNC=0`).@@ -377,7 +377,7 @@ To prevent injected content from being captured a second time, the injection pro| cursor | stop: `capturedSinceCommit ≥ 8` (counted in messages, ~4 Q&A turns; purely client-side counting), keep 0 | sessionEnd: registered (but never reached in practice, see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) | preCompact: unconditional || trae / trae-cn | Every Stop with content commits (no threshold), keep 0 | — | None (no PreCompact event upstream) || zcode | Same as trae (every Stop commits, keep 0; the rollout incremental cursor advances conservatively, so any missed turns are caught up on the next Stop in the same session) | — | None (no PreCompact event upstream) |-| opencode | `session.idle` path: after the flush runs, `pending_tokens ≥ 20000` must hold before it commits, keep 10 | `session.deleted` / `session.error`: forced commit; dispose: forced commit | Fires once before `experimental.session.compacting` and once after `session.compacted` (so one host compaction = two commits) |+| opencode | v1 `session.idle` / v2 execution completion: after flush, `pending_tokens ≥ 20000` triggers commit, keep 10 | `session.deleted` / v1 `session.error`: forced commit; v1 dispose / v2 cleanup: forced commit | v1 fires before compacting and after compacted; v2 fires once after `session.compaction.ended` || dsh | `turn/end`: `pending_tokens ≥ 20000` (30s timeout), keep 10 | Teardown (see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) | None (does not listen for compaction events) || pi (takeover on by default) | `onTurnSynced`: when the locally estimated `pendingTokens ≥ 30000` and `lastSeenUserTurns > 3`, runs commitAndAdvance (keep 3; the overview polls 15 times at 2s intervals, and if it returns empty, the boundary does not advance, but pendingTokens is zeroed and retried once it has accumulated again) | Run `/viking commit` manually | `session_before_compact` (requires a non-empty `firstKeptEntryId`) || pi (takeover off) | After syncBranch runs: server-side `pending_tokens ≥ 20000`, keep 10 | `session_shutdown`: unconditional commit; run `/viking commit` manually | `session_before_compact`: unconditional commit |@@ -399,7 +399,7 @@ Legend: **C** = commits; **C\*** = commits, with a precondition (see notes); **| cursor | **—** (closing a chat or opening a new chat fires no event) | **—** | **—** | **—** (`sessionEnd` is registered and only fires on window_close, but by then the host has destroyed the shell-exec host, causing the hook to abort before spawn) | **—** | A session ending below the 8-message watermark leaves its tail waiting for later messages in the same session to trigger a commit || trae / trae-cn | **—** (no session-end-style event) | **—** | **—** | **—** | **—** | Every Stop has already committed, meaning the most data left to archive equals the last in-flight turn || zcode | **—** (no session-end-style event) | **C\*** | **—** | **—** | **—** | C\* precondition: The Stop for that turn had already fired when Ctrl+C arrived (the detached worker finishes writing as usual); every Stop has already committed, and missed turns are recovered by the rollout cursor on the next Stop in the same session |-| opencode | **C\*** (≥1.15.11 `dispose` calls `flushAll({commit:true})`, covering all four shutdown paths; <1.15.11 has no such hook → —) | **C\*** | **C\*** | **C\*** | **—** | C\* precondition: The host shutdown budget is 5s, while a single session takes up to 5s for health + 10s for batch + 30s for commit, and multiple sessions process serially. A commit overrunning the budget is cut off, and the pending queue does not cover this (unsettled fetches are never queued); after a restart, `init()` does not proactively flush leftover sessions |+| opencode | **C\*** (v1 ≥1.15.11 `dispose` or v2 cleanup calls `flushAll({commit:true})`) | **C\*** | **C\*** | **C\*** | **—** | C\* precondition: host cleanup time is finite, so slow requests or serial commits across several sessions may be cut off; v2 cleanup runs after 60 minutes of inactivity, service shutdown, and local-plugin hot reload || dsh | **C** (Cordis teardown triggers one 3s-timeout commit per session, no threshold) | **C** (the first one; a second Ctrl+C force-quits → —) | **C** | **—** (no SIGHUP listener) | **—** | The teardown commit and the threshold commit share a serial write chain, meaning it may not fit inside the 5s process grace period if a slow request precedes it; in the web form, closing the browser tab does not trigger a teardown || pi (takeover default) | **—** (`session_shutdown` fires on every shutdown path and is awaited, but the handler persists local takeover state and does not commit) | **—** | **—** | **—** | **—** | The next run accumulating 30000, or a manual `/viking commit` || pi (takeover off) | **C** (`await sync.commit()`, failures go to the pending queue) | **C** | **C** | **C** | **—** | — |@@ -431,7 +431,7 @@ Legend: **C** = commits; **C\*** = commits, with a precondition (see notes); **|---|---|| claude-code | Offers the most complete isolation: SubagentStart derives a separate `cc-<sid>__subagent-<agent_id>` session, and SubagentStop reads the subagent transcript, pushes it, commits unconditionally, and clears the state || codex / trae-cli | No separate session: Subagent output (`agent_message` / `sub_agent_activity`) is folded into the main session's assistant/tool components |-| opencode | `oc-<parent>__subagent-<child>` hangs under the parent namespace; the session-start injection skips subagents (though recall does not); ID derivation is sensitive to event order — when `chat.message` arrives before `session.created`, the `__subagent-` suffix is lost |+| opencode | `oc-<parent>__subagent-<child>` hangs under the parent namespace; session-start injection skips subagents (recall does not); v2 maps `parentID` from `session.created`, then reads context when execution ends || dsh | Each subagent operates as a separate `dsh-<id>` session, preserving no parent-child relationship; N subagents = N profile injections + N separate sessions || hermes | `delegate_task` passes `skip_memory=True` → the subagent is disconnected from OV (no session, recall, or tool surface); subtask output is not fed back || cursor / trae×2 / zcode / pi / openclaw | No specific subagent handling (anything generating its own session ID becomes its own session; otherwise, it mixes into the main session. `openclaw` can mask this behavior using `bypassSessionPatterns`) |@@ -445,7 +445,7 @@ Legend: **C** = commits; **C\*** = commits, with a precondition (see notes); **| claude-code | No takeover | PreCompact commits synchronously. This is the only write path that does not detach, as CC rewrites the transcript immediately afterward. | A SessionStart with `source="compact"` re-injects OV's `latest_archive_overview` plus ≤5 abstracts. || codex / trae-cli | No takeover | PreCompact backfills uncaptured turns → full commit → `ovSessionId=null`. If the backfill is incomplete, no commit occurs and it is left for retry. There is no PostCompact wiring; it relies instead on the transcript shrinkage observed at Stop for defensive correction. | Injects the archive digest upon resume. || cursor / trae×2 / zcode | No takeover | Cursor: `preCompact` commits unconditionally (Trae×2/Zcode lack this upstream event). | — |-| opencode | No takeover | Flush and commit prior to compaction. | Flush and commit again once `session.compacted` fires (two commits in total). |+| opencode | No takeover | v1 flushes and commits before compaction; v2 captures the transcript before compaction | v1 commits again on `session.compacted`; v2 commits once on `session.compaction.ended` || dsh | Unaware. It does not listen for compaction events; injection rides on a pre-step user message and shrinks alongside the host's compaction. The profile is not re-sent. | — | — || pi | **Two-layer takeover** (on by default, [§3.4.2](#_3-4-2-pi-takeover)) | `session_before_compact`: flush → commit → `pollOverview`. On success, it returns a custom compaction summary that overrides Pi's. On failure, it fails open and falls back to Pi's default compaction. | Calls `resetBoundary` upon success. || openclaw | **Full takeover**: `ownsCompaction: true`, the host no longer runs its own summary ([§3.4.3](#_3-4-3-openclaw-contextengine)) | `compact()` = `commit(wait=true, keep 0)` → reads the overview back and utilizes it as the summary. | The main `assemble` rebuilds context with `[Session History Summary]`. |@@ -506,7 +506,7 @@ There are three primary guards on MCP `write` and REST `content/write` (`content| claude-code | All hooks catch exceptions → approve (never blocks); at session-start, even pending replays are skipped | context-face 6h + host-cli probe 7d + health 5s | None (relies on pending replay); `peer_scope` degrades once; batch falls back to sequential | No (`uri-guard` deny is by design) || codex / trae-cli | All hooks catch exceptions → noop | context-face 6h + compressor runtime_failed (until the next startup) | Same as above (pending replay, triggered at SessionStart) | No || cursor/trae×2/zcode | Fetch errors are swallowed as `status:0`, and catch returns an empty injection; silently skips if the lock isn't acquired within 5s | context-face 6h (no negative cache for unreachable servers; every turn waits the full 15s) | None | No |-| opencode | All paths catch exceptions → WARN; the `event`/`dispose` hooks lack try/catch blocks (non-retryable commit failures bubble up to the host) | context-face 6h only; `/health` is uncached (one round trip per turn) | No synchronous retry; the MCP proxy retries once each for 401/403 and 400/404 | Mostly no (except `event`/`dispose`) |+| opencode | Recall, context, after-tool, event-loop, and cleanup failures are caught and logged; intentional URI-guard denials still reach the model | context-face 6h only; `/health` is uncached | No synchronous retry; the MCP proxy retries once each for 401/403 and 400/404 | No (URI-guard denial is intentional) || dsh | The client swallows all exceptions; `ensureState` failures are not cached (when the server is unreachable, each pre-step makes two 5s health calls) | context-face 6h + an in-process user-space cache that never expires | None; pending queue replays 3 times across processes | Yes (pre-step runs profile+recall serially; session/flush blocks) || pi | On health failure, `start()` returns early and registers no tools; subsequent prompts silently retry the connection. A `/mcp` handshake that fails on its own (401/403, timeout, no `/mcp`) never fails startup: recall, sync and takeover carry on, the status line shows `tools ✗`, and `/viking` prints the full error | context-face 6h; the handshake has none, so a still-failing bridge is retried once per turn and can spend its 5s budget before recall is queued | Hooks: none, pending queue only. A failed MCP transport is discarded and the next invocation reconnects; the failed call is never replayed | Partly (`session_shutdown` is awaited: ~0s with takeover, max 30s without, plus closing the MCP client; on a `turn_end` network error, each message waits 10s) || openclaw | Client construction never fails; health checks swallow exceptions; recall is skipped if the 500ms precheck fails | No negative cache (one 500ms health precheck per turn) | None (a single fetch); Phase2 polling in commit/afterTurn | No (except when `memory_store` re-raises; `compact()` blocks for up to 5 minutes) |@@ -526,7 +526,7 @@ General HTTP timeouts are 15000ms (with a 1000ms floor). MCP proxy requests time| cursor | ❌ | ❌ | Rule (`alwaysApply`) + 2 skills (`openviking-memory`, `openviking-skills`) | ❌ (Shares the installer TUI) | Standalone `uri-guard`, independent of the plugin toggle || trae/trae-cn | ❌ | ❌ | None | ❌ | — || zcode | ❌ | ❌ | None | ❌ | — |-| opencode | ❌ (Has toasts) | ❌ | None (Deliberately omitted) | ✅ | — |+| opencode | ❌ | ❌ | None (Deliberately omitted) | ✅ | v1 has toasts; v2 logs only || dsh | ❌ | ❌ | 2 skills, `openviking-memory` and `openviking-skills` (own isolated `ctx.skills` provider) | ❌ | `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it || pi | ✅ `ctx.ui.setStatus` | ✅ `/viking` `/viking commit` | None | ✅ | `e2e-live.sh` || openclaw | ❌ | ✅ 5 commands (`/add-resource`, `/add-skill`, `/ov-search`, `/ov-query-config`, `/ov-recall-trace`) | 3 skills shipped with the plugin | ✅ (Key role detection, version compatibility checks, and a `status` command) | Gateway HTTP routes for visualizing recall traces; feature-gated RPCs; health-check script |@@ -603,9 +603,9 @@ Each card serves as a quick-reference entry point. It records only the facts and## opencode- **Integration docs**: [OpenCode Plugin](./10-opencode.md)-- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 8 plugin hooks: config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. `tool.execute.before` denies read/glob/grep calls whose path is a `viking://` URI, and `tool.execute.after` appends a notice to the output of a bash command that carries one. Version 0.4.1.-- **Capability highlights**: The `dispose` hook covers all four standard shutdown paths (on hosts ≥1.15.11). The repository list is injected into the system prompt ([§3.2.3](#_3-2-3-profile-opening-injection)). It boasts the richest host event surface of any integration, with `session.idle`, `compacted`, `deleted`, and `error` each carrying their own specific semantics.-- **Behavior notes**: Features a `commitTokenThreshold` of 20000 (positive values only; 0 falls back to the default) and a commit timeout of 30000ms. A single host compaction equates to two commits. Within the `dispose` hook's 5-second host budget, a slow commit spanning several sessions might be cut short, and the pending queue does not cover this scenario ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). On host versions below 1.15.11, the `dispose` hook is unavailable, meaning shutdowns do not trigger a commit. Leftover sessions are not flushed upon restart. The opening injection is attempted once per session ([§3.2.3](#_3-2-3-profile-opening-injection)). Finally, directory matching in `bypassSessionPatterns` does not apply to opencode, as the input does not carry a current working directory (cwd).+- **Form**: The npm plugin `@openviking/opencode-plugin` 0.5.0 supports OpenCode v1 ≥1.15.7 and v2 ≥2.0.15 from one entrypoint. v1 retains its existing hooks; v2 uses `setup(ctx)`, prompt/context/tool hooks, and structured lifecycle events. MCP tools keep the `openviking_*` prefix, with v2 explicitly setting `codemode:false`.+- **Capability highlights**: On v2, the prompt hook recalls once and stores context in user-message metadata; later model steps inject the same stored content, avoiding repeated requests and prompt-cache churn. At execution completion, `session.context()` supplies complete user, assistant, and tool messages for capture. The repository list remains in the system prompt ([§3.2.3](#_3-2-3-profile-opening-injection)).+- **Behavior notes**: `commitTokenThreshold` is 20000 and commit timeout is 30000ms. v2 checks the threshold after every succeeded, failed, or interrupted execution and force-commits on session deletion, completed compaction, and cleanup; a failed or interrupted execution retains state. v2 handles only sessions of its own location and stores its capture cursor in plugin storage. v2 cleanup runs after 60 minutes of inactivity, service shutdown, or local-plugin hot reload. v2 has no toast API and logs notices instead. Opening injection is attempted once per session ([§3.2.3](#_3-2-3-profile-opening-injection)).- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.opencode`), and the workspace files.- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | subagent [§3.3.5](#_3-3-5-subagent-session-comparison).diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.mdindex da7082a23..ae2b2ac95 100644--- a/docs/zh/agent-integrations/10-opencode.md+++ b/docs/zh/agent-integrations/10-opencode.md@@ -8,7 +8,7 @@## 前置条件-- [OpenCode](https://opencode.ai/)+- [OpenCode](https://opencode.ai/) 1.15.7+ 或 2.0.15+- Node.js 18+- OpenViking HTTP server- 如果服务端启用了鉴权,需要一个可用的 OpenViking API key@@ -60,6 +60,10 @@ opencode已有 `~/.config/opencode/opencode.json` 时,不要覆盖原文件;只把 `"@openviking/opencode-plugin"` 合并到已有的 `plugin` 数组。OpenCode 启动时会自动下载这个 npm 包,插件会自动注册它的 MCP server。+OpenCode 2 使用同一个包:v2 调用 `setup()`,OpenCode 1 调用 `server()`。OpenCode 2 会把 `"plugin"` 规范化为 `"plugins"`,因此安装器继续写兼容 v1/v2 的 `"plugin"`;不要为了 v2 手工改写现有配置。不需要安装 OpenCode skill。++在 OpenCode 2 中,插件把 MCP server 设为 `codemode: false`,所以工具仍以 `openviking_*` 直接暴露,不会收进 Code Mode。OpenCode 2 没有插件 toast API,服务不可用等信息只写入插件日志。+### 源码安装如果当前环境不能通过 package 安装:@@ -151,6 +155,10 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`+OpenCode 2 在每次 execution 结束时抓取本轮用户消息、助手回复和工具结果,并在压缩前补齐即将移出上下文的对话;达到 token 阈值时提交,compaction、session 删除和插件 cleanup 会强制提交。OpenCode 2 会在无活动 60 分钟、服务停止或本地插件热重载时执行 cleanup。++OpenCode 1.15.7 不会调用插件 dispose。v1 的短时 CLI 运行也可能在异步捕获完成前退出,这一行为在 v2 适配前已存在。使用常驻 v1 服务可以让 idle 捕获完成;OpenCode 1.18.32 会在 instance dispose 时调用插件的 dispose。+可以让 OpenCode 搜索或浏览 OpenViking memory。运行时状态和错误日志会写入:```bash@@ -162,7 +170,7 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`| 问题 | 排查方向 ||------|----------|-| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 引用了 `@openviking/opencode-plugin`;源码安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 |+| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 的 `plugin` 数组引用了 `@openviking/opencode-plugin`;源码安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 || 加载时报找不到 `lib/shared/*.mjs` | 源码复制前没有运行 `sync.mjs`。在仓库根目录运行 `node examples/memory-plugin-shared/sync.mjs` 后重新复制 `lib/` || MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量;`OPENVIKING_CLI_CONFIG_FILE` 可让插件改读另一份 ovcli.conf || OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex 3b60abdfa..fd5fcaa2f 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -57,7 +57,7 @@| trae / trae-cn | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) | ❌ | ✅ | ❌ || zcode | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) | ❌ | ✅ | ❌ || kimicode | 7 个原生 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),首次成功 prompt 加载 | ❌(PreCompact 只捕获/commit) | ✅ | ❌ |-| opencode | 8 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) + repo 列表进 system prompt | ❌(compacting 前后各 commit 一次) | ✅ | ❌(有 toast) |+| opencode | v1/v2 双栈 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200) + repo 列表进 system prompt | ❌(只在压缩完成后 commit) | ✅ | ❌ || dsh | Cordis 原生插件(同进程)+ MCP 代理 + skill | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),每 session 一次 | ❌ | ✅ | ❌ || pi | 原生扩展(9 事件) | ✅ | ✅ | ❌ | ✅(10000)+ `<available-skills>`(1200),进 systemPrompt 每轮重拼 | ✅ **takeover**(默认开) | ✅ | ✅ || openclaw | context-engine 插件(`ownsCompaction:true`) | ✅ | ❌(走 `/find`,该接口无 session_id 字段) | ❌ | ❌ | ✅ **ContextEngine 全接管** | ❌ 失败轮次不重放 | ❌ |@@ -285,7 +285,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处| cursor | `beforeSubmitPrompt` | prompt 原文;基于事件 id 与 500ms 窗口去重,同 promptHash 复用缓存块 | ✅ `cu-` | A | `additional_context` | ❌ || trae / trae-cn | `UserPromptSubmit` | 剥离历史注入块后的 prompt(只认 `input.prompt`) | ✅ `tr-`/`trcn-` | A | `additionalContext` | ❌ || zcode | `UserPromptSubmit` | 剥离三类注入块(含 `<system-reminder>`) | ✅ `zc-` | A | `additionalContext`(严格 JSON) | ❌ |-| opencode | 每条 `chat.message` 中的 user 消息 | 拼接非 synthetic text part;若正文已含 `<openviking-context` 则跳过本轮召回 | ✅ `oc-` | A(timeoutMs=30000) | 合成 synthetic part 并 `unshift` 到 parts 最前 | ❌ |+| opencode | v1:每条 `chat.message`;v2:每条 `prompt` | v1 拼接非 synthetic text part;v2 直接读取 prompt text | ✅ `oc-` | A(timeoutMs=30000) | v1 合成 synthetic part;v2 写入消息 metadata,并在 context hook 中插到该 user message 前 | ❌ || dsh | `agent/pre-step` waterfall(先 await next 再 append) | claimed batch 全部消息(过滤自身注入的内容) | ✅ `dsh-` | A | 借由 `createUserMessage` append 到 `decision.messages` 尾部(source: plugin/openviking-memory) | ❌ || pi | `before_agent_start` 阶段排队;在 `context` 事件内检索(当前轮 prompt 拿当前轮记忆) | prompt 原文 | ✅ `pi-`(会话未建立时不带) | A | 前置到最后一条真实 user 消息(通过 `<openviking-context` 幂等检测) | ❌ || openclaw | context-engine transformContext assemble(设有 7 道 passthrough 门) | 最后一条 user 消息纯 text,清洗后截 4000 字符 | ❌(`/find` 无该字段) | `/find` | 以 `<relevant-memories>` + `Source: openviking-auto-recall` 格式前置进最后一条 user 消息 | ❌ |@@ -342,7 +342,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处### 3.3.1 机制底座-- **写入路径**:JS 系统一通过 `batch-send.mjs` 处理(对应接口 `POST /messages/batch`,每批最多 100 条,与服务端的 `max_length=100` 限制保持一致;若遇 404/405 错误则降级为逐条发送)。增量游标由各家自行实现(cc 按 transcript turn 序号计算,codex 机制相同;cursor 采用 `sha256(index+role+content)`;zcode 基于 rollout 的 `turn_id`;opencode 依赖事件流 Map;dsh 基于事件白名单;pi 依据 branch 条目水位;hermes 则按当前轮切片)。+- **写入路径**:JS 系统一通过 `batch-send.mjs` 处理(对应接口 `POST /messages/batch`,每批最多 100 条,与服务端的 `max_length=100` 限制保持一致;若遇 404/405 错误则降级为逐条发送)。增量游标由各家自行实现(cc 按 transcript turn 序号计算,codex 机制相同;cursor 采用 `sha256(index+role+content)`;zcode 基于 rollout 的 `turn_id`;opencode v1 依赖事件流 Map,v2 在 execution 结束时读取 context 并按 message id 推进游标;dsh 基于事件白名单;pi 依据 branch 条目水位;hermes 则按当前轮切片)。- **commit 是客户端触发的**(详见 [§2.3](#_2-3-服务端会话与-commit-语义)):服务端默认不自动 commit。下表所有的"阈值/触发"条件,均指客户端逻辑。- **keep_recent_count 差异**(即 commit 后给宿主留多少 live tail):服务端默认值为 0。各家传参如下:cc/codex 阈值提交传 10;cursor、trae×2、zcode 发空 body `{}`,即传 0(每次均为全量归档);opencode 传 10;dsh 传 10;pi 在非 takeover 模式传 10,takeover 模式传 3(本地含义是"保留 3 个用户轮",而服务端按消息条数解释,实际保留更少);openclaw 在 afterTurn 阈值触发时传 10,在 compact/reset/memory_store 操作时传 0;hermes 恒定传 0。- **写路径 detach**(`async-writer.mjs`,cc/codex/zcode 的 Stop 默认开):drain stdin → spawn detached worker → approve → write payload → unref(注:spawn 失败时尚未 approve,回落同步恰好只输出一次)。detached worker 自成进程组,不受终端信号波及——这是保证 cc 在关闭链路时具有高可靠性、zcode 在按下 Ctrl+C 时不丢失写入数据的关键机制。附带效果:执行 detach 后,Stop 的 `appended N turn(s)` 提示将不再展示(设置 `OPENVIKING_WRITE_PATH_ASYNC=0` 可恢复该提示)。@@ -356,7 +356,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处| cursor | stop:`capturedSinceCommit ≥ 8`(按消息条数计算,≈4 轮问答;纯客户端计数),keep 0 | sessionEnd:已注册该事件(但实践中不触达,见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)) | preCompact:无条件触发 || trae / trae-cn | 每个有内容的 Stop 都 commit(无阈值),keep 0 | — | 无(上游无 PreCompact 事件) || zcode | 同 trae(每 Stop 都 commit,keep 0;rollout 增量游标保守推进,若有漏掉的轮次,将在同会话的下个 Stop 补齐) | — | 无(上游无 PreCompact 事件) |-| opencode | `session.idle` 路径:flush 执行后,需满足 `pending_tokens ≥ 20000` 才 commit,keep 10 | `session.deleted` / `session.error`:强制 commit;dispose:强制 commit | 在 `experimental.session.compacting` 前与 `session.compacted` 后各触发一次(即一次宿主压缩 = 两次 commit) |+| opencode | v1 `session.idle` / v2 execution 结束:flush 后 `pending_tokens ≥ 20000` 才 commit,keep 10 | `session.deleted` / v1 `session.error`:强制 commit;v1 dispose / v2 cleanup:强制 commit | v1 在 compacting 前与 compacted 后触发;v2 只在 `session.compaction.ended` 后触发 || dsh | `turn/end`:`pending_tokens ≥ 20000`(30s 超时),keep 10 | teardown(见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)) | 无(不监听 compaction 事件) || pi(takeover 默认开) | `onTurnSynced`:本地估算 `pendingTokens ≥ 30000` 且 `lastSeenUserTurns > 3` 时,执行 commitAndAdvance(keep 3;overview 15×2s 轮询,拿不到则边界不推进,但 pendingTokens 会清零,重新累计后重试) | 手动执行 `/viking commit` | `session_before_compact`(需 `firstKeptEntryId` 非空) || pi(takeover off) | syncBranch 执行后:服务端 `pending_tokens ≥ 20000`,keep 10 | `session_shutdown`:无条件 commit;手动执行 `/viking commit` | `session_before_compact`:无条件 commit |@@ -378,7 +378,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处| cursor | **—**(chat 关闭 / new-chat 无事件) | **—** | **—** | **—**(`sessionEnd` 已注册且仅 window_close 触发,但此时宿主已销毁 shell-exec host,hook 在 spawn 前中止) | **—** | 结束在 <8 条消息水位的会话,尾部依赖同一会话的后续消息触发 commit || trae / trae-cn | **—**(无 session-end 类事件) | **—** | **—** | **—** | **—** | 每 Stop 已 commit,最大待归档量 = 最后一轮 in-flight || zcode | **—**(无 session-end 类事件) | **C\*** | **—** | **—** | **—** | C\* 前提:Ctrl+C 时该轮 Stop 已触发(detached worker 照常写完);每 Stop 已 commit,漏掉的轮次靠 rollout 游标在同一会话的下个 Stop 补回 |-| opencode | **C\***(≥1.15.11 的 `dispose` → `flushAll({commit:true})`,覆盖全部四种关闭;<1.15.11 无该 hook → —) | **C\*** | **C\*** | **C\*** | **—** | C\* 前提:宿主 shutdown 预算 5s,单会话最坏 health 5s + batch 10s + commit 30s,多会话串行累加——超预算的 commit 会被截断,且 pending queue 不覆盖此场景(fetch 未 settle 不入队);重启后 `init()` 不主动 flush 遗留会话 |+| opencode | **C\***(v1 ≥1.15.11 的 `dispose` 或 v2 cleanup → `flushAll({commit:true})`) | **C\*** | **C\*** | **C\*** | **—** | C\* 前提:宿主给 cleanup 的时间有限,慢请求或多个会话串行提交可能被截断;v2 会在无活动 60 分钟、服务停止和本地插件热重载时触发 cleanup || dsh | **C**(Cordis teardown → 每 session 一次 3s 超时 commit,无阈值) | **C**(第一次;第二次 Ctrl+C 强退 → —) | **C** | **—**(无 SIGHUP 监听) | **—** | teardown commit 与阈值 commit 共享同一条串行写链,5s 进程 grace 内前方有慢请求时可能挤不进;web 形态关浏览器 tab 不触发 teardown || pi(takeover 默认) | **—**(`session_shutdown` 全关闭方式都触发且被 await,handler 持久化本地 takeover 状态,不 commit) | **—** | **—** | **—** | **—** | 下次续跑攒满 30000,或手动 `/viking commit` || pi(takeover off) | **C**(`await sync.commit()`,失败入 pending 队列) | **C** | **C** | **C** | **—** | — |@@ -410,7 +410,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处|---|---|| claude-code | 隔离最完整:SubagentStart 派生 `cc-<sid>__subagent-<agent_id>` 独立会话,SubagentStop 读 subagent transcript 推送后无条件 commit 并清 state || codex / trae-cli | 不单独建会话:subagent 输出(`agent_message` / `sub_agent_activity`)折叠进主会话的 assistant/tool part |-| opencode | `oc-<parent>__subagent-<child>` 挂在父命名空间下;开场注入跳过 subagent(召回不跳过);ID 派生依赖事件顺序——`chat.message` 先于 `session.created` 到达时会丢 `__subagent-` 后缀 |+| opencode | `oc-<parent>__subagent-<child>` 挂在父命名空间下;开场注入跳过 subagent(召回不跳过);v2 从 `session.created` 的 `parentID` 建立映射,再在 execution 结束时读取 context || dsh | 每个 subagent = 独立 `dsh-<id>` 会话,父子关系不保留;N 个 subagent = N 份 profile 注入 + N 个独立会话 || hermes | `delegate_task` 传 `skip_memory=True` → subagent 不接 OV(无会话/召回/工具面);子任务产出不回灌 || cursor / trae×2 / zcode / pi / openclaw | 无 subagent 处理(有独立会话 id 就各自成会话,否则混入主会话;openclaw 可用 `bypassSessionPatterns` 屏蔽) |@@ -425,7 +425,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处| claude-code | 不接管 | PreCompact 同步 commit(唯一不 detach 的写路径,因为 CC 随后立刻重写 transcript) | `source="compact"` 的 SessionStart 会把 OV 的 `latest_archive_overview` + ≤5 条 abstracts 重新注回 || codex / trae-cli | 不接管 | PreCompact 补齐未捕获轮次 → 全量 commit → `ovSessionId=null`(补齐不全时不 commit,留待重试);无 PostCompact 接线,依靠 Stop 的转录收缩做防御性纠偏 | resume 时注入 archive digest || cursor / trae×2 / zcode | 不接管 | cursor:preCompact 无条件 commit(trae×2/zcode 上游无该事件) | — |-| opencode | 不接管 | compacting 前 flush+commit | `session.compacted` 触发后再 flush+commit(共两次) |+| opencode | 不接管 | v1 compacting 前 flush+commit;v2 在压缩前捕获对话 | v1 `session.compacted` 再提交一次;v2 `session.compaction.ended` 后提交一次 || dsh | 不感知(不监听 compaction 事件;注入走 pre-step user 消息,随宿主压缩一起收缩,profile 不重投) | — | — || pi | **takeover 双层接管**(默认开,[§3.4.2](#_3-4-2-pi-takeover)) | `session_before_compact`:flush → commit → pollOverview。成功则返回自定义 compaction 摘要覆盖 pi 的;失败则 fail-open 回退到 pi 默认压缩 | 成功后 resetBoundary || openclaw | **全接管**:`ownsCompaction: true`,宿主不再跑自己的摘要([§3.4.3](#_3-4-3-openclaw-contextengine)) | `compact()` = commit(wait=true, keep 0) → 读回 overview 当 summary | 主 assemble 用 `[Session History Summary]` 重建上下文 |@@ -487,7 +487,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可| claude-code | 各 hook catch→approve,不阻塞;session-start 时连 pending 重放都跳过 | context-face 6h + host-cli 探测 7d + health 5s | 无(靠 pending 重放);peer_scope 降级 1 次;batch→逐条 | 否(uri-guard deny 是设计意图) || codex / trae-cli | 各 hook catch→noop | context-face 6h + 压缩器 runtime_failed(至下次启动) | 同上(靠 pending 重放,SessionStart 触发) | 否 || cursor/trae×2/zcode | fetch 吞成 status:0,catch 返回空注入;锁 5s 拿不到则静默跳过 | context-face 6h(服务端整体不可达时无负缓存,每轮等满 15s) | 无 | 否 |-| opencode | 各路径 catch→WARN;`event`/`dispose` hook 无 try/catch(不可重试的 commit 失败会冒泡宿主) | 仅 context-face 6h;`/health` 无缓存(每轮一次往返) | 无同步重试;MCP 代理 401/403、400/404 各一次 | 基本否(event/dispose 例外) |+| opencode | recall、context、after-tool、事件循环与 cleanup 失败均 catch→WARN;URI guard 的预期拒绝仍会返回给模型 | 仅 context-face 6h;`/health` 无缓存 | 无同步重试;MCP 代理 401/403、400/404 各一次 | 否(URI guard deny 是设计意图) || dsh | client 全吞异常;`ensureState` 失败不缓存(服务端不可达时每 pre-step 两次 health 各 5s) | context-face 6h + user-space 缓存进程内不过期 | 无;pending 跨进程重放 3 次 | 是(pre-step 串行 profile+recall;session/flush 阻塞) || pi | health 失败时 start() 提前返回,本轮也不注册工具,此后每 prompt 静默重试连接;`/mcp` 握手单独失败(401/403、超时、server 无 `/mcp`)不影响启动:召回、同步、takeover 照常,状态栏显示 `tools ✗`,`/viking` 打印完整错误 | context-face 6h;握手没有负缓存,一直失败就每轮重试一次,最多占满 5s 握手预算才轮到排队召回 | hook 侧无,只有 pending queue;传输失败后丢弃当前 MCP 连接,下次调用重新连接;失败的工具调用不会自动重放 | 部分(session_shutdown 被 await:takeover 近 0、非 takeover 最坏 30s,外加关闭 MCP 客户端;turn_end 网络异常时逐条各等 10s) || openclaw | client 构造永不失败;health 吞异常;召回 500ms precheck 失败跳过 | 无负缓存(每轮一次 500ms health 预检) | 无(单次 fetch);commit/afterTurn 的 Phase2 轮询 | 否(`memory_store` 重抛例外;`compact()` 最长阻塞 5 分钟) |@@ -507,7 +507,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可| cursor | ❌ | ❌ | rule(alwaysApply)+ 2 个 skill(`openviking-memory`、`openviking-skills`) | ❌(共用安装器 TUI) | 独立 uri-guard,不受插件开关控制 || trae/trae-cn | ❌ | ❌ | 无 | ❌ | — || zcode | ❌ | ❌ | 无 | ❌ | — |-| opencode | ❌(有 toast) | ❌ | 无(设计上不提供) | ✅ | — |+| opencode | ❌ | ❌ | 无(设计上不提供) | ✅ | v1 有 toast;v2 只写日志 || dsh | ❌ | ❌ | 2 个 skill:`openviking-memory` 与 `openviking-skills`(独立的 `ctx.skills` provider) | ❌ | `ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发 || pi | ✅ `ctx.ui.setStatus` | ✅ `/viking` `/viking commit` | 无 | ✅ | e2e-live.sh || openclaw | ❌ | ✅ 5 个(/add-resource /add-skill /ov-search /ov-query-config /ov-recall-trace) | 3 skill 随插件分发 | ✅(key 角色探测 + 版本兼容检查 + `status` 命令) | Gateway HTTP 路由做 recall trace 可视化;feature-gate RPC;健康检查脚本 |@@ -585,9 +585,9 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## opencode- **集成文档**:[OpenCode 插件](./10-opencode.md)-- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。8 个 plugin hook:config / event / tool.execute.before / tool.execute.after / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。tool.execute.before 拒绝路径是 `viking://` URI 的 read/glob/grep;bash 命令带 `viking://` URI 时,tool.execute.after 在输出末尾追加提示。版本 0.4.1。-- **能力亮点**:`dispose` hook 覆盖全部四种常规关闭方式(宿主 ≥1.15.11);repo 列表进 system prompt([§3.2.3](#_3-2-3-profile-开场注入));宿主事件面最丰富(session.idle/compacted/deleted/error 各有语义)。-- **行为要点**:`commitTokenThreshold=20000`(取正数,0 回落默认值);commit 超时 30000ms;一次宿主压缩 = 两次 commit;dispose 的 5s 宿主预算下,多会话慢 commit 可能被截断,且 pending queue 不覆盖此场景([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));<1.15.11 无 dispose 时关闭不 commit;重启后不主动 flush 遗留会话;开场注入每会话尝试一次([§3.2.3](#_3-2-3-profile-开场注入));`bypassSessionPatterns` 的目录匹配在 opencode 上不适用(input 无 cwd)。+- **形态**:npm 插件 `@openviking/opencode-plugin` 0.5.0,同一入口支持 OpenCode v1 ≥1.15.7 与 v2 ≥2.0.15。v1 保留原有 hooks;v2 使用 `setup(ctx)`、prompt/context/tool hooks 和结构化生命周期事件。MCP 工具保持 `openviking_*` 前缀,v2 显式设置 `codemode:false`。+- **能力亮点**:v2 在 prompt hook 只召回一次并把上下文存进用户消息 metadata,后续每个模型 step 注入同一份内容,避免重复请求和 prompt cache 失效;execution 结束后通过 `session.context()` 捕获完整的用户、助手和工具消息。repo 列表继续进入 system prompt([§3.2.3](#_3-2-3-profile-开场注入))。+- **行为要点**:`commitTokenThreshold=20000`,commit 超时 30000ms。v2 在每次 execution 结束(succeeded、failed、interrupted)后按阈值提交,session 删除、compaction ended 和 cleanup 时强制提交;failed 与 interrupted 都保留状态。v2 只处理本 location 的 session,捕获游标存放在插件 storage 中。v2 cleanup 会在 60 分钟无活动、服务停止和本地插件热重载时触发;v2 没有 toast API,只写日志。开场注入每会话尝试一次([§3.2.3](#_3-2-3-profile-开场注入))。- **配置**:env + ovcli.conf `plugin.opencode` + workspace 文件。- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |subagent [§3.3.5](#_3-3-5-subagent-会话对照)。diff --git a/examples/memory-plugin-shared/recall-session-wiring.test.mjs b/examples/memory-plugin-shared/recall-session-wiring.test.mjsindex 500df0b89..45ac1d389 100644--- a/examples/memory-plugin-shared/recall-session-wiring.test.mjs+++ b/examples/memory-plugin-shared/recall-session-wiring.test.mjs@@ -57,7 +57,7 @@ test("pi wires the sync manager into the recall manager", async () => {});test("OpenCode passes the session manager into the recall component", async () => {- const source = await readFile(join(ROOT, "examples", "opencode-plugin", "index.mjs"), "utf-8");+ const source = await readFile(join(ROOT, "examples", "opencode-plugin", "lib", "plugin-runtime.mjs"), "utf-8");assert.match(source, /createMemoryRecall\(\{\s*config,\s*sessionManager\s*\}\)/);});diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex d55b57d4c..6924017ff 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -11,7 +11,7 @@需要先准备:-- OpenCode+- OpenCode 1.15.7+ 或 OpenCode 2.0.15+- OpenViking HTTP Server- Node.js 18+- 如果服务端启用了认证,需要可用的 OpenViking API Key@@ -38,6 +38,8 @@ curl http://localhost:1933/health}```+这份 `plugin` 配置同时兼容 v1 和 v2;v2 会在加载时规范化为原生的 `plugins`,无需手工迁移配置。+## 安装方式二:源码安装用于开发调试或 PR 测试。OpenCode 推荐插件目录:diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex 4380cea30..c5d7c1ee1 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -11,7 +11,7 @@ This is the only OpenCode plugin example maintained in this repository. It doesPrepare the following first:-- OpenCode+- OpenCode 1.15.7+ or OpenCode 2.0.15+- OpenViking HTTP Server- Node.js 18+- A valid OpenViking API key if authentication is enabled on the server@@ -38,6 +38,8 @@ Normal users are recommended to enable it through OpenCode's package plugin mech}```+This `plugin` entry works on both v1 and v2. OpenCode v2 normalizes it to the native `plugins` form at load time, so no manual config migration is required.+## Installation Method 2: Source InstallUse this method for development, debugging, or PR testing. OpenCode's recommended plugin directory is:diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex bb5051549..3e226ca7b 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -17,6 +17,7 @@ The plugin uses OpenCode hooks for lifecycle behavior and registers OpenViking's- Exposes the same OpenViking MCP tools used by the Claude Code and Codex memory plugins.- Maps each OpenCode session to an OpenViking session.- Captures user and assistant text messages into OpenViking.+- On OpenCode v2, reads the structured session context at execution boundaries so tool calls and results are captured too.- 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 `openviking_read`, `openviking_glob`, or `openviking_search`. Shell commands that carry a `viking://` URI still run, with a notice appended to their output.@@ -50,11 +51,13 @@ There is intentionally no `skills/openviking/SKILL.md`. The tool surface comes f## Requirements-- OpenCode+- OpenCode 1.15.7+ or OpenCode 2.0.15+- OpenViking HTTP server- Node.js 18+- An OpenViking API key if your server requires authentication+The same package serves both plugin APIs. OpenCode 1 calls `server()` (or the named `OpenVikingPlugin` export), while OpenCode 2 calls `setup()`. The v2 entrypoint does not import `@opencode/plugin`, so a source install on OpenCode 1 still loads. OpenCode 2 normalizes the installer's `"plugin"` key to `"plugins"`; keep `"plugin"` in shared v1/v2 configuration. On v2, the bundled MCP server uses `codemode: false`, preserving the documented `openviking_*` tool names.+Start OpenViking first:```bash@@ -202,6 +205,8 @@ call and points it to the OpenViking MCP tools. A `bash` command that contains aan HTTP payload); the command runs and the plugin appends a notice naming theMCP tools to its output.+OpenCode v2 has no plugin toast API. Service availability and other non-fatal notices are written to `openviking-memory.log`. The plugin captures the transcript before compaction discards it, checks the commit threshold after every execution (succeeded, failed, or interrupted), and forces a commit after completed compaction, session deletion, and cleanup. Each plugin instance handles only the sessions of its own location, and keeps its capture cursor in OpenCode plugin storage so a reloaded instance does not resend earlier turns.+## MCP ToolsOpenCode sees the OpenViking MCP server as `openviking`, so tool names are namespaced with `openviking_`.diff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjsindex a02a3edbc..85d0f1306 100644--- a/examples/opencode-plugin/index.mjs+++ b/examples/opencode-plugin/index.mjs@@ -1,41 +1,30 @@import { dirname } from "path"import { fileURLToPath } from "url"-import { initializeRuntime } from "./lib/runtime.mjs"-import { createRepoContext } from "./lib/repo-context.mjs"-import { createMemorySessionManager } from "./lib/memory-session.mjs"-import { createMemoryRecall } from "./lib/memory-recall.mjs"-import { createSessionInject } from "./lib/session-inject.mjs"-import { createVikingUriGuard, createVikingUriNotice } from "./lib/viking-uri-guard.mjs"+import { createOpenVikingRuntime } from "./lib/plugin-runtime.mjs"+import { startV2Plugin } from "./lib/v2-plugin.mjs"import { injectOpenVikingMcpConfig } from "./lib/mcp-config.mjs"-import { loadConfig, resolveDataDir } from "./lib/config.mjs"import { isRecallEnabled } from "./lib/shared/recall-core.mjs"-import { initLogger, log, makeToast } from "./lib/utils.mjs"+import { log } from "./lib/utils.mjs"const pluginRoot = dirname(fileURLToPath(import.meta.url))-export async function OpenVikingPlugin({ client, directory }) {- const config = loadConfig(pluginRoot, directory)- const dataDir = resolveDataDir(pluginRoot, config)- initLogger(dataDir)-- if (!config.enabled) {- log("INFO", "plugin", "OpenViking plugin is disabled in configuration")- return {}- }-- const repoContext = createRepoContext({ config })- const sessionManager = createMemorySessionManager({ config, pluginRoot: dataDir })- const recall = createMemoryRecall({ config, sessionManager })- const sessionInject = createSessionInject({ config, sessionManager })- const vikingUriGuard = createVikingUriGuard()- const vikingUriNotice = createVikingUriNotice()+export async function OpenVikingPlugin({ client, directory } = {}) {+ const runtime = createOpenVikingRuntime({ client, directory, pluginRoot })+ if (!runtime) return {}+ await runtime.ready+ return v1Hooks(runtime)+}- await sessionManager.init()- const toast = makeToast(client)- Promise.resolve().then(async () => {- const ready = await initializeRuntime(config, client)- if (ready) await repoContext.refreshRepos({ force: true })- })+function v1Hooks(runtime) {+ const {+ config,+ sessionManager,+ repoContext,+ recall,+ sessionInject,+ vikingUriGuard,+ vikingUriNotice,+ } = runtimereturn {config: async (opencodeConfig) => {@@ -92,4 +81,17 @@ export async function OpenVikingPlugin({ client, directory }) {}}-export default OpenVikingPlugin+const OpenVikingV2Plugin = {+ id: "openviking",+ async setup(ctx) {+ const directory = ctx?.location?.project?.directory || ctx?.location?.directory+ const runtime = createOpenVikingRuntime({ directory, pluginRoot })+ if (!runtime) return+ return startV2Plugin(ctx, runtime, { pluginRoot })+ },+ async server(input) {+ return OpenVikingPlugin(input)+ },+}++export default OpenVikingV2Plugindiff --git a/examples/opencode-plugin/lib/mcp-config.mjs b/examples/opencode-plugin/lib/mcp-config.mjsindex 4a6d67512..3e9210f64 100644--- a/examples/opencode-plugin/lib/mcp-config.mjs+++ b/examples/opencode-plugin/lib/mcp-config.mjs@@ -11,6 +11,19 @@ export function createOpenVikingMcpConfig(pluginRoot) {}}+export function createOpenVikingV2McpConfig(pluginRoot) {+ return {+ type: "local",+ command: ["node", resolvePath(pluginRoot, "servers", "mcp-proxy.mjs")],+ codemode: false,+ timeout: {+ startup: 15000,+ catalog: 15000,+ execution: 15000,+ },+ }+}+export function injectOpenVikingMcpConfig(config, pluginRoot, enabled = true) {if (!config || typeof config !== "object") return falseif (!enabled) return falsediff --git a/examples/opencode-plugin/lib/memory-recall.mjs b/examples/opencode-plugin/lib/memory-recall.mjsindex 6708d7c64..befde8d62 100644--- a/examples/opencode-plugin/lib/memory-recall.mjs+++ b/examples/opencode-plugin/lib/memory-recall.mjs@@ -3,12 +3,12 @@ import { isBypassed } from "./shared/session-model.mjs"import { effectivePeerId, fetchJSON, log } from "./utils.mjs"export function createMemoryRecall({ config, sessionManager }) {- async function injectRelevantMemories(input, output) {+ async function buildRelevantMemories(input, parts) {if (!isRecallEnabled(config)) return- const query = extractCurrentUserText(output.parts ?? [])+ const query = extractCurrentUserText(parts ?? [])if (!query) returnif (query.length < config.minQueryLength) return- const sessionID = input.sessionID ?? output.message?.sessionID+ const sessionID = input.sessionIDif (isBypassed(config, {sessionId: sessionID,cwd: input.directory ?? input.cwd,@@ -34,14 +34,20 @@ export function createMemoryRecall({ config, sessionManager }) {log: (stage, data) => log("DEBUG", "recall", stage, data),},)- if (!block) return+ return block || undefined+ }- if (prependSyntheticRecallPart(input, output, block)) {+ async function injectRelevantMemories(input, output) {+ const block = await buildRelevantMemories({+ ...input,+ sessionID: input.sessionID ?? output.message?.sessionID,+ }, output.parts)+ if (block && prependSyntheticRecallPart(input, output, block)) {log("INFO", "recall", "Injected OpenViking context")}}- return { injectRelevantMemories }+ return { buildRelevantMemories, injectRelevantMemories }}export function extractCurrentUserText(parts) {diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjsindex 28ae4eea1..8286af734 100644--- a/examples/opencode-plugin/lib/memory-session.mjs+++ b/examples/opencode-plugin/lib/memory-session.mjs@@ -31,6 +31,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {const statePath = path.join(pluginRoot, "openviking-session-state.json")const oldSessionMapPath = path.join(pluginRoot, "openviking-session-map.json")let saveTimer = null+ let initBackground = Promise.resolve()// Serialize saves: concurrent saveState() calls (a debounced save racing// with flushAll / flushSession / session deletion) all share the same// `${statePath}.tmp` temp file, so one rename can fail with ENOENT after@@ -46,16 +47,24 @@ export function createMemorySessionManager({ config, pluginRoot }) {return run}- async function init() {- if (isCaptureEnabled(config)) await migrateLegacySessionMap()+ async function init({ deferNetwork = false } = {}) {await loadState()- const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })- if (health.ok) {+ initBackground = Promise.resolve().then(async () => {+ if (isCaptureEnabled(config)) await migrateLegacySessionMap()+ const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })+ if (!health.ok) returnawait replayPending((endpoint, init = {}, options = {}) => fetchJSON(config, endpoint, init, options),(stage, data) => log("DEBUG", "pending", stage, data),)- }+ }).catch((error) => {+ log("WARN", "pending", "Pending replay failed during initialization", { error: error?.message })+ })+ if (!deferNetwork) await initBackground+ }++ async function waitForBackground() {+ await initBackground}async function loadState() {@@ -306,6 +315,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {return {init,+ waitForBackground,handleEvent,getMappedSessionId,commitSession,diff --git a/examples/opencode-plugin/lib/plugin-runtime.mjs b/examples/opencode-plugin/lib/plugin-runtime.mjsnew file mode 100644index 000000000..fd80f2799--- /dev/null+++ b/examples/opencode-plugin/lib/plugin-runtime.mjs@@ -0,0 +1,51 @@+import { createRepoContext } from "./repo-context.mjs"+import { createMemorySessionManager } from "./memory-session.mjs"+import { createMemoryRecall } from "./memory-recall.mjs"+import { createSessionInject } from "./session-inject.mjs"+import { createVikingUriGuard, createVikingUriNotice } from "./viking-uri-guard.mjs"+import { loadConfig, resolveDataDir } from "./config.mjs"+import { initializeRuntime } from "./runtime.mjs"+import { initLogger, log } from "./utils.mjs"++export function createOpenVikingRuntime({ client, directory, pluginRoot }) {+ const config = loadConfig(pluginRoot, directory)+ const dataDir = resolveDataDir(pluginRoot, config)+ initLogger(dataDir)++ if (!config.enabled) {+ log("INFO", "plugin", "OpenViking plugin is disabled in configuration")+ return null+ }++ const repoContext = createRepoContext({ config })+ const sessionManager = createMemorySessionManager({ config, pluginRoot: dataDir })+ const recall = createMemoryRecall({ config, sessionManager })+ const sessionInject = createSessionInject({ config, sessionManager })+ const vikingUriGuard = createVikingUriGuard()+ const vikingUriNotice = createVikingUriNotice()++ // OpenCode v2 has no v1 client object and waits for setup before accepting+ // the first prompt. Load local state before hooks run, but keep health and+ // pending replay off that activation path.+ const ready = sessionManager.init({ deferNetwork: !client })+ const background = ready.then(async () => {+ const healthy = await initializeRuntime(config, client)+ if (healthy) await repoContext.refreshRepos({ force: true })+ }).catch((error) => {+ log("WARN", "plugin", "OpenViking runtime initialization failed", {+ error: error?.message ?? String(error),+ })+ })++ return {+ config,+ repoContext,+ sessionManager,+ recall,+ sessionInject,+ vikingUriGuard,+ vikingUriNotice,+ ready,+ background,+ }+}diff --git a/examples/opencode-plugin/lib/session-inject.mjs b/examples/opencode-plugin/lib/session-inject.mjsindex 9b6b6a379..f4b42c229 100644--- a/examples/opencode-plugin/lib/session-inject.mjs+++ b/examples/opencode-plugin/lib/session-inject.mjs@@ -4,10 +4,10 @@ import { effectivePeerId, fetchJSON, log } from "./utils.mjs"export function createSessionInject({ config, sessionManager }) {const injectedSessions = new Set()- async function injectSessionContext(input, output) {+ async function buildSessionContext(input) {if (config.noAutoInject) return false- const sessionID = input.sessionID ?? output.message?.sessionID- const messageID = input.messageID ?? output.message?.id+ const sessionID = input.sessionID+ const messageID = input.messageIDif (!sessionID || !messageID || injectedSessions.has(sessionID)) return falseconst ovSessionId = sessionManager.getMappedSessionId(sessionID)@@ -26,7 +26,7 @@ export function createSessionInject({ config, sessionManager }) {if (parts.length === 0) {injectedSessions.add(sessionID)- return false+ return undefined}const block = [@@ -35,14 +35,6 @@ export function createSessionInject({ config, sessionManager }) {"</openviking-context>",].join("\n")- output.parts.unshift({- id: `prt-ov-session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,- type: "text",- text: block,- synthetic: true,- sessionID,- messageID,- })injectedSessions.add(sessionID)log("INFO", "session-inject", "Injected OpenViking session context", {opencode_session: sessionID,@@ -50,10 +42,28 @@ export function createSessionInject({ config, sessionManager }) {hasProfile: Boolean(profile?.block),hasArchive: Boolean(archive),})+ return block+ }++ async function injectSessionContext(input, output) {+ const block = await buildSessionContext({+ ...input,+ sessionID: input.sessionID ?? output.message?.sessionID,+ messageID: input.messageID ?? output.message?.id,+ })+ if (!block) return false+ output.parts.unshift({+ id: `prt-ov-session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,+ type: "text",+ text: block,+ synthetic: true,+ sessionID: input.sessionID ?? output.message?.sessionID,+ messageID: input.messageID ?? output.message?.id,+ })return true}- return { injectSessionContext }+ return { buildSessionContext, injectSessionContext }}async function fetchArchiveBlock(fetcher, ovSessionId, tokenBudget) {diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex 24c264c93..ff760fd67 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -56,10 +56,12 @@ export function log(level, toolName, message, data) {}export function makeToast(client) {- return (message, variant = "warning") =>- client?.tui?.showToast?.({+ return (message, variant = "warning") => {+ const request = client?.tui?.showToast?.({body: { title: "OpenViking", message, variant, duration: 8000 },- }).catch(() => {})+ })+ return request?.catch?.(() => {})+ }}export function normalizeEndpoint(endpoint) {diff --git a/examples/opencode-plugin/lib/v2-events.mjs b/examples/opencode-plugin/lib/v2-events.mjsnew file mode 100644index 000000000..65dc028fc--- /dev/null+++ b/examples/opencode-plugin/lib/v2-events.mjs@@ -0,0 +1,102 @@+export function normalizeV2LifecycleEvent(event) {+ const type = event?.type+ const data = event?.data && typeof event.data === "object" ? event.data : {}+ const sessionID = data.sessionID ?? data.sessionId+ if (!type || !sessionID) return []++ if (type === "session.created") {+ return [sessionEvent("session.created", sessionID, { parentID: data.parentID })]+ }+ if (type === "session.deleted") {+ return [sessionEvent("session.deleted", sessionID)]+ }+ if (type === "session.compaction.ended") {+ return [sessionEvent("session.compacted", sessionID)]+ }+ // A failed execution ends one turn, not the session, so it keeps state like+ // the other terminal outcomes instead of taking v1's session.error path.+ if (+ type === "session.execution.succeeded" ||+ type === "session.execution.interrupted" ||+ type === "session.execution.failed"+ ) {+ return [sessionEvent("session.idle", sessionID)]+ }+ return []+}++export function contextMessageEvents(sessionID, message) {+ if (!sessionID || !message?.id) return []+ if (message.type === "user") {+ if (typeof message.text !== "string" || !message.text.trim()) return []+ return [+ messageUpdated(sessionID, message.id, "user"),+ partUpdated(sessionID, message.id, `${message.id}:text`, { type: "text", text: message.text }),+ ]+ }+ if (message.type !== "assistant") return []++ const events = [messageUpdated(sessionID, message.id, "assistant")]+ for (const [index, block] of (message.content ?? []).entries()) {+ const part = contentPart(block, index)+ if (part) events.push(partUpdated(sessionID, message.id, part.id, part))+ }+ return events.length > 1 ? events : []+}++function sessionEvent(type, sessionID, info = {}) {+ return {+ type,+ properties: { info: { id: sessionID, sessionID, ...info } },+ }+}++function contentPart(block, index) {+ if (!block || typeof block !== "object") return null+ // Reasoning is dropped, matching v1 parts and the shared capture filter.+ if (block.type === "text") {+ return {+ id: `text:${index}`,+ type: "text",+ text: typeof block.text === "string" ? block.text : "",+ }+ }+ if (block.type !== "tool") return null+ const output = toolContentText(block.state?.content) || errorText(block.state?.error)+ return {+ id: block.id || `tool:${index}`,+ type: "tool",+ callID: block.id,+ tool: block.name,+ state: block.state,+ output,+ }+}++function toolContentText(content) {+ if (!Array.isArray(content)) return ""+ return content+ .filter((item) => item?.type === "text" && typeof item.text === "string")+ .map((item) => item.text)+ .join("\n\n")+}++function errorText(error) {+ if (typeof error === "string") return error+ if (typeof error?.message === "string") return error.message+ return ""+}++function messageUpdated(sessionID, messageID, role) {+ return {+ type: "message.updated",+ properties: { info: { sessionID, id: messageID, role } },+ }+}++function partUpdated(sessionID, messageID, partId, part) {+ return {+ type: "message.part.updated",+ properties: { part: { ...part, id: partId, sessionID, messageID } },+ }+}diff --git a/examples/opencode-plugin/lib/v2-plugin.mjs b/examples/opencode-plugin/lib/v2-plugin.mjsnew file mode 100644index 000000000..db84a3934--- /dev/null+++ b/examples/opencode-plugin/lib/v2-plugin.mjs@@ -0,0 +1,352 @@+import { isRecallEnabled } from "./shared/recall-core.mjs"+import { createOpenVikingV2McpConfig } from "./mcp-config.mjs"+import { contextMessageEvents, normalizeV2LifecycleEvent } from "./v2-events.mjs"+import { log } from "./utils.mjs"++const METADATA_KEY = "openviking"+const CURSOR_KEY_PREFIX = "capture-cursor/"+const LIFECYCLE_EVENTS = new Set([+ "session.created",+ "session.deleted",+ "session.execution.succeeded",+ "session.execution.failed",+ "session.execution.interrupted",+ "session.compaction.ended",+])++export async function startV2Plugin(ctx, runtime, { pluginRoot }) {+ const {+ config,+ sessionManager,+ repoContext,+ recall,+ sessionInject,+ vikingUriGuard,+ vikingUriNotice,+ } = runtime+ const captureCursors = new Map()+ const sessionOwnership = new Map()+ // Compaction hooks can run while lifecycle events are still flushing. Keep+ // capture and flush ordered so the same pending message is never sent twice.+ let sessionTask = Promise.resolve()+ const serializeSession = (operation) => {+ const task = sessionTask.then(operation)+ sessionTask = task.catch(() => {})+ return task+ }+ const directory = ctx?.location?.project?.directory || ctx?.location?.directory++ if (config.mcp.enabled && ctx?.mcp?.transform) {+ await ctx.mcp.transform((editor) => {+ const current = editor.get?.("openviking")+ if (current?.disabled === true) return+ editor.set("openviking", createOpenVikingV2McpConfig(pluginRoot))+ })+ log("INFO", "mcp", "Registered OpenViking MCP server for OpenCode v2")+ } else if (!config.mcp.enabled) {+ log("INFO", "mcp", "Skipped bundled MCP registration in hook-only mode")+ }++ if (ctx?.tool?.hook) {+ await ctx.tool.hook("execute.before", async (event) => {+ await runtime.ready+ await vikingUriGuard(+ { tool: event.tool, args: event.input },+ { args: event.input },+ )+ })+ await ctx.tool.hook("execute.after", async (event) => {+ try {+ await runtime.ready+ await noticeV2Tool(event, vikingUriNotice)+ } catch (error) {+ logHookError("tool.execute.after", error)+ }+ })+ }++ if (ctx?.session?.hook) {+ await ctx.session.hook("prompt", async (event) => {+ try {+ await runtime.ready+ await prepareV2Prompt(event, {+ directory,+ recall,+ sessionInject,+ recallEnabled: isRecallEnabled(config),+ })+ } catch (error) {+ logHookError("session.prompt", error)+ }+ })++ await ctx.session.hook("context", async (event) => {+ try {+ await runtime.ready+ injectV2Context(event, repoContext)+ } catch (error) {+ logHookError("session.context", error)+ }+ })++ await ctx.session.hook("compaction", async (event) => {+ try {+ await runtime.ready+ // context() drops the old transcript as soon as compaction completes.+ // Capture it now; the ended event below owns the commit.+ await serializeSession(() => captureV2Context(ctx, sessionManager, captureCursors, event.sessionID))+ } catch (error) {+ logHookError("session.compaction.capture", error)+ }+ })+ }++ const controller = new AbortController()+ let eventTask = Promise.resolve()+ if (ctx?.event?.subscribe) {+ eventTask = consumeEvents(ctx, controller.signal, async (event) => {+ const sessionID = event?.data?.sessionID ?? event?.data?.sessionId+ if (!LIFECYCLE_EVENTS.has(event?.type) || !sessionID) return+ if (!(await ownsSession(ctx, sessionOwnership, event, sessionID))) return+ await serializeSession(async () => {+ await runtime.ready+ if (event.type === "session.execution.failed") {+ log("WARN", "v2", "OpenCode v2 execution failed", {+ opencode_session: sessionID,+ error: event.data?.error?.message ?? event.data?.error,+ })+ }+ if (isExecutionBoundary(event.type)) {+ try {+ await captureV2Context(ctx, sessionManager, captureCursors, sessionID)+ } catch (error) {+ logHookError("session.context.capture", error)+ }+ }+ for (const normalized of normalizeV2LifecycleEvent(event)) {+ await sessionManager.handleEvent(normalized)+ if (normalized.type === "session.created") {+ await repoContext.refreshRepos({ force: true })+ }+ }+ if (event.type === "session.deleted") {+ sessionOwnership.delete(sessionID)+ await forgetCursor(ctx, captureCursors, sessionID)+ }+ })+ })+ }++ return async () => {+ controller.abort()+ try {+ await eventTask+ await sessionTask+ await runtime.ready+ await runtime.background+ await sessionManager.waitForBackground?.()+ await sessionManager.flushAll({ commit: true })+ } catch (error) {+ logHookError("plugin.cleanup", error)+ }+ log("INFO", "plugin", "OpenViking plugin disposed")+ }+}++async function consumeEvents(ctx, signal, handle) {+ try {+ for await (const event of ctx.event.subscribe({ signal })) {+ try {+ await handle(event)+ } catch (error) {+ logHookError(`event.${event?.type || "unknown"}`, error)+ }+ }+ } catch (error) {+ if (signal.aborted) return+ logHookError("event.subscribe", error)+ }+}++export async function prepareV2Prompt(event, {+ directory,+ recall,+ sessionInject,+ recallEnabled,+}) {+ const sessionID = event?.sessionID+ const messageID = event?.messageID+ if (!sessionID || !messageID) return+ const text = event?.prompt?.text+ const parts = typeof text === "string" && text.trim() ? [{ type: "text", text }] : []+ const input = { sessionID, messageID, directory }+ const blocks = []+ try {+ const sessionBlock = await sessionInject.buildSessionContext(input)+ if (sessionBlock) blocks.push(sessionBlock)+ } catch (error) {+ logHookError("session.prompt.profile", error)+ }+ if (recallEnabled) {+ try {+ const recallBlock = await recall.buildRelevantMemories(input, parts)+ if (recallBlock) blocks.push(recallBlock)+ } catch (error) {+ logHookError("session.prompt.recall", error)+ }+ }+ if (blocks.length === 0) return++ event.metadata = event.metadata && typeof event.metadata === "object" ? event.metadata : {}+ event.metadata[METADATA_KEY] = { context: blocks }+}++export function injectV2Context(event, repoContext) {+ const repoPrompt = repoContext.getRepoSystemPrompt()+ if (repoPrompt) pushSystem(event, repoPrompt)+ if (!Array.isArray(event?.messages)) return++ for (const message of event.messages) {+ const blocks = message?.metadata?.[METADATA_KEY]?.context+ if (message?.role !== "user" || !Array.isArray(blocks) || blocks.length === 0) continue+ if (!Array.isArray(message.content)) message.content = []+ if (message.content.some((part) => part?.metadata?.[METADATA_KEY] === true)) continue+ message.content.unshift({+ type: "text",+ text: blocks.filter((block) => typeof block === "string" && block).join("\n\n"),+ metadata: { [METADATA_KEY]: true },+ })+ }+}++// The plugin event stream carries every location served by the process, and+// execution events have no envelope location, so ownership comes from the+// session itself. An unresolvable session is handled rather than dropped.+async function ownsSession(ctx, ownership, event, sessionID) {+ if (event.type === "session.created") {+ const owned = sameLocation(event.location ?? event.data?.location, ctx.location)+ ownership.set(sessionID, owned)+ return owned+ }+ if (event.location) return sameLocation(event.location, ctx.location)+ if (ownership.has(sessionID)) return ownership.get(sessionID)+ if (event.type === "session.deleted" || !ctx.session?.get) return true+ try {+ const result = await ctx.session.get({ sessionID })+ const location = (result?.data ?? result)?.location+ if (location?.directory) {+ const owned = sameLocation(location, ctx.location)+ ownership.set(sessionID, owned)+ return owned+ }+ } catch (error) {+ logHookError("session.get", error)+ }+ return true+}++function sameLocation(ref, location) {+ if (!ref?.directory || !location?.directory) return true+ if (ref.directory !== location.directory) return false+ return !ref.workspaceID || !location.workspaceID || ref.workspaceID === location.workspaceID+}++export async function captureV2Context(ctx, sessionManager, cursors, sessionID) {+ const messages = await ctx.session.context({ sessionID })+ if (!Array.isArray(messages)) return+ // The cursor lives in host storage because the session state file is shared+ // by every location instance and cannot prove what was already captured.+ const cursor = cursors.get(sessionID) ?? await readCursor(ctx, sessionID)+ const cursorIndex = cursor ? messages.findIndex((message) => message?.id === cursor) : -1+ const pending = cursorIndex >= 0 ? messages.slice(cursorIndex + 1) : messages+ for (const message of pending) {+ for (const normalized of contextMessageEvents(sessionID, message)) {+ await sessionManager.handleEvent(normalized)+ }+ }+ const last = messages.at(-1)?.id+ if (!last) return+ cursors.set(sessionID, last)+ if (last !== cursor) await writeCursor(ctx, sessionID, last)+}++async function readCursor(ctx, sessionID) {+ if (!ctx?.storage?.get) return undefined+ try {+ const value = await ctx.storage.get(CURSOR_KEY_PREFIX + sessionID)+ return typeof value === "string" ? value : undefined+ } catch (error) {+ logHookError("storage.get", error)+ return undefined+ }+}++async function writeCursor(ctx, sessionID, cursor) {+ if (!ctx?.storage?.set) return+ try {+ await ctx.storage.set(CURSOR_KEY_PREFIX + sessionID, cursor)+ } catch (error) {+ logHookError("storage.set", error)+ }+}++async function forgetCursor(ctx, cursors, sessionID) {+ cursors.delete(sessionID)+ if (!ctx?.storage?.remove) return+ try {+ await ctx.storage.remove(CURSOR_KEY_PREFIX + sessionID)+ } catch (error) {+ logHookError("storage.remove", error)+ }+}++function isExecutionBoundary(type) {+ return type === "session.execution.succeeded" ||+ type === "session.execution.failed" ||+ type === "session.execution.interrupted"+}++function pushSystem(event, text) {+ if (!text) return+ if (!Array.isArray(event.system)) event.system = []+ if (event.system.some((part) => part?.type === "text" && part.text === text)) return+ event.system.push({ type: "text", text })+}++function logHookError(hook, error) {+ log("WARN", "v2", `OpenCode v2 ${hook} failed`, {+ error: error?.message ?? String(error),+ })+}++async function noticeV2Tool(event, vikingUriNotice) {+ if (event?.status !== "completed") return+ const before = toolResultText(event.result)+ const output = { output: before }+ await vikingUriNotice({ tool: event.tool, args: event.input }, output)+ if (!output.output || output.output === before) return+ writeToolResultText(event.result, output.output)+}++function toolResultText(result) {+ if (!result || typeof result !== "object") return ""+ if (typeof result.content === "string") return result.content+ if (!Array.isArray(result.content)) return ""+ return result.content+ .filter((item) => item?.type === "text" && typeof item.text === "string")+ .map((item) => item.text)+ .join("\n\n")+}++function writeToolResultText(result, text) {+ if (!result || typeof result !== "object") return+ if (typeof result.content === "string" || result.content == null) {+ result.content = text+ return+ }+ if (!Array.isArray(result.content)) return+ // Preserve the original text/media blocks and append only the new notice.+ const before = toolResultText(result)+ const notice = text.startsWith(before) ? text.slice(before.length).trimStart() : text+ if (notice) result.content.push({ type: "text", text: notice })+}diff --git a/examples/opencode-plugin/lib/viking-uri-guard.mjs b/examples/opencode-plugin/lib/viking-uri-guard.mjsindex 0ccafc29f..c1ce1a2d6 100644--- a/examples/opencode-plugin/lib/viking-uri-guard.mjs+++ b/examples/opencode-plugin/lib/viking-uri-guard.mjs@@ -18,6 +18,10 @@ const FILESYSTEM_TOOL_HINTS = {tool: "openviking_read or openviking_search",example: (uri) => `openviking_read(uris=["${uri}"])`,},+ shell: {+ tool: "openviking_read or openviking_search",+ example: (uri) => `openviking_read(uris=["${uri}"])`,+ },}export function createVikingUriGuard() {diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.jsonindex 9f7c84166..70acb7e26 100644--- a/examples/opencode-plugin/package.json+++ b/examples/opencode-plugin/package.json@@ -1,6 +1,6 @@{"name": "@openviking/opencode-plugin",- "version": "0.4.2",+ "version": "0.5.0","author": "@openviking","description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory","type": "module",@@ -24,7 +24,7 @@],"scripts": {"prepack": "node ../memory-plugin-shared/sync.mjs",- "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs",+ "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/plugin-runtime.mjs && node --check lib/v2-events.mjs && node --check lib/v2-plugin.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs","test": "node --test tests/*.test.mjs"},"dependencies": {},diff --git a/examples/opencode-plugin/tests/mcp-config.test.mjs b/examples/opencode-plugin/tests/mcp-config.test.mjsindex c4e65c0f8..5bcf85cc9 100644--- a/examples/opencode-plugin/tests/mcp-config.test.mjs+++ b/examples/opencode-plugin/tests/mcp-config.test.mjs@@ -3,7 +3,7 @@ import assert from "node:assert/strict"import { readFile } from "node:fs/promises"import { fileURLToPath } from "node:url"import { dirname, join } from "node:path"-import { createOpenVikingMcpConfig, injectOpenVikingMcpConfig } from "../lib/mcp-config.mjs"+import { createOpenVikingMcpConfig, createOpenVikingV2McpConfig, injectOpenVikingMcpConfig } from "../lib/mcp-config.mjs"const testDir = dirname(fileURLToPath(import.meta.url))@@ -60,3 +60,23 @@ test("OpenCode MCP config points to the proxy entrypoint", () => {assert.equal(entry.command[0], "node")assert.match(entry.command[1], /servers\/mcp-proxy\.mjs$/)})++test("OpenCode v2 MCP config uses the local server schema", () => {+ const entry = createOpenVikingV2McpConfig("/tmp/ov")++ assert.equal(entry.type, "local")+ assert.equal(entry.command[0], "node")+ assert.match(entry.command[1], /servers\/mcp-proxy\.mjs$/)+ assert.equal(entry.enabled, undefined)+ assert.equal(entry.codemode, false)+ assert.deepEqual(entry.timeout, { startup: 15000, catalog: 15000, execution: 15000 })+})++test("OpenCode plugin exports a v2 setup without importing @opencode/plugin", async () => {+ const source = await readFile(join(testDir, "../index.mjs"), "utf8")++ assert.match(source, /id:\s*"openviking"/)+ assert.match(source, /async setup\(ctx\)/)+ assert.match(source, /async server\(input\)/)+ assert.doesNotMatch(source, /@opencode\/plugin/)+})diff --git a/examples/opencode-plugin/tests/memory-session.test.mjs b/examples/opencode-plugin/tests/memory-session.test.mjsindex 3adb0fe81..e33bf14bf 100644--- a/examples/opencode-plugin/tests/memory-session.test.mjs+++ b/examples/opencode-plugin/tests/memory-session.test.mjs@@ -65,6 +65,40 @@ function baseConfig(endpoint) {}}+test("deferred startup loads local state without waiting for legacy migration", async () => {+ await withTempDir("ov-oc-deferred-", async (dir) => {+ let releaseCommit+ let markCommitStarted+ const commitStarted = new Promise((resolve) => { markCommitStarted = resolve })+ const commitGate = new Promise((resolve) => { releaseCommit = resolve })+ const server = createServer(async (req, res) => {+ if (req.url?.endsWith("/commit")) {+ markCommitStarted()+ await commitGate+ }+ res.setHeader("Content-Type", "application/json")+ res.end(JSON.stringify({ status: "ok", result: {} }))+ })+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))+ const legacyPath = join(dir, "openviking-session-map.json")+ fs.writeFileSync(legacyPath, JSON.stringify({ sessions: { old: { ovSessionId: "legacy" } } }))+ const manager = createMemorySessionManager({ config: baseConfig(`http://127.0.0.1:${server.address().port}`), pluginRoot: dir })+ let initialized = false+ const init = manager.init({ deferNetwork: true }).then(() => { initialized = true })+ try {+ await commitStarted+ assert.equal(initialized, true, "activation must finish while legacy commit is still pending")+ assert.equal(fs.existsSync(`${legacyPath}.migrated`), false)+ } finally {+ releaseCommit()+ await init+ await manager.waitForBackground()+ await new Promise((resolve) => server.close(resolve))+ }+ assert.equal(fs.existsSync(`${legacyPath}.migrated`), true)+ })+})+test("autoCapture=false prevents OpenCode messages from being captured", async () => {await withCaptureServer(async ({ endpoint, requests }) => {await withTempDir("ov-oc-session-", async (dir) => {diff --git a/examples/opencode-plugin/tests/v2-events.test.mjs b/examples/opencode-plugin/tests/v2-events.test.mjsnew file mode 100644index 000000000..dfc0eef3b--- /dev/null+++ b/examples/opencode-plugin/tests/v2-events.test.mjs@@ -0,0 +1,85 @@+import test from "node:test"+import assert from "node:assert/strict"+import { contextMessageEvents, normalizeV2LifecycleEvent } from "../lib/v2-events.mjs"+import { extractPartsFromPayload } from "../lib/shared/capture-utils.mjs"++test("normalizeV2LifecycleEvent maps the v2 lifecycle onto the v1 handler shape", () => {+ const created = normalizeV2LifecycleEvent({+ type: "session.created",+ data: { sessionID: "ses_1", parentID: "ses_parent" },+ })+ assert.equal(created[0].type, "session.created")+ assert.equal(created[0].properties.info.id, "ses_1")+ assert.equal(created[0].properties.info.parentID, "ses_parent")++ assert.equal(normalizeV2LifecycleEvent({+ type: "session.execution.succeeded",+ data: { sessionID: "ses_1" },+ })[0].type, "session.idle")+ assert.equal(normalizeV2LifecycleEvent({+ type: "session.execution.failed",+ data: { sessionID: "ses_1", error: { message: "boom" } },+ })[0].type, "session.idle")+ assert.equal(normalizeV2LifecycleEvent({+ type: "session.compaction.ended",+ data: { sessionID: "ses_1" },+ })[0].type, "session.compacted")+ assert.deepEqual(normalizeV2LifecycleEvent({ type: "session.created", data: {} }), [])+})++test("contextMessageEvents converts v2 user and assistant messages", () => {+ const user = contextMessageEvents("ses_1", {+ id: "msg_user",+ type: "user",+ text: "remember this",+ })+ assert.equal(user[0].properties.info.role, "user")+ assert.equal(user[1].properties.part.text, "remember this")++ const assistant = contextMessageEvents("ses_1", {+ id: "msg_assistant",+ type: "assistant",+ content: [+ { type: "text", text: "answer" },+ {+ type: "tool",+ id: "call_1",+ name: "read",+ state: {+ status: "completed",+ input: { path: "README.md" },+ content: [{ type: "text", text: "file body" }],+ },+ },+ ],+ })+ assert.equal(assistant[0].properties.info.role, "assistant")+ assert.equal(assistant[1].properties.part.text, "answer")+ assert.equal(assistant[2].properties.part.type, "tool")+ assert.equal(assistant[2].properties.part.tool, "read")+ assert.equal(assistant[2].properties.part.state.content[0].text, "file body")+ assert.equal(extractPartsFromPayload(assistant[2].properties.part)[0].tool_output, "file body")+})++test("contextMessageEvents drops reasoning like the v1 capture path", () => {+ const events = contextMessageEvents("ses_1", {+ id: "msg_assistant",+ type: "assistant",+ content: [+ { type: "reasoning", text: "private chain of thought" },+ { type: "text", text: "final answer" },+ ],+ })+ const texts = events.slice(1).map((event) => event.properties.part.text)+ assert.deepEqual(texts, ["final answer"])+ assert.deepEqual(contextMessageEvents("ses_1", {+ id: "msg_reasoning_only",+ type: "assistant",+ content: [{ type: "reasoning", text: "thinking" }],+ }), [])+})++test("contextMessageEvents ignores non-conversation context entries", () => {+ assert.deepEqual(contextMessageEvents("ses_1", { id: "msg_idle", type: "idle" }), [])+ assert.deepEqual(contextMessageEvents("ses_1", { id: "msg_empty", type: "assistant", content: [] }), [])+})diff --git a/examples/opencode-plugin/tests/v2-plugin.test.mjs b/examples/opencode-plugin/tests/v2-plugin.test.mjsnew file mode 100644index 000000000..54a495f9b--- /dev/null+++ b/examples/opencode-plugin/tests/v2-plugin.test.mjs@@ -0,0 +1,292 @@+import test from "node:test"+import assert from "node:assert/strict"+import { captureV2Context, injectV2Context, prepareV2Prompt, startV2Plugin } from "../lib/v2-plugin.mjs"+import { createVikingUriNotice } from "../lib/viking-uri-guard.mjs"++function runtimeFixture(overrides = {}) {+ const events = []+ return {+ events,+ runtime: {+ config: { mcp: { enabled: true }, recall: { enabled: true } },+ sessionManager: {+ handleEvent: async (event) => events.push(event),+ flushSession: async () => {},+ flushAll: async () => {},+ },+ repoContext: {+ getRepoSystemPrompt: () => null,+ refreshRepos: async () => {},+ },+ recall: { buildRelevantMemories: async () => undefined },+ sessionInject: { buildSessionContext: async () => undefined },+ vikingUriGuard: async () => {},+ vikingUriNotice: async () => {},+ ready: Promise.resolve(),+ ...overrides,+ },+ }+}++function contextFixture(messages = []) {+ const hooks = {}+ const registered = []+ return {+ hooks,+ registered,+ ctx: {+ location: { directory: "/tmp/project" },+ mcp: {+ transform: async (callback) => callback({+ get: () => undefined,+ set: (name, config) => registered.push([name, config]),+ }),+ },+ tool: { hook: async (name, fn) => { hooks[name] = fn } },+ session: {+ hook: async (name, fn) => { hooks[name] = fn },+ context: async () => messages,+ },+ event: { subscribe: () => (async function* empty() {})() },+ },+ }+}++test("startV2Plugin registers direct MCP tools and all v2 hooks", async () => {+ const { runtime } = runtimeFixture()+ const { ctx, hooks, registered } = contextFixture()+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })++ assert.equal(registered[0][0], "openviking")+ assert.equal(registered[0][1].type, "local")+ assert.equal(registered[0][1].codemode, false)+ assert.deepEqual(Object.keys(hooks).sort(), ["compaction", "context", "execute.after", "execute.before", "prompt"])+ await cleanup()+})++test("compaction captures messages before the host drops them and contains read failures", async () => {+ const { runtime, events } = runtimeFixture()+ const messages = [+ { id: "user", type: "user", text: "run the build" },+ { id: "assistant", type: "assistant", content: [+ { type: "tool", id: "build", name: "shell", state: { status: "completed", input: { command: "make" }, content: [{ type: "text", text: "built" }] } },+ ] },+ ]+ const { ctx, hooks } = contextFixture(messages)+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })+ await hooks.compaction({ sessionID: "ses_1" })+ assert.equal(events.filter((event) => event.type === "message.updated").length, 2)+ assert.equal(events.at(-1).properties.part.output, "built")+ messages.length = 0+ await hooks.compaction({ sessionID: "ses_1" })+ assert.equal(events.filter((event) => event.type === "message.updated").length, 2)+ ctx.session.context = async () => { throw new Error("host unavailable") }+ await assert.doesNotReject(() => hooks.compaction({ sessionID: "ses_1" }))+ await cleanup()+})++test("shell notice preserves multiple text and media blocks without duplicating output", async () => {+ const { runtime } = runtimeFixture({ vikingUriNotice: createVikingUriNotice() })+ const { ctx, hooks } = contextFixture()+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })+ const original = [+ { type: "text", text: "command output", metadata: { source: "stdout" } },+ { type: "image", data: "test" },+ { type: "text", text: "Exited with code 1" },+ ]+ const result = { content: structuredClone(original) }+ await hooks["execute.after"]({ status: "completed", tool: "shell", input: { command: "cat viking://resources/test" }, result })+ assert.deepEqual(result.content.slice(0, 3), original)+ assert.equal(result.content.length, 4)+ assert.match(result.content[3].text, /openviking_read/)+ assert.doesNotMatch(result.content[3].text, /Exited with code 1/)+ await cleanup()+})++test("cleanup waits for background initialization before flushing", async () => {+ let completeBackground+ let flushed = false+ const background = new Promise((resolve) => { completeBackground = resolve })+ const { runtime } = runtimeFixture({ background })+ runtime.sessionManager.flushAll = async () => { flushed = true }+ const { ctx } = contextFixture()+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })+ const cleaning = cleanup()+ await new Promise((resolve) => setImmediate(resolve))+ assert.equal(flushed, false)+ completeBackground()+ await cleaning+ assert.equal(flushed, true)+})++test("prompt metadata is persisted and context injection is stable across model steps", async () => {+ let recallCalls = 0+ const event = {+ sessionID: "ses_1",+ messageID: "msg_1",+ prompt: { text: "find the deployment notes" },+ metadata: { caller: "test" },+ }+ await prepareV2Prompt(event, {+ directory: "/tmp/project",+ recallEnabled: true,+ sessionInject: { buildSessionContext: async () => "<profile>profile</profile>" },+ recall: {+ buildRelevantMemories: async (_input, parts) => {+ recallCalls += 1+ assert.equal(parts[0].text, "find the deployment notes")+ return "<openviking-context>memory</openviking-context>"+ },+ },+ })+ assert.equal(recallCalls, 1)+ assert.equal(event.metadata.caller, "test")++ const message = { role: "user", content: [{ type: "text", text: event.prompt.text }], metadata: event.metadata }+ const context = { system: [], messages: [message] }+ const repoContext = { getRepoSystemPrompt: () => "repo prompt" }+ injectV2Context(context, repoContext)+ injectV2Context(context, repoContext)++ assert.equal(message.content.length, 2)+ assert.match(message.content[0].text, /<profile>profile<\/profile>/)+ assert.match(message.content[0].text, /<openviking-context>memory<\/openviking-context>/)+ assert.equal(message.content[0].metadata.openviking, true)+ assert.equal(context.system.length, 1)+})++test("captureV2Context advances a per-session cursor and preserves tool parts", async () => {+ const events = []+ const messages = [+ { id: "msg_user", type: "user", text: "question" },+ {+ id: "msg_assistant",+ type: "assistant",+ content: [+ { type: "text", text: "answer" },+ {+ type: "tool", id: "call_1", name: "read",+ state: { status: "completed", input: { path: "README.md" }, content: [{ type: "text", text: "body" }] },+ },+ ],+ },+ ]+ const ctx = { session: { context: async () => messages } }+ const manager = { handleEvent: async (event) => events.push(event) }+ const cursors = new Map()++ await captureV2Context(ctx, manager, cursors, "ses_1")+ assert.equal(events.filter((event) => event.type === "message.updated").length, 2)+ assert.equal(events.at(-1).properties.part.tool, "read")+ assert.equal(cursors.get("ses_1"), "msg_assistant")++ events.length = 0+ await captureV2Context(ctx, manager, cursors, "ses_1")+ assert.deepEqual(events, [])+})++test("v2 prompt, context, after-tool, and event failures are contained", async () => {+ const { runtime } = runtimeFixture({+ recall: { buildRelevantMemories: async () => { throw new Error("recall failed") } },+ vikingUriNotice: async () => { throw new Error("notice failed") },+ })+ const { ctx, hooks } = contextFixture()+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })++ const prompt = { sessionID: "ses_1", messageID: "msg_1", prompt: { text: "query" } }+ runtime.sessionInject.buildSessionContext = async () => "<profile>still available</profile>"+ await assert.doesNotReject(() => hooks.prompt(prompt))+ assert.equal(prompt.metadata.openviking.context[0], "<profile>still available</profile>")+ await assert.doesNotReject(() => hooks.context({ sessionID: "ses_1", messages: null, system: [] }))+ await assert.doesNotReject(() => hooks["execute.after"]({+ status: "completed", tool: "shell", input: { command: "ls" }, result: { content: [] },+ }))+ await cleanup()+})++function eventLoopFixture({ events, contexts, locations, storage = new Map() }) {+ const contextCalls = []+ return {+ contextCalls,+ storage,+ ctx: {+ location: { directory: "/repo/a" },+ session: {+ hook: async () => {},+ context: async ({ sessionID }) => {+ contextCalls.push(sessionID)+ return contexts[sessionID] ?? []+ },+ get: async ({ sessionID }) => ({ data: { id: sessionID, location: { directory: locations[sessionID] } } }),+ },+ storage: {+ get: async (key) => storage.get(key),+ set: async (key, value) => { storage.set(key, value) },+ remove: async (key) => { storage.delete(key) },+ },+ event: { subscribe: () => (async function* replay() { yield* events })() },+ },+ }+}++const conversation = [+ { id: "msg_user", type: "user", text: "question" },+ { id: "msg_assistant", type: "assistant", content: [{ type: "text", text: "answer" }] },+]++test("event loop handles only sessions that belong to this location", async () => {+ const { runtime, events: handled } = runtimeFixture()+ const { ctx, contextCalls } = eventLoopFixture({+ events: [+ { type: "session.created", data: { sessionID: "ses_a", location: { directory: "/repo/a" } } },+ { type: "session.created", data: { sessionID: "ses_b", location: { directory: "/repo/b" } } },+ { type: "session.execution.succeeded", data: { sessionID: "ses_a" } },+ { type: "session.execution.succeeded", data: { sessionID: "ses_b" } },+ { type: "session.execution.succeeded", data: { sessionID: "ses_c" } },+ { type: "session.execution.failed", data: { sessionID: "ses_a", error: { message: "rate limited" } } },+ ],+ contexts: { ses_a: conversation, ses_b: conversation, ses_c: conversation },+ locations: { ses_c: "/repo/b" },+ })+ const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })+ await cleanup()++ assert.deepEqual(contextCalls, ["ses_a", "ses_a"])+ const sessionOf = (event) => event.properties.info?.sessionID ?? event.properties.part?.sessionID+ assert.ok(handled.every((event) => sessionOf(event) === "ses_a"))+ assert.deepEqual(+ handled.filter((event) => event.type.startsWith("session.")).map((event) => event.type),+ ["session.created", "session.idle", "session.idle"],+ )+ assert.equal(handled.filter((event) => event.type === "message.updated").length, 2)+})++test("a new plugin instance resumes from the stored capture cursor", async () => {+ const storage = new Map()+ const first = runtimeFixture()+ const firstLoop = eventLoopFixture({+ events: [{ type: "session.execution.succeeded", data: { sessionID: "ses_a" } }],+ contexts: { ses_a: conversation },+ locations: { ses_a: "/repo/a" },+ storage,+ })+ await (await startV2Plugin(firstLoop.ctx, first.runtime, { pluginRoot: "/tmp/ov" }))()+ assert.equal(first.events.filter((event) => event.type === "message.updated").length, 2)++ const second = runtimeFixture()+ const followUp = { id: "msg_follow_up", type: "user", text: "next question" }+ const secondLoop = eventLoopFixture({+ events: [+ { type: "session.execution.succeeded", data: { sessionID: "ses_a" } },+ { type: "session.deleted", data: { sessionID: "ses_a" } },+ ],+ contexts: { ses_a: [...conversation, followUp] },+ locations: { ses_a: "/repo/a" },+ storage,+ })+ await (await startV2Plugin(secondLoop.ctx, second.runtime, { pluginRoot: "/tmp/ov" }))()++ const captured = second.events.filter((event) => event.type === "message.updated")+ assert.deepEqual(captured.map((event) => event.properties.info.id), ["msg_follow_up"])+ assert.equal(storage.size, 0)+})diff --git a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs b/examples/opencode-plugin/tests/viking-uri-guard.test.mjsindex 12771b8b7..7dd954280 100644--- a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs+++ b/examples/opencode-plugin/tests/viking-uri-guard.test.mjs@@ -49,6 +49,15 @@ test("viking uri notice fills empty shell output", async () => {assert.match(output.output, /ignore this notice/)})+test("viking uri notice recognizes the OpenCode v2 shell tool", async () => {+ const notice = createVikingUriNotice()+ const output = { output: "No such file" }++ await notice({ tool: "shell", args: { command: "cat viking://resources/project/file.md" } }, output)++ assert.match(output.output, /openviking_read/)+})+test("viking uri notice leaves file tools and plain shell commands alone", async () => {const notice = createVikingUriNotice()const cases = [