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
fix(memory-plugin): run shell commands that carry viking:// and attach a notice (#5131)
t0saki6fb370cfba37
diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.mdindex 033ea8ffa..1e50535e9 100644--- a/docs/en/agent-integrations/04-codex.md+++ b/docs/en/agent-integrations/04-codex.md@@ -57,7 +57,7 @@ For TraeCode CLI 2.0, launch `trae-cli` and use `trae-cli plugin list` to confir## How it works-The plugin integrates with Codex's lifecycle by hooking into key events. On `SessionStart` (`startup`, `clear`, or `resume`), it injects `profile.md` plus URI and abstract indexes for `preferences/` and `entities/` through the same shared, CJK-aware profile builder used by the other coding-agent integrations. It then searches OpenViking and injects relevant memories before every prompt (`UserPromptSubmit`), appends new turns to the session after each response (`Stop`), commits the full transcript before compaction (`PreCompact`), and commits the session when the thread shuts down (`SessionEnd`) so memory extraction processes the entire conversation. Upon starting a fresh session, it also sweeps any orphaned sessions left by previous runs. A resumed session may combine the fixed profile block with its latest archive digest.+The plugin integrates with Codex's lifecycle by hooking into key events. On `SessionStart` (`startup`, `clear`, or `resume`), it injects `profile.md` plus URI and abstract indexes for `preferences/` and `entities/` through the same shared, CJK-aware profile builder used by the other coding-agent integrations. It then searches OpenViking and injects relevant memories before every prompt (`UserPromptSubmit`), appends new turns to the session after each response (`Stop`), commits the full transcript before compaction (`PreCompact`), and commits the session when the thread shuts down (`SessionEnd`) so memory extraction processes the entire conversation. Before a shell command runs (`PreToolUse` on `Bash`), it looks for a `viking://` URI in the command: the command still runs, and the model gets a notice suggesting the OpenViking MCP tools, which it can ignore when the URI is intentional data such as an `ov` argument. Upon starting a fresh session, it also sweeps any orphaned sessions left by previous runs. A resumed session may combine the fixed profile block with its latest archive digest.> **Known limitation**: `SessionEnd` requires Codex 0.145 or newer, and it only fires on a graceful exit (`/quit`, `/exit`, double `Ctrl-C`, EOF, end of a `codex exec` run). It does not fire on `SIGTERM`, a closed terminal, `kill -9`, or a crash, and it is deferred when the TUI runs against a `codex app-server` daemon. Those sessions — and every session on Codex older than 0.145, and any TraeCode CLI build without it — are recovered by the idle-TTL sweep (30 minutes) at the next `SessionStart`.@@ -103,7 +103,7 @@ Change it with `OPENVIKING_PEER_SOURCE`, with `plugin.peerSource` in `ovcli.conf|---------|-------|-----|| MCP tool calls fail with an auth error | The active ovcli config has no valid `api_key` for an authenticated server | Fix `~/.openviking/ovcli.conf` (or run `node <plugin-dir>/scripts/setup.mjs`) and restart Codex; the stdio proxy re-reads it on launch and after auth failures. || MCP tool calls fail with a connection error | Server unreachable or the URL is wrong | Check the endpoint: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| `4 hooks need review` | Security review on first launch | Run `/hooks` within Codex and approve the hooks. |+| `6 hooks need review` | Security review on first launch; after an upgrade that adds a hook, Codex asks again for the new one | Run `/hooks` within Codex and approve the hooks. || Plugin still targets an old server after `ov config switch` | Codex keeps the proxy process from the previous session | Restart Codex; the proxy resolves credentials at startup. || Hooks use one server, MCP another | Stale `OPENVIKING_*` credential env vars in one context (env vars override ovcli.conf by default) | Unset the stale env vars (ovcli.conf then drives both), set `OPENVIKING_CREDENTIAL_SOURCE=cli`, or make the env vars consistent. |diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex c12f9b458..032a335dd 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -12,7 +12,7 @@ Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenV- **Context takeover** is enabled by default. The `context` hook injects `[OpenViking Session Context]` from the latest archive overview before recall is added to the latest user turn.- **Native tools** `viking_search`, `viking_read`, `viking_browse`, `viking_remember`, `viking_forget`, `viking_add_resource`, `viking_archive_expand` let the model query and update memory on demand.- A footer status segment (`OV ✓ …`) shows connection and capture state; the `/viking` command prints status, and `/viking commit` forces a commit.-- Accidental `read`/`bash` calls on `viking://` URIs are blocked with a hint pointing back to `viking_read` / `viking_search`.+- Accidental `read`/`grep`/`find`/`ls` calls whose path is a `viking://` URI are blocked with a hint pointing to the matching `viking_*` tool. A `bash` command that carries a `viking://` URI still runs, and its result ends with a notice suggesting `viking_read` / `viking_search`.Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result).diff --git a/docs/en/agent-integrations/12-cursor.md b/docs/en/agent-integrations/12-cursor.mdindex e0bc90b6d..c118e455d 100644--- a/docs/en/agent-integrations/12-cursor.md+++ b/docs/en/agent-integrations/12-cursor.md@@ -31,7 +31,7 @@ Quit Cursor completely and restart it after installation.## Verify1. Restart Cursor and create a new Agent session.-2. Open **Cursor Settings → Hooks** and confirm that the OpenViking lifecycle Hooks execute `scripts/hook.mjs` and its URI protection Hooks execute `scripts/uri-guard.mjs`.+2. Open **Cursor Settings → Hooks** and confirm that the OpenViking lifecycle Hooks execute `scripts/hook.mjs` and its URI protection Hook executes `scripts/uri-guard.mjs`.3. Check that the `beforeSubmitPrompt` output contains `additional_context`. This confirms that recall reaches the Agent without requiring an MCP call first.4. Open **Cursor Settings → Tools & MCPs** and confirm that `openviking` is connected.5. Tell Cursor a temporary preference, wait for the response to finish, then create a new session and ask for that preference to verify capture and cross-session recall.@@ -40,7 +40,7 @@ Quit Cursor completely and restart it after installation.- `sessionStart` loads your profile and the current project's memory index.- `beforeSubmitPrompt` recalls context for the current request and injects it through `additional_context`.-- `beforeReadFile` and `beforeShellExecution` redirect accidental local access to `viking://` paths back to OpenViking MCP tools.+- `beforeReadFile` denies reading a `viking://` path as a local file and points the Agent to OpenViking MCP tools. Shell commands are not checked.- `stop` incrementally captures new user and assistant messages.- `preCompact` and `sessionEnd` commit pending messages for memory extraction.diff --git a/docs/en/agent-integrations/13-trae.md b/docs/en/agent-integrations/13-trae.mdindex bd83f55f4..9fcb3f0e5 100644--- a/docs/en/agent-integrations/13-trae.md+++ b/docs/en/agent-integrations/13-trae.md@@ -43,7 +43,7 @@ Quit and restart the corresponding client after installation.- `SessionStart` loads your profile and current project memory.- `UserPromptSubmit` recalls and injects context for the current request.-- `PreToolUse` redirects accidental local access to `viking://` paths back to OpenViking MCP tools.+- `PreToolUse` on TRAE and TRAE CN denies `Read`, `Glob`, and `Grep` calls whose path is a `viking://` URI and points to OpenViking MCP tools; a `Bash` or `RunCommand` command that carries a `viking://` URI still runs, with a notice suggesting those tools. TraeCode CLI 2.0 uses the Codex plugin, whose `PreToolUse` matches only `Bash`: it adds the same notice and never denies a call.- `Stop` captures and immediately commits the completed turn, including short sessions.- The OpenViking MCP server transparently exposes the full server MCP tool set (15 tools): `find`, `search`, `read`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, and `health`. `search` with `mode="context"` returns assembled context.diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex 544dedc4a..8d7da322c 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -52,13 +52,13 @@| harness | how it plugs in | auto-recall | recall carries session_id | digest (client)* | profile injection | takes over host compaction | offline compensation (pending queue) | statusline ||---|---|---|---|---|---|---|---|---|| claude-code | 9 hooks + MCP proxy + slash + statusline + skill | ✅ | ✅ | ✅ local `claude -p` / server-side rewrite (auto by default) | ✅ (10000) | ❌ (PreCompact only commits) | ✅ | ✅ |-| codex / trae-cli | 5 hooks + MCP proxy + skill | ✅ | ✅ | ✅ local `codex exec` (on by default) | ✅ (10000) | ❌ | ✅ | ❌ |-| cursor | 7 hooks + MCP proxy + rule + skill | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |+| codex / trae-cli | 6 hooks + MCP proxy + skill | ✅ | ✅ | ✅ local `codex exec` (on by default) | ✅ (10000) | ❌ | ✅ | ❌ |+| cursor | 6 hooks + MCP proxy + rule + skill | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ || trae / trae-cn | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ || zcode | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |-| opencode | 7 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + repo list into the system prompt | ❌ (commits once before and once after compacting) | ✅ | ❌ (toast instead) |+| opencode | 8 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + repo list into the system prompt | ❌ (commits once before and once after compacting) | ✅ | ❌ (toast instead) || dsh | native Cordis plugin (same process) + MCP proxy + skill | ✅ | ✅ | ❌ | ✅ (10000, once per session) | ❌ | ✅ | ❌ |-| pi | native extension (8 events) | ✅ | ✅ | ❌ | ✅ (10000, rebuilt into systemPrompt every turn) | ✅ **takeover** (on by default) | ✅ | ✅ |+| pi | native extension (9 events) | ✅ | ✅ | ❌ | ✅ (10000, 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 | ❌ || hermes | native MemoryProvider plugin | ✅ | partial (preferred `search/search` path only; the degraded `/find` path drops it) | ❌ | ❌ (static tool-guidance block) | ❌ | ✅ in-process queue (never written to disk) | ❌ || ov CLI | one-shot commands | ❌ (`ov find/search` are explicit commands) | — (`ov search --session-id` is an explicit argument) | ❌ | ❌ | ❌ | ❌ | ❌ |@@ -136,7 +136,7 @@ Core modules at a glance (detailed further in the per-dimension sections):| `workspace-identity.mjs` | Workspace root + git identity (normalized `origin`, root path, worktree/submodule kind), derived by walking the filesystem with no `git` subprocess and cached per cwd | All JS-based || `workspace-config.mjs` | The layered workspace config: reads `<root>/.openviking/config.json` and `config.local.json`, merges layers with provenance, strips connection and credential keys | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `workspace-registry.mjs` | The per-machine registry `~/.openviking/workspaces/<slot>.json` — one file per workspace, hand-created and read-only for the plugins, the layer that outranks any committed file | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |-| `uri-guard.mjs` | Intercepts cases where `viking://` is incorrectly treated as a local path | Used in each harness's `PreToolUse` or `tool.execute.before`-style hooks |+| `uri-guard.mjs` | Denies a file-tool call whose path argument is a `viking://` URI; lets a shell command that carries one run and attaches a notice for the model. grep's `pattern` is search text, not a path | Deny: each harness's `PreToolUse` or `tool.execute.before`-style hooks. Notice: `PreToolUse`, or a post-execution hook (`tools/post-execute` on dsh, `tool_result` on pi, `tool.execute.after` on opencode) || `config-schema.mjs` | The single declaration of every knob: canonical name, type, default, range, `OPENVIKING_*` variable, accepted aliases, and workspace key. The doctor's known-key set and the workspace file's dotted-key map are projections of it | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `plugin-config.mjs` | Resolves every declared knob through the layers: env → the workspace layers → `ovcli.conf` `plugin.<harness>` → `ovcli.conf` `plugin` → ov.conf's harness section → defaults | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `setup-wizard.mjs` | Interactively writes to `ovcli.conf` | cc, codex, opencode, and pi expose an entry point for this |@@ -165,7 +165,7 @@ Core modules at a glance (detailed further in the per-dimension sections):| Harness | Integration Form | Install Channel | Session ID Prefix/Format | Config Source | Standalone Setup Wizard ||---|---|---|---|---|---|| claude-code | CC plugin (marketplace): 9 hooks + MCP proxy + slash + statusline + skill | One-line `install.sh --harness claude` (supports both the modern plugin path and the legacy `claude mcp add` compatibility path) / manual marketplace / TOS mirror | `cc-<CC session_id verbatim>`; subagents use `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |-| codex | Codex plugin (marketplace): 4 hooks + MCP proxy + skill | One-line `--harness codex` / `codex plugin marketplace add` (the TOS channel uses dumb-HTTP git to ensure remote updates continue working) | `cx-<safeId>` (deterministically derived, without reading state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |+| codex | Codex plugin (marketplace): 6 hooks + MCP proxy + skill | One-line `--harness codex` / `codex plugin marketplace add` (the TOS channel uses dumb-HTTP git to ensure remote updates continue working) | `cx-<safeId>` (deterministically derived, without reading state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ || trae-cli | **Installed as a codex plugin alias** (TraeCode CLI 2.0, 2.0 only; a Codex-family CLI: uses the `traecli` binary and `~/.trae/traecli.toml` config; its capability surface is identical to codex) | One-line `--harness trae-cli` (reuses the codex install flow; marketplace commands run against the targeted binary, e.g., `traecli plugin marketplace add`) | Same derivation rule as codex | Same as codex (env + ovcli.conf `plugin.codex` + ov.conf) | ✅ (same as codex) || cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌ (shares the installer TUI) || trae / trae-cn | Config-driven (`~/.trae{,-cn}/hooks.json` + platform-specific mcp.json) | One-line `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |@@ -518,8 +518,8 @@ Each card serves as a quick-reference entry point. It records only the facts and## claude-code- **Integration docs**: [Claude Code Memory Plugin](./02-claude-code.md)-- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.5.0.-- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep` (5s, `uri-guard`) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).+- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.5.1.+- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep|Edit|Write|Bash` (5s, `uri-guard`: denies a file tool whose path is a `viking://` URI, adds a notice to a Bash command that carries one) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).- **Behavior notes**: The session ID format is `cc-<raw_CC_session_id>`, while subagents use `…__subagent-<agent_id>`. `Stop` commits at a threshold of 20000 (keep 10), and `PreCompact` commits synchronously. Automatic recall excludes resources ([§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)). The incremental cursor is stored in `/tmp` (if cleared by the system, the entire session is pushed again).- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 70 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.- **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) | compaction [§3.4](#_3-4-compaction-takeover) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance) | UX [§3.7](#_3-7-additional-ux-comparison).@@ -527,9 +527,9 @@ Each card serves as a quick-reference entry point. It records only the facts and## codex- **Integration docs**: [Codex Memory Plugin](./04-codex.md)-- **Form**: A Codex plugin (marketplace). Features 5 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s), an MCP proxy, and 1 experience skill. Version 0.9.0.-- **Capability highlights**: A local recall-compression pipeline (`codex exec`, [§3.2.5](#_3-2-5-recall-digest)). `SessionEnd` (Codex ≥ 0.145) commits the session on a graceful exit, catching up any turns `Stop` missed, and a `SessionStart` fallback sweep reclaims messages left unarchived by exits that never fired it ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).-- **Behavior notes**: The session ID format is `cx-<safeId>` (derived deterministically without reading state). `SessionEnd` fires only on a graceful exit and only on Codex 0.145+, so signals, crashes, older builds and `codex app-server` deferral fall to the sweep. Has no on-disk pending queue (while offline, the cursor simply doesn't advance, and the next turn resends to compensate, [§3.3.4](#_3-3-4-pending-queue-offline-compensation-comparison)). Idle-TTL is 1800000ms, lock wait 120000ms (configured via env). `Stop` and `SessionEnd` detach by default (the `appended N turn(s)` notice is hidden by default); a per-session mkdir lock serializes the Stop worker, PreCompact, the SessionEnd worker and the sweep. A newly registered hook event has no Codex trust record, so `/hooks` must approve `SessionEnd` after an upgrade.+- **Form**: A Codex plugin (marketplace). Features 6 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s / `PreToolUse:Bash` 5s), an MCP proxy, and 1 experience skill. Version 0.9.1.+- **Capability highlights**: A local recall-compression pipeline (`codex exec`, [§3.2.5](#_3-2-5-recall-digest)). `SessionEnd` (Codex ≥ 0.145) commits the session on a graceful exit, catching up any turns `Stop` missed, and a `SessionStart` fallback sweep reclaims messages left unarchived by exits that never fired it ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). `PreToolUse:Bash` (`uri-guard`) lets a shell command that carries a `viking://` URI run and adds a notice suggesting the OpenViking MCP tools. Codex edits files through `apply_patch`, whose input has no path argument, so the guard never denies a call.+- **Behavior notes**: The session ID format is `cx-<safeId>` (derived deterministically without reading state). `SessionEnd` fires only on a graceful exit and only on Codex 0.145+, so signals, crashes, older builds and `codex app-server` deferral fall to the sweep. Has no on-disk pending queue (while offline, the cursor simply doesn't advance, and the next turn resends to compensate, [§3.3.4](#_3-3-4-pending-queue-offline-compensation-comparison)). Idle-TTL is 1800000ms, lock wait 120000ms (configured via env). `Stop` and `SessionEnd` detach by default (the `appended N turn(s)` notice is hidden by default); a per-session mkdir lock serializes the Stop worker, PreCompact, the SessionEnd worker and the sweep. A newly registered hook has no Codex trust record, so after an upgrade `/hooks` must approve each hook the upgrade added (`SessionEnd`, `PreToolUse`).- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.codex`), and `ov.conf` (`codex`). Hooks authenticate with `Authorization: Bearer` alone ([§3.1.3](#_3-1-3-credential-systems)).- **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) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).@@ -537,22 +537,22 @@ Each card serves as a quick-reference entry point. It records only the facts and- **Integration docs**: [TRAE Memory Integration](./13-trae.md)- **Form**: TraeCode CLI 2.0 is a Codex-family CLI (binary `traecli`, user config `~/.trae/traecli.toml`, TUI support for `/plugins`, `/skills`, and `/mcp`). OpenViking integrates via a **codex plugin alias install**: using `--harness trae-cli` reuses the Codex installation flow, redirecting only the install parameters (binary, home, and config paths) to TraeCode CLI.-- **Capability surface**: Same plugin as Codex: 5 registered hooks, an MCP proxy, an experience skill, local recall compression, idle-TTL commit reclamation, and resume-archive injection. Refer to the Codex profile card. If the TraeCode CLI build lacks `SessionEnd`, the registration is ignored and every commit at shutdown goes through the idle-TTL sweep.+- **Capability surface**: Same plugin as Codex: 6 registered hooks, an MCP proxy, an experience skill, local recall compression, idle-TTL commit reclamation, and resume-archive injection. Refer to the Codex profile card. If the TraeCode CLI build lacks `SessionEnd`, the registration is ignored and every commit at shutdown goes through the idle-TTL sweep.- **Version support**: TraeCode CLI 2.0 only. 1.0 and 2.0 are not the same CLI — only 2.0 is Codex-family, and only 2.0 can use the codex plugin alias install. The earlier standalone plugin for 1.0 (the `~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` approach) has been removed from the repository. The installer still accepts `--harness trae-cli --uninstall` to clean up a copy an old install left on disk.- **Dimension index**: Same as the Codex card.## cursor- **Integration docs**: [Cursor Memory Integration](./12-cursor.md)-- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and a skill. Includes 7 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `beforeShellExecution` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring). Version 0.3.0.-- **Capability highlights**: Features a dual `uri-guard` on `beforeReadFile` and `beforeShellExecution` (independent of the plugin toggle). The rule and skill are installed alongside it.+- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and a skill. Includes 6 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring). Version 0.3.1.+- **Capability highlights**: Features a `uri-guard` on `beforeReadFile` (independent of the plugin toggle) that denies reading a `viking://` path. Shell commands are not checked, and an upgrade removes the `beforeShellExecution` entry an older install registered. The rule and skill are installed alongside it.- **Behavior notes**: The session ID format is `cu-<conversation_id>`. `stop` commits every 8 messages (`commitTurnThreshold=8`, counted in messages, keep 0). `sessionEnd` only fires on `window_close`. By then, the host has already destroyed the shell-exec host, so it practically never runs ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) — sessions ending below the 8-message watermark leave their tail to be archived by a later message in the same session ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the server is unreachable, every turn waits out the full 15s recall timeout.- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.cursor`), and the workspace files ([§3.1.4](#_3-1-4-configuration-layers)).- **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) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).## trae / trae-cn (IDE editions)- **Integration docs**: [TRAE Memory Integration](./13-trae.md)-- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). The shared library is introduced via relative imports, and the MCP server is named `openviking`. Version 0.3.0.+- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). `PreToolUse` denies Read/Glob/Grep calls whose path is a `viking://` URI, while a Bash/RunCommand command that carries one runs with a notice attached. The shared library is introduced via relative imports, and the MCP server is named `openviking`. Version 0.3.1.- **Capability highlights**: Features the simplest and most direct behavior of the group. Every Stop that carries content is committed (keep 0). Consequently, upon shutdown, the largest possible backlog is merely the last in-flight turn ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).- **Behavior notes**: trae and trae-cn differ only in their session ID prefixes (`tr-` vs. `trcn-`) and installation paths. The same workload lands in two separate sets of sessions across the two clients, and cross-client sharing occurs via the server-side memory space after extraction rather than by reusing sessions. Note that there is no handling for PreCompact, status lines, skills, or subagents.- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.trae` / `plugin.trae_cn`), and the workspace files.@@ -561,7 +561,7 @@ Each card serves as a quick-reference entry point. It records only the facts and## zcode- **Integration docs**: [Community Integrations → ZCode](./08-community-plugins.md)-- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors nothing: the installer assembles its shared runtime the same way it does for cursor and trae. Version 0.3.0.+- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors nothing: the installer assembles its shared runtime the same way it does for cursor and trae. Version 0.3.1.- **Capability highlights**: The rollout file `~/.zcode/cli/rollout/model-io-<sid>.jsonl` serves as the source of truth for increments (a `lastTurnId` diff backfills any missed Stop events). Stop detaches by default, meaning Ctrl+C does not result in lost writes.- **Behavior notes**: Commits on every Stop (keep 0). The capture path only strips the three types of injection blocks without performing any further text cleanup ([§3.2.6](#_3-2-6-injection-backflow-protection)). The initial capture reads the entire rollout at once, meaning that installing it into a long-running session will produce a single large push.- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.zcode`), and the workspace files; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.@@ -570,7 +570,7 @@ 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 7 plugin hooks: config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. Version 0.3.0.+- **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.3.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).- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.opencode`), and the workspace files.@@ -578,16 +578,16 @@ Each card serves as a quick-reference entry point. It records only the facts and## dsh (DeepSeek Harness)-- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). It natively registers 7 `viking_*` tools (`viking_search/read/browse/remember/forget/add_resource/archive_expand`) and communicates directly via REST. It features 4 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush. Version 0.4.0.+- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). It natively registers 7 `viking_*` tools (`viking_search/read/browse/remember/forget/add_resource/archive_expand`) and communicates directly via REST. It features 6 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush / tools/pre-execute / tools/post-execute. Version 0.4.2.- **Capability highlights**: `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it. Pre-step injection is transmitted as a user message, aligning with the `complete:true` rendering mode of the DSH persona.-- **Behavior notes**: The unified installer covers dsh and asks which profile to install into (default `web`, overridable with `--dsh-profile`); npm is the bundle's only distribution channel, so the github/tos choice does not apply and every mode except `dev` installs the published package; `dev` packs the checkout first, because `dsh plugin` forwards to pnpm and a linked source tree cannot resolve the dsh peers the bundle imports. The teardown commit is allocated 3 seconds with no threshold, and it does not trigger on SIGHUP or a consecutive Ctrl+C ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). Compaction remains invisible to the plugin: injected content shrinks alongside the host's compaction, and the profile is not re-injected. Each subagent is assigned its own session ([§3.3.5](#_3-3-5-subagent-session-comparison)). The tool surface is the server's own MCP surface, reached through the same stdio proxy the other integrations use and published under `mcp__openviking__*`, so a server upgrade adds tools without a bundle release; the trade-off is that the proxy runs once per profile, so tool calls carry a process-level actor peer and `remember` is not session-scoped (recall, capture, and commit still resolve a peer per session). The bundle also ships the shared `openviking-memory` skill. Additionally, `uri-guard` matches tool names without normalizing case.+- **Behavior notes**: The unified installer covers dsh and asks which profile to install into (default `web`, overridable with `--dsh-profile`); npm is the bundle's only distribution channel, so the github/tos choice does not apply and every mode except `dev` installs the published package; `dev` packs the checkout first, because `dsh plugin` forwards to pnpm and a linked source tree cannot resolve the dsh peers the bundle imports. The teardown commit is allocated 3 seconds with no threshold, and it does not trigger on SIGHUP or a consecutive Ctrl+C ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). Compaction remains invisible to the plugin: injected content shrinks alongside the host's compaction, and the profile is not re-injected. Each subagent is assigned its own session ([§3.3.5](#_3-3-5-subagent-session-comparison)). The tool surface is the server's own MCP surface, reached through the same stdio proxy the other integrations use and published under `mcp__openviking__*`, so a server upgrade adds tools without a bundle release; the trade-off is that the proxy runs once per profile, so tool calls carry a process-level actor peer and `remember` is not session-scoped (recall, capture, and commit still resolve a peer per session). The bundle also ships the shared `openviking-memory` skill. `uri-guard` lowercases tool names before matching: `tools/pre-execute` denies a file tool whose path is a `viking://` URI, and `tools/post-execute` adds a notice (`form: "notice"`) when a `bash` command carries one.- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.dsh`), the workspace files, and the cordis patch, which is the lowest layer for behavior knobs. Credentials are the exception: an endpoint, key, account, user, or peer named in the patch overrides the credential chain.- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | 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) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).## pi (pi Coding Agent Extension)- **Integration docs**: [pi Coding Agent Extension](./11-pi.md)-- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). It registers 7 native `viking_*` tools and uses direct REST communication (since pi lacks MCP support). It features 8 events + a `/viking` command. Version 0.3.0.+- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). It registers 7 native `viking_*` tools and uses direct REST communication (since pi lacks MCP support). It features 9 events + a `/viking` command; `tool_call` blocks read/grep/find/ls calls whose path is a `viking://` URI, and `tool_result` appends a notice to the result of a `bash` command that carries one. Version 0.3.1.- **Highlights**: Features takeover compaction (enabled by default, [§3.4.2](#_3-4-2-pi-takeover)). Employs a two-stage recall system: it queues at `before_agent_start` and performs synchronous retrieval during the context event, ensuring the current turn's prompt receives its corresponding memories. It also includes a status line. The `session_shutdown` event triggers across all shutdown paths and is properly awaited.- **Behavior**: When takeover is enabled, exiting does not trigger a commit. Instead, the handler persists local state, and archiving waits either for the next resumed run to hit the threshold or for a manual `/viking commit` command ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). The takeover threshold is set to 30000 tokens while keeping the last 3 turns (keep 3, which the server interprets as a message count). When takeover is disabled, the threshold is 20000 tokens (keep 10), and exiting triggers an unconditional commit. Tool registration requires `health` and `ensureSession` to be established first ([§1.1](#_1-1-active-tool-surface-agentic-calls)). The `viking_add_resource` tool exclusively accepts HTTP URLs (the guard resides on the server). If takeover is off, resuming via `pi -c` will re-report the entire branch.- **Config**: Configured via environment variables, `ovcli.conf` (`plugin.pi`), and the workspace files (credentials always pass through the credential chain, [§3.1.3](#_3-1-3-credential-systems)). Bypass goes through the shared `isBypassed` glob matcher under the key `bypassSessionPatterns`; the older `bypassPatterns` still reads.diff --git a/docs/en/agent-integrations/17-dsh.md b/docs/en/agent-integrations/17-dsh.mdindex 39357ef45..cc977aa75 100644--- a/docs/en/agent-integrations/17-dsh.md+++ b/docs/en/agent-integrations/17-dsh.md@@ -63,7 +63,7 @@ Each DSH session maps to `dsh-<session-id>` in OpenViking, and every subagent geThe model-facing surface is the OpenViking MCP tool set, reached through the same stdio proxy the other memory integrations use and published under an `mcp__openviking__` prefix. Because that proxy runs once per profile, `mcp__openviking__remember` stores into a short-lived server-side session rather than the current one—automatic capture still records the conversation itself—and tool calls carry the actor peer resolved at startup. Set `OPENVIKING_PEER_ID` when one process serves several workspaces and tool calls need exact attribution. The bundle also ships the shared `openviking-memory` skill, so the model knows when to search, read, and write.-Accidental filesystem or shell calls on `viking://` URIs are blocked with a hint pointing at the right OpenViking tool.+A filesystem tool call whose path is a `viking://` URI is blocked with a hint pointing at the right OpenViking tool. A shell command that carries a `viking://` URI still runs, and the model gets a notice suggesting the OpenViking tools, which it can ignore when the URI is intentional data.<details><summary><b>Configuration</b></summary>diff --git a/docs/en/agent-integrations/18-plugin-development.md b/docs/en/agent-integrations/18-plugin-development.mdindex 99a08f7b5..c3abc1afa 100644--- a/docs/en/agent-integrations/18-plugin-development.md+++ b/docs/en/agent-integrations/18-plugin-development.md@@ -112,7 +112,7 @@ Authoritative capability sources live in [`examples/memory-plugin-shared/lib/`](| Batch sending, offline replay, retry classification | [batch-send.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/batch-send.mjs), [pending-queue.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/pending-queue.mjs), [retryable.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/retryable.mjs) | When to call them and how acknowledgements advance the host cursor || Background writes | [async-writer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/async-writer.mjs) | Host-supported detach timing and recovery measures || MCP configuration and protocol | [mcp-proxy-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs), [mcp-proxy-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs) | Configuration projection, logger factory, necessary local tools |-| Virtual URI checks and diagnostics | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs), [doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | Tool names, denial format, host installation/state checks |+| Virtual URI checks and diagnostics | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs), [doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | Tool names, deny and notice envelopes, host installation/state checks |Dependencies must point from host adapters to shared capabilities. Shared code must not import a host directory. Pass a small, explicit callback when a capability needs a host action. Do not introduce a plugin container, service locator, or inheritance hierarchy for a single file read. Shared runtime modules must not depend on installers, tests, or user interfaces.@@ -192,7 +192,7 @@ A persistent MCP proxy cannot infer the active project from its startup cwd. Use| Before compaction | Ensure preceding messages were written, then commit as appropriate | `PreCompact` commits existing messages; this entrypoint does not catch up the transcript | `PreCompact` catches up the transcript and commits || Session end | Finish outstanding writes and commit | `SessionEnd` commits existing messages; this entrypoint does not catch up the transcript | `SessionEnd` catches up and commits in a worker, with startup recovery retained || Subagents | Preserve identity and parent relationships without duplicates | `SubagentStart`, `SubagentStop` | Neither event is registered in the current hook manifest |-| Local tool checks | Prevent treating virtual URIs as local paths | `PreToolUse` URI guard | No URI guard is registered in the current hook manifest |+| Local tool checks | Deny a file tool whose path is a virtual URI; attach a notice to a shell command that carries one | `PreToolUse` URI guard on Read, Glob, Grep, Edit, Write, and Bash | `PreToolUse` URI guard on Bash, notice only; file edits go through `apply_patch`, which has no path argument |Use [Claude Code hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json) and [Codex hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/hooks/hooks.json) as the event registration references. Identical event names do not guarantee identical payloads or outputs. A host without an end event must choose and document an alternative commit point, such as ZCode's Stop commits, rather than register an unreachable SessionEnd handler.@@ -276,7 +276,7 @@ Use direct remote MCP connections only when the host has suitable credential and## 7. URI guards, skills, and diagnostics-`viking://` is a virtual URI and must not be passed to local file or shell tools. Where the host supports checks before tool execution, use `evaluateUriGuard()` and keep only tool-parameter mapping and denial envelopes in the adapter. Do not expand the guard into a general command interceptor; ordinary file paths retain their behavior. Without the required event, document the limitation and guide models through a skill, without claiming equivalent interception.+`viking://` is a virtual URI. A local file tool whose path argument is a `viking://` URI cannot succeed, so where the host supports checks before tool execution, deny the call with `evaluateUriGuard()`. A shell command that carries a `viking://` URI may be using it as data (an `ov` argument, an HTTP payload, a search pattern), so let it run and attach the notice from `evaluateUriNotice()` through the host's model-visible context channel; `PreToolUse` hosts use `preToolUseOutput()`, which returns the deny or the notice envelope. Keep only tool hints and envelopes in the adapter. Do not expand the guard into a general command interceptor; ordinary file paths retain their behavior. Without the required event, document the limitation and guide models through a skill, without claiming equivalent interception.Shared skill sources live in [`examples/skills/`](https://github.com/volcengine/OpenViking/tree/main/examples/skills/) and are shipped through `SKILL_TARGETS`. Do not edit the same guidance separately in several plugin copies. Skills must describe tools that can actually be called and capabilities that exist. Do not instruct the model to repeat capture or commits each turn when hooks already own them. Distinct tool surfaces may need distinct skills; explain why. Generated skill files must not receive a banner before their YAML frontmatter.diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.mdindex 5045982db..f4c48dd19 100644--- a/docs/zh/agent-integrations/04-codex.md+++ b/docs/zh/agent-integrations/04-codex.md@@ -56,7 +56,7 @@ TraeCode CLI 2.0 用户启动 `trae-cli`,并可用 `trae-cli plugin list` 确## 工作原理-本插件深度挂载于 Codex 的生命周期之中:在 `SessionStart`(`startup`、`clear` 或 `resume`)阶段,它会复用其他 coding-agent 集成共用的 CJK-aware profile 构建逻辑,注入 `profile.md`,以及 `preferences/`、`entities/` 的 URI 和摘要索引;在每次用户输入前,它会搜索 OpenViking 并注入相关的记忆(触发 `UserPromptSubmit`);在每轮对话结束后,会将新的对话追加至当前会话(触发 `Stop`);在上下文压缩前,补齐并提交(commit)完整的对话记录(触发 `PreCompact`);在线程正常退出时提交整段会话(触发 `SessionEnd`),以确保记忆抽取器能够在完整的上下文环境中运行。此外,在启动新会话时,插件还会清扫前次运行遗留的孤儿会话(orphan session)。恢复已有会话时,固定 profile 背景还会与最新的 archive digest 合并注入。+本插件深度挂载于 Codex 的生命周期之中:在 `SessionStart`(`startup`、`clear` 或 `resume`)阶段,它会复用其他 coding-agent 集成共用的 CJK-aware profile 构建逻辑,注入 `profile.md`,以及 `preferences/`、`entities/` 的 URI 和摘要索引;在每次用户输入前,它会搜索 OpenViking 并注入相关的记忆(触发 `UserPromptSubmit`);在每轮对话结束后,会将新的对话追加至当前会话(触发 `Stop`);在上下文压缩前,补齐并提交(commit)完整的对话记录(触发 `PreCompact`);在线程正常退出时提交整段会话(触发 `SessionEnd`),以确保记忆抽取器能够在完整的上下文环境中运行。shell 命令执行前(`Bash` 上的 `PreToolUse`),插件会检查命令里是否带 `viking://` URI:命令照常执行,模型会收到一条提示,建议改用 OpenViking MCP 工具;如果该 URI 是有意传入的数据(例如 `ov` 命令参数),模型可以忽略这条提示。此外,在启动新会话时,插件还会清扫前次运行遗留的孤儿会话(orphan session)。恢复已有会话时,固定 profile 背景还会与最新的 archive digest 合并注入。> **已知局限**:`SessionEnd` 需要 Codex 0.145 及以上版本,且只在正常退出时触发(`/quit`、`/exit`、连按两次 `Ctrl-C`、EOF、`codex exec` 运行结束)。`SIGTERM`、直接关闭终端、`kill -9` 或崩溃都不会触发;当 TUI 挂在 `codex app-server` 守护进程上时,该事件会被延后。这些会话——以及 Codex 低于 0.145 的所有会话(以及没有该事件的 TraeCode CLI 版本)——由下一次 `SessionStart` 的闲置 TTL(生存时间,默认为 30 分钟)清扫回收。@@ -102,7 +102,7 @@ TraeCode CLI 2.0 用户启动 `trae-cli`,并可用 `trae-cli plugin list` 确|------|------|------|| MCP 工具调用报认证错误 | 当前 ovcli 配置没有 authenticated server 所需的有效 `api_key` | 修正 `~/.openviking/ovcli.conf`(或运行 `node <插件目录>/scripts/setup.mjs`)后重启 Codex;stdio 代理会在启动时和认证失败后重新读取配置 || MCP 工具调用报连接错误 | 服务器不可达或 URL 配置错误 | 执行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查服务器状态 |-| `4 hooks need review` | 首次启动需要进行安全审批 | 在 Codex 终端内输入 `/hooks` 完成审批 |+| `6 hooks need review` | 首次启动需要进行安全审批;升级新增 hook 后,Codex 会要求再次审批新增的 hook | 在 Codex 终端内输入 `/hooks` 完成审批 || `ov config switch` 后插件仍指向旧服务器 | 上个会话的代理进程仍在运行 | 重启 Codex;代理在启动时解析凭据 || Hook 与 MCP 指向不同服务器 | 某一侧残留了过期的 `OPENVIKING_*` 凭据环境变量(默认环境变量优先于 ovcli.conf) | 清除过期环境变量(让 ovcli.conf 同时驱动两者)、设置 `OPENVIKING_CREDENTIAL_SOURCE=cli`,或保证环境变量一致 |diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex ac936230b..997ce310c 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -12,7 +12,7 @@- **Context takeover** 默认开启。`context` hook 会先注入来自最新 archive overview 的 `[OpenViking Session Context]`,再把 recall 结果插入最新用户消息。- **原生工具** `viking_search`、`viking_read`、`viking_browse`、`viking_remember`、`viking_forget`、`viking_add_resource`、`viking_archive_expand` 供模型按需查询和写入记忆。- 底部状态栏显示 `OV ✓ …` 连接与捕获状态;`/viking` 命令查看状态,`/viking commit` 强制 commit。-- 模型误用本地 `read`/`bash` 读取 `viking://` URI 时会被拦截,并提示改用 `viking_read` / `viking_search`。+- 模型用本地 `read`/`grep`/`find`/`ls` 访问 `viking://` URI 路径时,调用会被拦截,并提示改用对应的 `viking_*` 工具;`bash` 命令带 `viking://` URI 时照常执行,结果末尾附一条提示,建议改用 `viking_read` / `viking_search`。工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result) 读回。diff --git a/docs/zh/agent-integrations/12-cursor.md b/docs/zh/agent-integrations/12-cursor.mdindex edaf9d506..8da62405c 100644--- a/docs/zh/agent-integrations/12-cursor.md+++ b/docs/zh/agent-integrations/12-cursor.md@@ -40,7 +40,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar- `sessionStart`:加载用户画像和当前项目的记忆索引。- `beforeSubmitPrompt`:根据当前问题召回记忆并通过 `additional_context` 注入。-- `beforeReadFile` 和 `beforeShellExecution`:阻止把 `viking://` 虚拟路径当作本地文件访问,并提示改用 OpenViking MCP 工具。+- `beforeReadFile`:阻止把 `viking://` 虚拟路径当作本地文件读取,并提示改用 OpenViking MCP 工具;shell 命令不做检查。- `stop`:增量捕获本轮新增的用户与助手消息。- `preCompact` / `sessionEnd`:提交尚未处理的消息,触发记忆抽取。diff --git a/docs/zh/agent-integrations/13-trae.md b/docs/zh/agent-integrations/13-trae.mdindex 14b184651..b36e2b620 100644--- a/docs/zh/agent-integrations/13-trae.md+++ b/docs/zh/agent-integrations/13-trae.md@@ -43,7 +43,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar- `SessionStart`:加载用户画像和当前项目记忆。- `UserPromptSubmit`:根据当前问题召回并注入相关内容。-- `PreToolUse`:阻止把 `viking://` 虚拟路径当作本地文件访问,并提示改用 OpenViking MCP 工具。+- `PreToolUse`:在 TRAE 和 TRAE CN 上,`Read`、`Glob`、`Grep` 的路径是 `viking://` URI 时拒绝调用,并提示改用 OpenViking MCP 工具;`Bash` 或 `RunCommand` 命令带 `viking://` URI 时照常执行,同时附加改用建议。TraeCode CLI 2.0 使用 Codex 插件,它的 `PreToolUse` 只匹配 `Bash`,只附加同样的提示,不拒绝调用。- `Stop`:捕获本轮消息并立即提交,使短会话也能进入记忆抽取流程。- OpenViking MCP Server:透传服务端完整 MCP 工具集(15 个工具):`find`、`search`、`read`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex 46fdcc76b..8d3b8fc9c 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -52,13 +52,13 @@| harness | 接入方式 | 自动召回 | 召回带 session_id | 再摘要(客户端)* | profile 注入 | 接管宿主压缩 | 离线补偿(pending queue) | statusline ||---|---|---|---|---|---|---|---|---|| claude-code | 9 hook + MCP 代理 + slash + statusline + skill | ✅ | ✅ | ✅ 本地 `claude -p` / 服务端 rewrite(默认 auto) | ✅(10000) | ❌(PreCompact 只 commit) | ✅ | ✅ |-| codex / trae-cli | 5 hook + MCP 代理 + skill | ✅ | ✅ | ✅ 本地 `codex exec`(默认开) | ✅(10000) | ❌ | ✅ | ❌ |-| cursor | 7 hook + MCP 代理 + rule + skill | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |+| codex / trae-cli | 6 hook + MCP 代理 + skill | ✅ | ✅ | ✅ 本地 `codex exec`(默认开) | ✅(10000) | ❌ | ✅ | ❌ |+| cursor | 6 hook + MCP 代理 + rule + skill | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ || trae / trae-cn | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ || zcode | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |-| opencode | 7 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ repo 列表进 system prompt | ❌(compacting 前后各 commit 一次) | ✅ | ❌(有 toast) |+| opencode | 8 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ repo 列表进 system prompt | ❌(compacting 前后各 commit 一次) | ✅ | ❌(有 toast) || dsh | Cordis 原生插件(同进程)+ MCP 代理 + skill | ✅ | ✅ | ❌ | ✅(10000,每 session 一次) | ❌ | ✅ | ❌ |-| pi | 原生扩展(8 事件) | ✅ | ✅ | ❌ | ✅(10000,进 systemPrompt 每轮重拼) | ✅ **takeover**(默认开) | ✅ | ✅ |+| pi | 原生扩展(9 事件) | ✅ | ✅ | ❌ | ✅(10000,进 systemPrompt 每轮重拼) | ✅ **takeover**(默认开) | ✅ | ✅ || openclaw | context-engine 插件(`ownsCompaction:true`) | ✅ | ❌(走 `/find`,该接口无 session_id 字段) | ❌ | ❌ | ✅ **ContextEngine 全接管** | ❌ 失败轮次不重放 | ❌ || hermes | MemoryProvider 原生插件 | ✅ | 部分(仅 `search/search` 首选路径;降级 `/find` 不带) | ❌ | ❌(静态工具指引块) | ❌ | ✅ 进程内队列(不落盘) | ❌ || ov CLI | 一次性命令 | ❌(`ov find/search` 是显式命令) | —(`ov search --session-id` 为显式参数) | ❌ | ❌ | ❌ | ❌ | ❌ |@@ -137,7 +137,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章| `workspace-identity.mjs` | workspace 根目录 + git 身份(归一化 `origin`、仓库根路径、worktree/submodule 类型),纯文件系统上溯、不起 `git` 子进程,按 cwd 缓存 | 全部 JS 系 || `workspace-config.mjs` | 分层 workspace 配置:读 `<root>/.openviking/config.json` 与 `config.local.json`,带来源(provenance)合并各层,剥离连接与凭据类 key | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `workspace-registry.mjs` | 每机注册表 `~/.openviking/workspaces/<slot>.json`——一个 workspace 一个文件,由人工创建、插件只读,优先级高于任何已提交的文件 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |-| `uri-guard.mjs` | 拦截 `viking://` 被误当成本地路径的情况 | 各 harness 的 PreToolUse/tool.execute.before 类 hook |+| `uri-guard.mjs` | 文件工具的路径参数是 `viking://` URI 时拒绝调用;shell 命令带 `viking://` URI 时照常执行,并给模型附加提示;grep 的 `pattern` 是搜索文本,不当作路径 | 拒绝:各 harness 的 PreToolUse/tool.execute.before 类 hook;提示:PreToolUse,或执行后的 hook(dsh `tools/post-execute`、pi `tool_result`、opencode `tool.execute.after`) || `config-schema.mjs` | 全部旋钮的唯一声明:规范名、类型、默认值、取值范围、`OPENVIKING_*` 变量、可接受的旧拼写、workspace 键。doctor 的已知键集合与 workspace 文件的点分键映射都是它的投影 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `plugin-config.mjs` | 按层解析全部已声明旋钮:env → workspace 各层 → ovcli.conf `plugin.<harness>` → ovcli.conf `plugin` → ov.conf 的 harness 段 → 默认值 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `setup-wizard.mjs` | 交互式写 ovcli.conf | cc / codex / opencode / pi 暴露入口 |@@ -167,7 +167,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章| harness | 集成形态 | 安装通道 | 会话 id 前缀/格式 | 配置来源 | 独立 setup 向导 ||---|---|---|---|---|---|| claude-code | CC 插件(marketplace):包含 9 hook + MCP 代理 + slash + statusline + skill | 一键 `install.sh --harness claude`(支持现代 plugin 路径与 legacy `claude mcp add` 兼容路径)/ 手动 marketplace / TOS 镜像 | `cc-<CC session_id 原文>`;subagent 格式为 `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |-| codex | Codex 插件(marketplace):包含 4 hook + MCP 代理 + skill | 一键 `--harness codex` / `codex plugin marketplace add`(TOS 走 dumb-HTTP git 以保留远程更新能力) | `cx-<safeId>`(确定性推导,不读取 state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |+| codex | Codex 插件(marketplace):包含 6 hook + MCP 代理 + skill | 一键 `--harness codex` / `codex plugin marketplace add`(TOS 走 dumb-HTTP git 以保留远程更新能力) | `cx-<safeId>`(确定性推导,不读取 state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ || trae-cli | **codex 插件别名安装**(TraeCode CLI 2.0,仅支持 2.0;Codex 系:binary `traecli`、配置 `~/.trae/traecli.toml`;能力面与 codex 一致) | 一键 `--harness trae-cli`(复用 codex 安装流程;marketplace 命令会随指向的 binary 执行,如 `traecli plugin marketplace add`) | 与 codex 的派生规则一致 | 与 codex 一致(env + ovcli.conf `plugin.codex` + ov.conf) | ✅(同 codex) || cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌(共用安装器 TUI) || trae / trae-cn | 配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json) | 一键 `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |@@ -499,8 +499,8 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## claude-code- **集成文档**:[Claude Code 记忆插件](./02-claude-code.md)-- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.5.0。-- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep(5s,uri-guard) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。+- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.5.1。+- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep\|Edit\|Write\|Bash(5s,uri-guard:文件工具的路径是 `viking://` URI 时拒绝,Bash 命令带 `viking://` URI 时附加提示) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。- **行为要点**:session id 为 `cc-<CC session_id 原文>`,subagent 为 `…__subagent-<agent_id>`;Stop 阈值 commit 20000/keep 10,PreCompact 同步 commit;自动召回排除 resources([§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));增量游标存于 `/tmp`(被系统清理后,同一会话会整段重推)。- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 70 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |压缩 [§3.4](#_3-4-压缩-compaction-接管) |降级 [§3.6](#_3-6-降级与容错) |UX [§3.7](#_3-7-附加-ux-对照)。@@ -508,9 +508,9 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## codex- **集成文档**:[Codex 记忆插件](./04-codex.md)-- **形态**:Codex 插件(marketplace),5 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s)+ MCP 代理 + 1 experience skill。版本 0.9.0。-- **能力亮点**:本地召回压缩管线(`codex exec`,[§3.2.5](#_3-2-5-召回再摘要));SessionEnd(Codex ≥ 0.145)在正常退出时补齐 Stop 漏掉的轮次并 commit,SessionStart 的兜底扫描回收那些没触发 SessionEnd 的退出所遗留的未归档消息([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。-- **行为要点**:session id 为 `cx-<safeId>`(确定性推导,不读 state);SessionEnd 只在正常退出、且 Codex 0.145+ 时触发,信号、崩溃、旧版本以及 `codex app-server` 延后的场景都落到扫描路径;不使用磁盘 pending queue(离线靠游标不推进、下一轮重发补偿,[§3.3.4](#_3-3-4-pending-queue-离线补偿对照));idle-TTL 1800000ms、锁等待 120000ms(env 配置);Stop 与 SessionEnd 默认 detach(`appended N turn(s)` 提示默认不展示);单会话 mkdir 锁串行化 Stop worker、PreCompact、SessionEnd worker 与扫描。新增的 hook 事件在 Codex 侧没有信任记录,升级后需在 `/hooks` 中批准 SessionEnd。+- **形态**:Codex 插件(marketplace),6 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s / PreToolUse:Bash 5s)+ MCP 代理 + 1 experience skill。版本 0.9.1。+- **能力亮点**:本地召回压缩管线(`codex exec`,[§3.2.5](#_3-2-5-召回再摘要));SessionEnd(Codex ≥ 0.145)在正常退出时补齐 Stop 漏掉的轮次并 commit,SessionStart 的兜底扫描回收那些没触发 SessionEnd 的退出所遗留的未归档消息([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));PreToolUse:Bash(uri-guard)放行带 `viking://` URI 的 shell 命令,并附加提示,建议改用 OpenViking MCP 工具;Codex 通过 `apply_patch` 编辑文件,输入里没有路径参数,因此 guard 不会拒绝任何调用。+- **行为要点**:session id 为 `cx-<safeId>`(确定性推导,不读 state);SessionEnd 只在正常退出、且 Codex 0.145+ 时触发,信号、崩溃、旧版本以及 `codex app-server` 延后的场景都落到扫描路径;不使用磁盘 pending queue(离线靠游标不推进、下一轮重发补偿,[§3.3.4](#_3-3-4-pending-queue-离线补偿对照));idle-TTL 1800000ms、锁等待 120000ms(env 配置);Stop 与 SessionEnd 默认 detach(`appended N turn(s)` 提示默认不展示);单会话 mkdir 锁串行化 Stop worker、PreCompact、SessionEnd worker 与扫描。新增的 hook 在 Codex 侧没有信任记录,升级后需在 `/hooks` 中批准这次升级新增的 hook(SessionEnd、PreToolUse)。- **配置**:env + ovcli.conf `plugin.codex` + ov.conf `codex`;hooks 只用 `Authorization: Bearer` 认证([§3.1.3](#_3-1-3-凭据体系))。- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。@@ -518,15 +518,15 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可- **集成文档**:[TRAE 记忆集成](./13-trae.md)- **形态**:TraeCode CLI 2.0 是 Codex 系 CLI(binary `traecli`,用户配置 `~/.trae/traecli.toml`,TUI 支持 `/plugins` `/skills` `/mcp`)。OpenViking 经 **codex 插件别名安装**接入:`--harness trae-cli` 复用 codex 安装流程,仅安装参数(binary / home / 配置路径)指向 TraeCode CLI。-- **能力面**:与 codex 同一套插件——5 个已注册 hook + MCP 代理 + experience skill、本地召回压缩、idle-TTL commit 回收、resume archive 注入等,详见 codex 档案卡。若 TraeCode CLI 所基于的 Codex 版本没有 `SessionEnd`,该 hook 会被忽略,关闭时的 commit 全部依赖 idle-TTL 扫描。+- **能力面**:与 codex 同一套插件——6 个已注册 hook + MCP 代理 + experience skill、本地召回压缩、idle-TTL commit 回收、resume archive 注入等,详见 codex 档案卡。若 TraeCode CLI 所基于的 Codex 版本没有 `SessionEnd`,该 hook 会被忽略,关闭时的 commit 全部依赖 idle-TTL 扫描。- **版本支持**:仅支持 TraeCode CLI 2.0。1.0 与 2.0 不是同一套 CLI,2.0 才是 Codex 系、才能走 codex 插件别名安装;早期面向 1.0 的独立插件(`~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` 方案)已随仓库移除;安装器仍保留 `--harness trae-cli --uninstall`,用于清掉旧安装留在磁盘上的那份。- **维度索引**:同 codex 卡。## cursor- **集成文档**:[Cursor 记忆集成](./12-cursor.md)-- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + skill。7 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / beforeShellExecution(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。版本 0.3.0。-- **能力亮点**:beforeReadFile/beforeShellExecution 双 uri-guard(不受插件开关控制);rule + skill 随装。+- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + skill。6 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。版本 0.3.1。+- **能力亮点**:beforeReadFile 上的 uri-guard 拒绝读取 `viking://` 路径(不受插件开关控制);shell 命令不做检查,升级时会移除旧版本注册的 beforeShellExecution 条目;rule + skill 随装。- **行为要点**:session id 为 `cu-<conversation_id>`;stop 每 8 条消息 commit(`commitTurnThreshold=8`,消息条数计数,keep 0);`sessionEnd` 仅 window_close 触发,且此时宿主已销毁 shell-exec host,实践中不执行([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——结束在 <8 条消息水位的会话,尾部依赖后续同会话消息触发归档([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));服务端不可达时,每轮等满 15s 召回超时。- **配置**:env + ovcli.conf `plugin.cursor` + workspace 文件([§3.1.4](#_3-1-4-配置体系分层))。- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。@@ -534,7 +534,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## trae / trae-cn(IDE 版)- **集成文档**:[TRAE 记忆集成](./13-trae.md)-- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。相对 import 共享 lib。MCP server 名为 `openviking`。版本 0.3.0。+- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。PreToolUse 对路径是 `viking://` URI 的 Read/Glob/Grep 直接拒绝;Bash/RunCommand 命令带 `viking://` URI 时照常执行,并附加提示。相对 import 共享 lib。MCP server 名为 `openviking`。版本 0.3.1。- **能力亮点**:行为最简单直接的一档——每个有内容的 Stop 都 commit(keep 0),关闭场景下最大待归档量只有最后一轮 in-flight([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。- **行为要点**:trae 与 trae-cn 的差异是 session id 前缀 `tr-` / `trcn-` 与安装路径——同一份记忆在两个客户端落到两组不同 session,跨客户端共享靠服务端抽取后的记忆空间而非 session 复用;无 PreCompact/statusline/skill/subagent 处理。- **配置**:env + ovcli.conf `plugin.trae` / `plugin.trae_cn` + workspace 文件。@@ -543,7 +543,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## zcode- **集成文档**:[社区插件 → ZCode](./08-community-plugins.md)-- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。自身不 vendoring 任何共享模块:安装器按 cursor / trae 同样的方式为它拼装共享运行时。版本 0.3.0。+- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。自身不 vendoring 任何共享模块:安装器按 cursor / trae 同样的方式为它拼装共享运行时。版本 0.3.1。- **能力亮点**:以 rollout 文件 `~/.zcode/cli/rollout/model-io-<sid>.jsonl` 为增量真相源(`lastTurnId` 差集补齐漏掉的 Stop);Stop 默认 detach(Ctrl+C 不丢写入)。- **行为要点**:每 Stop commit(keep 0);捕获路径仅剥离三类注入块(不做额外文本清洗,[§3.2.6](#_3-2-6-注入回流防护));首次捕获会一次性读取整个 rollout(长会话首装时单次推送量大)。- **配置**:env + ovcli.conf `plugin.zcode` + workspace 文件;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。@@ -552,7 +552,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## opencode- **集成文档**:[OpenCode 插件](./10-opencode.md)-- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。7 个 plugin hook:config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。版本 0.3.0。+- **形态**: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.3.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)。- **配置**:env + ovcli.conf `plugin.opencode` + workspace 文件。@@ -560,16 +560,16 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## dsh(DeepSeek Harness)-- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),原生注册 7 个 `viking_*` 工具(`viking_search/read/browse/remember/forget/add_resource/archive_expand`),REST 直连。4 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush。版本 0.4.0。+- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),原生注册 7 个 `viking_*` 工具(`viking_search/read/browse/remember/forget/add_resource/archive_expand`),REST 直连。6 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush / tools/pre-execute / tools/post-execute。版本 0.4.2。- **能力亮点**:`ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发;pre-step 注入走 user 消息,适配 DSH persona 的 `complete:true` 渲染模式。-- **行为要点**:统一安装器已覆盖 dsh,会询问装到哪个 profile(默认 `web`,可用 `--dsh-profile` 指定);npm 是该插件唯一的分发渠道,因此 github/tos 选择对它不适用,除 `dev` 外的模式一律装已发布的包;`dev` 会先把 checkout 打包再装——`dsh plugin` 转发给 pnpm,link 一个源码目录无法解析插件 import 的 dsh peer;teardown commit 3s 无阈值,SIGHUP/二次 Ctrl+C 不触发([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));compaction 不感知(注入内容随宿主压缩收缩,profile 不重投);subagent 各自独立会话([§3.3.5](#_3-3-5-subagent-会话对照));工具面即服务端自身的 MCP 面,经与其他集成同一个 stdio 代理接入、以 `mcp__openviking__*` 发布,服务端升级即可增加工具而无需发版;代价是代理每个 profile 只起一个进程,因此工具调用带的是进程级 actor peer、`remember` 也不绑当前会话(召回/捕获/commit 仍按会话解析 peer);另随包附带共享的 `openviking-memory` 技能;uri-guard 匹配工具名不做大小写归一化。+- **行为要点**:统一安装器已覆盖 dsh,会询问装到哪个 profile(默认 `web`,可用 `--dsh-profile` 指定);npm 是该插件唯一的分发渠道,因此 github/tos 选择对它不适用,除 `dev` 外的模式一律装已发布的包;`dev` 会先把 checkout 打包再装——`dsh plugin` 转发给 pnpm,link 一个源码目录无法解析插件 import 的 dsh peer;teardown commit 3s 无阈值,SIGHUP/二次 Ctrl+C 不触发([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));compaction 不感知(注入内容随宿主压缩收缩,profile 不重投);subagent 各自独立会话([§3.3.5](#_3-3-5-subagent-会话对照));工具面即服务端自身的 MCP 面,经与其他集成同一个 stdio 代理接入、以 `mcp__openviking__*` 发布,服务端升级即可增加工具而无需发版;代价是代理每个 profile 只起一个进程,因此工具调用带的是进程级 actor peer、`remember` 也不绑当前会话(召回/捕获/commit 仍按会话解析 peer);另随包附带共享的 `openviking-memory` 技能;uri-guard 先把工具名转成小写再匹配,tools/pre-execute 拒绝路径是 `viking://` URI 的文件工具,bash 命令带 `viking://` URI 时由 tools/post-execute 附加提示(`form: "notice"`)。- **配置**:env + ovcli.conf `plugin.dsh` + workspace 文件 + cordis patch(行为旋钮的最低层);凭据是例外,patch 里写的 endpoint / key / account / user / peer 仍然压过凭据链。- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。## pi(pi Coding Agent Extension)- **集成文档**:[pi Coding Agent 扩展](./11-pi.md)-- **形态**:pi 原生扩展(目录装载,jiti 直译 TS),原生注册 7 个 `viking_*` 工具,REST 直连(pi 无 MCP 支持)。8 事件 + `/viking` 命令。版本 0.3.0。+- **形态**:pi 原生扩展(目录装载,jiti 直译 TS),原生注册 7 个 `viking_*` 工具,REST 直连(pi 无 MCP 支持)。9 事件 + `/viking` 命令;tool_call 拦截路径是 `viking://` URI 的 read/grep/find/ls,bash 命令带 `viking://` URI 时,tool_result 在结果末尾追加提示。版本 0.3.1。- **能力亮点**:takeover 压缩接管(默认开,[§3.4.2](#_3-4-2-pi-takeover));两段式召回(before_agent_start 排队 + context 事件同步检索,当前轮 prompt 拿当前轮记忆);statusline;`session_shutdown` 在所有关闭方式下都触发且被 await。- **行为要点**:默认 takeover 下退出不 commit(handler 持久化本地状态,归档靠下次续跑攒满阈值或 `/viking commit`,[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));takeover 阈值 30000 token + 保留 3 轮(keep 3,服务端按消息条数解释);非 takeover 阈值 20000/keep 10、退出无条件 commit;工具注册需 health+ensureSession 前置([§1.1](#_1-1-主动工具面-agentic-调用能力));`viking_add_resource` 仅 HTTP URL(guard 在服务端);非 takeover 模式下 `pi -c` 续跑会重新上报整条 branch。- **配置**:env + ovcli.conf `plugin.pi` + workspace 文件(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));bypass 走共享 `isBypassed` 的 glob 匹配,键名 `bypassSessionPatterns`(旧名 `bypassPatterns` 仍可读)。diff --git a/docs/zh/agent-integrations/17-dsh.md b/docs/zh/agent-integrations/17-dsh.mdindex 6b930c5d8..c136946c7 100644--- a/docs/zh/agent-integrations/17-dsh.md+++ b/docs/zh/agent-integrations/17-dsh.md@@ -63,7 +63,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar模型看到的工具面就是 OpenViking 的 MCP 工具集,经由与其他记忆集成相同的 stdio 代理接入,以 `mcp__openviking__` 前缀发布。由于该代理每个 profile 只起一个进程,`mcp__openviking__remember` 写入的是服务端一个短生命周期的会话而不是当前会话(对话本身仍由自动捕获记录),工具调用带的也是启动时解析的 actor peer。若一个进程要服务多个工作区且需要精确归属工具调用,请显式设置 `OPENVIKING_PEER_ID`。插件同时附带共享的 `openviking-memory` 技能,让模型知道何时该检索、读取和写入。-误把 `viking://` URI 当本地路径的文件或 shell 调用会被拦截,并提示改用对应的 OpenViking 工具。+文件工具误把 `viking://` URI 当本地路径时,调用会被拦截,并提示改用对应的 OpenViking 工具;shell 命令带 `viking://` URI 时照常执行,模型会收到一条改用 OpenViking 工具的提示,URI 是有意传入的数据时可以忽略。<details><summary><b>配置</b></summary>diff --git a/docs/zh/agent-integrations/18-plugin-development.md b/docs/zh/agent-integrations/18-plugin-development.mdindex 87898af1b..1e4332687 100644--- a/docs/zh/agent-integrations/18-plugin-development.md+++ b/docs/zh/agent-integrations/18-plugin-development.md@@ -112,7 +112,7 @@ sync / install / pack 负责把这张依赖图完整交付到机器上| 批量发送、离线重放、重试分类 | [batch-send.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/batch-send.mjs)、[pending-queue.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/pending-queue.mjs)、[retryable.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/retryable.mjs) | 何时调用、发送成功后如何推进宿主游标 || 后台写入 | [async-writer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/async-writer.mjs) | 宿主允许的 detach 时机和恢复措施 || MCP 配置与协议 | [mcp-proxy-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs)、[mcp-proxy-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs) | 配置投影、日志工厂、确有必要的本地工具 |-| 虚拟 URI 检查、诊断 | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs)、[doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | 工具名、拒绝格式、宿主安装与状态检查 |+| 虚拟 URI 检查、诊断 | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs)、[doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | 工具名、拒绝与提示 envelope、宿主安装与状态检查 |依赖必须从宿主适配器指向共享能力。共享能力不能 import 某个宿主目录;需要宿主动作时,由调用者传入小而明确的回调。不要为一次文件读取引入通用插件容器、服务定位器或继承体系。共享模块也不能反向依赖安装器、测试代码或用户界面。@@ -192,7 +192,7 @@ peer 解析使用共享实现。现状默认从 Git 身份推导,普通非 Git| 压缩前 | 确认压缩前消息已写入,再执行相应提交 | `PreCompact` 提交已有消息;本入口不补采 transcript | `PreCompact` 补齐 transcript 后提交 || 会话结束 | 完成尚未完成的写入与提交 | `SessionEnd` 提交已有消息;本入口不补采 transcript | `SessionEnd` 后台补齐并提交,保留启动补偿 || 子代理 | 保留身份和父子关系,避免重复 | `SubagentStart`、`SubagentStop` | 当前 hook manifest 没有这两个事件 |-| 本地工具检查 | 阻止把虚拟 URI 当本地路径 | `PreToolUse` URI guard | 当前 hook manifest 未注册 URI guard |+| 本地工具检查 | 文件工具的路径是虚拟 URI 时拒绝;shell 命令带虚拟 URI 时附加提示 | `PreToolUse` URI guard,匹配 Read、Glob、Grep、Edit、Write、Bash | `PreToolUse` URI guard 只匹配 Bash,只附加提示;文件编辑走 `apply_patch`,没有路径参数 |以两份 [Claude Code hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json) 和 [Codex hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/hooks/hooks.json) 为事件注册依据。相同事件名称不保证 payload 或输出格式相同。没有结束事件的宿主必须选择并说明替代提交点,例如 ZCode 在 Stop 提交;不能假装存在一个永远不会执行的 SessionEnd。@@ -276,7 +276,7 @@ proxy 入口不得拥有自己的工具 schema、副本 API client、SSE parser## 7. URI guard、Skill 和诊断-`viking://` 是虚拟 URI,不能交给本地文件或 shell 工具。宿主支持工具执行前检查时,应使用 `evaluateUriGuard()`,只在适配器中定义工具参数和拒绝 envelope。检查器不能扩展成一般命令拦截器;普通文件路径应保持原有行为。宿主不支持该事件时,明确限制并通过 Skill 指引模型使用 MCP,不得宣称具备等效拦截。+`viking://` 是虚拟 URI。本地文件工具的路径参数是 `viking://` URI 时必然失败,所以宿主支持工具执行前检查时,用 `evaluateUriGuard()` 拒绝这次调用。shell 命令里的 `viking://` URI 可能只是数据(`ov` 命令参数、HTTP 请求体、搜索模式),所以命令照常执行,再通过宿主的模型可见上下文通道附上 `evaluateUriNotice()` 生成的提示;`PreToolUse` 类宿主直接用 `preToolUseOutput()`,它返回拒绝或提示 envelope。适配器中只定义替代工具提示和 envelope。检查器不能扩展成一般命令拦截器;普通文件路径应保持原有行为。宿主不支持该事件时,明确限制并通过 Skill 指引模型使用 MCP,不得宣称具备等效拦截。共享 Skill 的源文件放在 [`examples/skills/`](https://github.com/volcengine/OpenViking/tree/main/examples/skills/),通过 `SKILL_TARGETS` 交付,禁止在多个插件副本里分别修改同一段指导。Skill 只描述真实可调用工具和实际能力;自动 hook 已处理的捕获、提交不应再要求模型每轮手动重复执行。不同工具集确有不同操作语义时,可以保留独立 Skill,并说明理由。生成 Skill 时不能在 YAML frontmatter 前插入生成标记。diff --git a/examples/agent-hook-plugin/DESIGN.md b/examples/agent-hook-plugin/DESIGN.mdindex 188e675ac..65eb252cd 100644--- a/examples/agent-hook-plugin/DESIGN.md+++ b/examples/agent-hook-plugin/DESIGN.md@@ -43,7 +43,9 @@ ZCode supports 7 events but NOT `PreCompact`/`SessionEnd`/`SubagentStart`/`Subag### 4. Output schema: ZCode-canonical keys only-ZCode's strict JSON schema rejects unrecognized keys. The adapter's envelope emits ONLY `{ hookSpecificOutput: { hookEventName, additionalContext } }` for context injection, and `{ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason } }` for URI guard. No `decision: "approve"` (Claude-Code-ism).+ZCode's strict JSON schema rejects unrecognized keys. The adapter's envelope emits ONLY `{ hookSpecificOutput: { hookEventName, additionalContext } }` for context injection, `{ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason } }` when the URI guard denies a file tool, and `{ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext } }` when it notices a `viking://` URI in a shell command. No `decision: "approve"` (Claude-Code-ism).++The shared guard produces that notice for any shell tool, but the `PreToolUse` matcher names only `Read|Glob|Grep`, so ZCode never sends one. Whether its schema accepts `additionalContext` on `PreToolUse` is unverified; add a shell tool to the matcher only after checking that against a live session.**Provenance**: Adversarial review R1-F1, R4-V1 — the #1 silent-failure mode.diff --git a/examples/agent-hook-plugin/README.md b/examples/agent-hook-plugin/README.mdindex be1cbccdd..f31f0ae20 100644--- a/examples/agent-hook-plugin/README.md+++ b/examples/agent-hook-plugin/README.md@@ -14,7 +14,7 @@ bash examples/memory-plugin-shared/install.sh --harness zcode- **Session start** — injects the user profile and preferences into context, and replays anything an offline session queued.- **Prompt submit** — searches OpenViking for memories relevant to the prompt and injects them, deduplicated by event id and a 500ms window.-- **Tool use** — denies `viking://` virtual paths to local file and shell tools, and points the agent back at the OpenViking MCP tools.+- **Tool use** — denies local file tools a `viking://` virtual path and points the agent back at the OpenViking MCP tools. On TRAE a shell command that carries a `viking://` URI still runs, with a notice pointing at the same tools.- **Stop** — captures the finished turn and commits the OpenViking session. Cursor also runs this before a compaction and at session end; ZCode answers first and finishes the writes in a detached worker.## Layout@@ -29,7 +29,7 @@ The memory logic itself is not here: recall, batching, the pending queue, creden## Host notes-- **Cursor** — seven events, including the `preCompact` and `sessionEnd` no other host in this plugin has. Commits on Stop once `capturedSinceCommit` reaches the threshold, and unconditionally before a compaction. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).+- **Cursor** — six events, including the `preCompact` and `sessionEnd` no other host in this plugin has. Commits on Stop once `capturedSinceCommit` reaches the threshold, and unconditionally before a compaction. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).- **TRAE / TRAE CN** — capture reads `prompt`, `text_content` and `last_assistant_message` off the Stop event rather than parsing a transcript. Every Stop that carries content commits. Sessions are `tr-` and `trcn-`. See the [TRAE guide](../../docs/en/agent-integrations/13-trae.md).- **ZCode** — the rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and let a later Stop recover missed turns, and hook stdin is only the fallback. ZCode supports neither `PreCompact` nor `SessionEnd`, so committing on every Stop stands in for both. Its output schema is strict, so a pass-through writes nothing at all. Sessions are `zc-`. [DESIGN.md](./DESIGN.md) records the verified extension surface.diff --git a/examples/agent-hook-plugin/README_CN.md b/examples/agent-hook-plugin/README_CN.mdindex 8e581e9fa..5679b07c6 100644--- a/examples/agent-hook-plugin/README_CN.md+++ b/examples/agent-hook-plugin/README_CN.md@@ -14,7 +14,7 @@ bash examples/memory-plugin-shared/install.sh --harness zcode- **会话开始** — 注入用户画像与偏好,并重放离线会话排队的写入。- **提交 prompt** — 搜索与 prompt 相关的记忆并注入,按事件 id 与 500ms 窗口去重。-- **工具调用前** — 拦截本地文件与 shell 工具对 `viking://` 虚拟路径的访问,引导回 OpenViking MCP 工具。+- **工具调用前** — 拦截本地文件工具对 `viking://` 虚拟路径的访问,引导回 OpenViking MCP 工具。在 TRAE 上,带 `viking://` URI 的 shell 命令照常执行,并附加一条指向同一组工具的提示。- **Stop** — 捕获完成的回合并提交 OpenViking 会话。Cursor 另外在压缩前与会话结束时执行;ZCode 先应答,再在 detached worker 里完成写入。## 目录结构@@ -29,7 +29,7 @@ bash examples/memory-plugin-shared/install.sh --harness zcode## 各宿主差异-- **Cursor** — 七个事件,其中 `preCompact` 与 `sessionEnd` 是本插件里独有的。Stop 时 `capturedSinceCommit` 达到阈值才 commit,压缩前无条件 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。+- **Cursor** — 六个事件,其中 `preCompact` 与 `sessionEnd` 是本插件里独有的。Stop 时 `capturedSinceCommit` 达到阈值才 commit,压缩前无条件 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。- **TRAE / TRAE CN** — 采集直接读 Stop 事件的 `prompt`、`text_content`、`last_assistant_message`,不解析 transcript;每次带内容的 Stop 都 commit。会话前缀 `tr-` 与 `trcn-`。见 [TRAE 接入文档](../../docs/zh/agent-integrations/13-trae.md)。- **ZCode** — rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能补回漏掉的回合,hook stdin 只是兜底。ZCode 不支持 `PreCompact` 与 `SessionEnd`,因此每次 Stop 都 commit 来补足这两个信号。它的输出 schema 是严格的,所以放行时不写任何内容。会话前缀 `zc-`。已验证的扩展面记录在 [DESIGN.md](./DESIGN.md)。diff --git a/examples/agent-hook-plugin/hosts/cursor.mjs b/examples/agent-hook-plugin/hosts/cursor.mjsindex acc0a3fa2..33a4aefc3 100644--- a/examples/agent-hook-plugin/hosts/cursor.mjs+++ b/examples/agent-hook-plugin/hosts/cursor.mjs@@ -63,10 +63,11 @@ export const cursor = {return {};},guard(input = {}) {- const isShell = typeof input.command === "string";- const decision = evaluateUriGuard(isShell ? "bash" : "read", input);- if (!decision) return {};- return denyCursorPermission(decision.reason, { agentMessage: isShell });+ // beforeShellExecution is no longer installed, but a hooks.json from an+ // older install may still route a shell command here, and it must run.+ if (typeof input.command === "string") return {};+ const decision = evaluateUriGuard("read", input);+ return decision ? denyCursorPermission(decision.reason) : {};},prompt: (input) => (typeof input.prompt === "string" ? input.prompt.trim() : ""),async capture(ctx, state, event) {diff --git a/examples/agent-hook-plugin/hosts/cursor/hooks.json b/examples/agent-hook-plugin/hosts/cursor/hooks.jsonindex 6bfe6cb5d..080fd768f 100644--- a/examples/agent-hook-plugin/hosts/cursor/hooks.json+++ b/examples/agent-hook-plugin/hosts/cursor/hooks.json@@ -19,12 +19,6 @@"timeout": 5}],- "beforeShellExecution": [- {- "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",- "timeout": 5- }- ],"stop": [{"command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs stop __OPENVIKING_CLIENT_ID__",diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.jsonindex f8f111a71..5f8933281 100644--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json@@ -1,7 +1,7 @@{"schemaVersion": 1,"id": "openviking-memory",- "version": "0.3.0",+ "version": "0.3.1","clients": ["cursor"],diff --git a/examples/agent-hook-plugin/hosts/trae.mjs b/examples/agent-hook-plugin/hosts/trae.mjsindex 75f8a3a49..292952336 100644--- a/examples/agent-hook-plugin/hosts/trae.mjs+++ b/examples/agent-hook-plugin/hosts/trae.mjs@@ -4,7 +4,7 @@ import {stableHash,} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";import { filterCaptureTurns } from "../../memory-plugin-shared/lib/capture-utils.mjs";-import { denyHookSpecificOutput, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";+import { preToolUseOutput } from "../../memory-plugin-shared/lib/uri-guard.mjs";import { buildTraeTurns, cleanTraeText } from "./trae-turns.mjs";export const trae = {@@ -22,12 +22,7 @@ export const trae = {}return value;},- guard(input = {}) {- const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;- const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};- const decision = evaluateUriGuard(toolName, toolInput);- return decision ? denyHookSpecificOutput(decision.reason) : {};- },+ guard: (input) => preToolUseOutput(input),prompt: (input) => cleanTraeText(input.prompt),async capture(ctx, state) {const hashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.jsonindex 65758b85c..2d9b19eb7 100644--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json@@ -1,7 +1,7 @@{"schemaVersion": 1,"id": "openviking-memory",- "version": "0.3.0",+ "version": "0.3.1","clients": ["trae","trae-cn"diff --git a/examples/agent-hook-plugin/hosts/zcode.mjs b/examples/agent-hook-plugin/hosts/zcode.mjsindex c9bb4ccbf..d493787f2 100644--- a/examples/agent-hook-plugin/hosts/zcode.mjs+++ b/examples/agent-hook-plugin/hosts/zcode.mjs@@ -8,7 +8,7 @@*/import { addAgentMessages, commitAgentSession } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";-import { denyHookSpecificOutput, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";+import { preToolUseOutput } from "../../memory-plugin-shared/lib/uri-guard.mjs";import { applyZcodeCaptureResult, buildZcodeCapturePlan } from "./zcode-capture.mjs";import { buildZcodeTurns, cleanZcodeText } from "./zcode-turns.mjs";@@ -27,12 +27,9 @@ export const zcode = {},};},- guard(input = {}) {- const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;- const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};- const decision = evaluateUriGuard(toolName, toolInput);- return decision ? denyHookSpecificOutput(decision.reason) : {};- },+ // The matcher names no shell tool, so the notice never fires: ZCode's strict+ // schema is not verified to accept additionalContext on PreToolUse.+ guard: (input) => preToolUseOutput(input),// ZCode may pass sessionId in camelCase or snake_case. Ensure both are present// so resolveNativeSessionId() finds it via the direct lookup path — avoids the// cwd fallback that would collide for two windows in the same directory.diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.jsonindex b4a7b08b5..e768c5dd2 100644--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json@@ -1,7 +1,7 @@{"schemaVersion": 1,"id": "openviking-memory",- "version": "0.3.0",+ "version": "0.3.1","clients": ["zcode"],diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.jsonindex 01568e668..4b7843c62 100644--- a/examples/agent-hook-plugin/plugin.json+++ b/examples/agent-hook-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "agent-hook-plugin",- "version": "0.3.0",+ "version": "0.3.1","description": "Long-term semantic memory for the config-driven hook hosts — Cursor, TRAE, TRAE CN and ZCode — powered by OpenViking. Auto-recall relevant memories at session start and capture the conversation as it happens.","author": {"name": "OpenViking",diff --git a/examples/agent-hook-plugin/scripts/uri-guard.mjs b/examples/agent-hook-plugin/scripts/uri-guard.mjsindex dd7f63844..774cb4009 100644--- a/examples/agent-hook-plugin/scripts/uri-guard.mjs+++ b/examples/agent-hook-plugin/scripts/uri-guard.mjs@@ -3,7 +3,7 @@import { runUriGuardHook } from "../../memory-plugin-shared/lib/uri-guard.mjs";import { HOSTS } from "../hosts/index.mjs";-// The deny envelope is the host's: Cursor answers its own permission shape,+// The envelope is the host's: Cursor answers its own permission shape,// TRAE and ZCode the PreToolUse one.export function evaluateHostUriGuard(clientId, input = {}) {return HOSTS[clientId] ? HOSTS[clientId].guard(input) : {};diff --git a/examples/agent-hook-plugin/tests/cursor.test.mjs b/examples/agent-hook-plugin/tests/cursor.test.mjsindex 6a3fe2f4f..63c71ff9b 100644--- a/examples/agent-hook-plugin/tests/cursor.test.mjs+++ b/examples/agent-hook-plugin/tests/cursor.test.mjs@@ -42,7 +42,6 @@ test("Cursor command-installed integration contains Hook, Rule, Skill, and MCP e"sessionStart","beforeSubmitPrompt","beforeReadFile",- "beforeShellExecution","stop","preCompact","sessionEnd",@@ -53,18 +52,20 @@ test("Cursor URI guard redirects virtual paths to OpenViking MCP tools", () => {const readDecision = evaluateHostUriGuard("cursor", {file_path: "viking://resources/project/file.md",});+ assert.deepEqual(Object.keys(readDecision).sort(), ["permission", "user_message"]);assert.equal(readDecision.permission, "deny");assert.match(readDecision.user_message, /OpenViking MCP read/);- const shellDecision = evaluateHostUriGuard("cursor", {- command: "cat viking://resources/project/file.md",- });- assert.equal(shellDecision.permission, "deny");- assert.match(shellDecision.agent_message, /OpenViking MCP read or search/);-assert.deepEqual(evaluateHostUriGuard("cursor", { file_path: "/tmp/file.md" }), {});});+test("Cursor URI guard lets a shell command routed by an older install run", () => {+ assert.deepEqual(evaluateHostUriGuard("cursor", {+ command: "cat viking://resources/project/file.md",+ cwd: "/workspace",+ }), {});+});+test("Cursor transcript parser keeps only user and assistant text", () => {const raw = [JSON.stringify({ role: "user", message: { content: [{ type: "text", text: "question" }] } }),diff --git a/examples/agent-hook-plugin/tests/trae.test.mjs b/examples/agent-hook-plugin/tests/trae.test.mjsindex 1d5849ee3..1e3c1338b 100644--- a/examples/agent-hook-plugin/tests/trae.test.mjs+++ b/examples/agent-hook-plugin/tests/trae.test.mjs@@ -51,6 +51,26 @@ test("TRAE URI guard follows the Claude Code PreToolUse response contract", () =}), {});});+test("TRAE runs shell commands that carry a viking:// URI and attaches a notice", () => {+ const hooks = JSON.parse(readFileSync(join(pluginRoot, "hosts", "trae", "hooks.json"), "utf8"));+ const matcher = hooks.hooks.PreToolUse[0].matcher.split("|");+ for (const toolName of ["Bash", "RunCommand"]) {+ assert.ok(matcher.includes(toolName), `${toolName} must reach the URI guard`);+ const output = evaluateHostUriGuard("trae", {+ tool_name: toolName,+ tool_input: { command: "ov read viking://resources/project/file.md" },+ });+ assert.equal(output.hookSpecificOutput?.hookEventName, "PreToolUse", toolName);+ assert.equal(output.hookSpecificOutput?.permissionDecision, undefined, toolName);+ assert.match(output.hookSpecificOutput?.additionalContext ?? "", /viking:\/\/resources\/project\/file\.md/, toolName);+ assert.match(output.hookSpecificOutput?.additionalContext ?? "", /ignore this notice/, toolName);+ }+ assert.deepEqual(evaluateHostUriGuard("trae", {+ tool_name: "Bash",+ tool_input: { command: "cat /tmp/file.md" },+ }), {});+});+async function runHook(event, client, input, env) {const run = expectExit(await runHookScript(hookEntry, { argv: [event, client], input, env }));return JSON.parse(run.stdout.trim() || "{}");diff --git a/examples/agent-hook-plugin/tests/zcode.test.mjs b/examples/agent-hook-plugin/tests/zcode.test.mjsindex a4318074d..2111a4566 100644--- a/examples/agent-hook-plugin/tests/zcode.test.mjs+++ b/examples/agent-hook-plugin/tests/zcode.test.mjs@@ -60,6 +60,14 @@ test("uri guard deny for Glob with viking URI", () => {assert.equal(output.hookSpecificOutput.permissionDecision, "deny");});+test("uri guard pass-through for Grep searching local files for a viking URI", () => {+ const output = evaluateHostUriGuard("zcode", {+ tool_name: "Grep",+ tool_input: { pattern: "viking://user/", path: "/repo" },+ });+ assert.deepEqual(output, {});+});+test("uri guard handles alternative tool_input field names", () => {const output = evaluateHostUriGuard("zcode", {tool_name: "Read",@@ -76,17 +84,25 @@ test("uri guard handles alternative tool_name field names", () => {assert.equal(output.hookSpecificOutput?.permissionDecision, "deny");});-test("uri guard returns empty for unmatched tool name", () => {+test("uri guard notice for a shell command carries only hookEventName and additionalContext", () => {const output = evaluateHostUriGuard("zcode", {tool_name: "Bash",tool_input: { command: "cat viking://user/test.md" },});- // Bash is not in the Read|Glob|Grep matcher — but evaluateUriGuard- // may still detect viking:// in certain fields. The important assertion is- // that the output shape is valid (either empty or correct deny).- if (Object.keys(output).length > 0) {- assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");- }+ assert.deepEqual(Object.keys(output), ["hookSpecificOutput"]);+ assert.deepEqual(Object.keys(output.hookSpecificOutput).sort(), ["additionalContext", "hookEventName"]);+ assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");+ assert.match(output.hookSpecificOutput.additionalContext, /viking:\/\/user\/test\.md/);+ assert.match(output.hookSpecificOutput.additionalContext, /ignore this notice/);+});++test("PreToolUse matcher names no shell tool", () => {+ const hooks = JSON.parse(readFileSync(join(PLUGIN_ROOT, "hosts", "zcode", "hooks.json"), "utf8"));+ assert.deepEqual(+ hooks.hooks.PreToolUse.map((entry) => entry.matcher),+ ["Read|Glob|Grep"],+ "a shell tool here sends ZCode a PreToolUse additionalContext its strict schema is not verified to accept",+ );});// ---------------------------------------------------------------------------diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonindex a14b19be3..acf3a63dd 100644--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openviking-memory",- "version": "0.5.0",+ "version": "0.5.1","description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.","author": {"name": "OpenViking",diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex b1f0f8ab6..2106808a1 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -468,7 +468,8 @@ A persistent OpenViking session is created on first contact and reused for the e| `SessionEnd` | Claude Code session closes | Final commit so the last window is archived || `SubagentStart` | Parent spawns a subagent via Task tool | Derive an isolated OV session ID for the subagent, persist start state || `SubagentStop` | Subagent finishes | Read subagent transcript → push to an isolated session with subagent peer identity → commit |-| `PreToolUse` | Native `Read` / `Glob` / `Grep` on a `viking://` URI | Deny the call and point Claude to the equivalent OpenViking MCP tool |+| `PreToolUse` | Native `Read` / `Glob` / `Grep` / `Edit` / `Write` whose path is a `viking://` URI | Deny the call and point Claude to the equivalent OpenViking MCP tool |+| `PreToolUse` | `Bash` command that contains a `viking://` URI | Let the command run and attach a notice pointing Claude to the OpenViking MCP tools in case it meant OpenViking content || `PostToolUse` | `Read` of a `SKILL.md` file | Optional (default off): inject an experience block when OV has relevant skill-experience memories |### Async write pathdiff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex fc5f76e3c..76e927b40 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -418,7 +418,8 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:| `SessionEnd` | Claude Code 会话关闭 | 最后一次 commit || `SubagentStart` | 父 session 通过 Task 工具孵化子 agent | 为子 agent 派生隔离的 OV session ID,写 start state || `SubagentStop` | 子 agent 结束 | 读子 agent transcript → 推到带子 agent peer 身份的隔离 session → commit |-| `PreToolUse` | 原生 `Read` / `Glob` / `Grep` 指向 `viking://` URI | 拒绝该调用,提示 Claude 改用对应的 OpenViking MCP 工具 |+| `PreToolUse` | 原生 `Read` / `Glob` / `Grep` / `Edit` / `Write` 的路径是 `viking://` URI | 拒绝该调用,提示 Claude 改用对应的 OpenViking MCP 工具 |+| `PreToolUse` | `Bash` 命令里带 `viking://` URI | 照常执行命令,并附一条提醒:如果本意是访问 OpenViking 内容,应改用 OpenViking MCP 工具 || `PostToolUse` | `Read` 读到 `SKILL.md` 文件 | 可选(默认关闭):OV 有相关 skill 经验记忆时注入经验块 |### 异步写路径diff --git a/examples/claude-code-memory-plugin/hooks/hooks.json b/examples/claude-code-memory-plugin/hooks/hooks.jsonindex 79f32f401..c9402f608 100644--- a/examples/claude-code-memory-plugin/hooks/hooks.json+++ b/examples/claude-code-memory-plugin/hooks/hooks.json@@ -37,7 +37,7 @@],"PreToolUse": [{- "matcher": "Read|Glob|Grep",+ "matcher": "Read|Glob|Grep|Edit|Write|Bash","hooks": [{"type": "command",diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.jsonindex cc3309675..77baa8759 100644--- a/examples/claude-code-memory-plugin/package.json+++ b/examples/claude-code-memory-plugin/package.json@@ -1,6 +1,6 @@{"name": "claude-code-openviking-memory",- "version": "0.5.0",+ "version": "0.5.1","description": "OpenViking memory plugin for Claude Code — semantic long-term memory","type": "module","scripts": {diff --git a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjsindex a430ffd81..896fd3b4a 100644--- a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs@@ -79,12 +79,12 @@ test("Claude hooks include optional skill experience PostToolUse Read hook", ()execFileSync("node", ["--check", join(pluginDir, "scripts", "skill-experience.mjs")], { stdio: "pipe" });});-test("Claude hooks include PreToolUse URI guard for filesystem tools", () => {+test("Claude hooks include PreToolUse URI guard for file and shell tools", () => {const hooks = readJson(join(pluginDir, "hooks", "hooks.json"));const preToolUse = hooks.hooks?.PreToolUse;assert.ok(Array.isArray(preToolUse), "hooks.json must define PreToolUse hooks");- const guardHook = preToolUse.find((entry) => entry?.matcher === "Read|Glob|Grep");- assert.ok(guardHook, "PreToolUse must guard Read|Glob|Grep");+ const guardHook = preToolUse.find((entry) => entry?.matcher === "Read|Glob|Grep|Edit|Write|Bash");+ assert.ok(guardHook, "PreToolUse must guard Read|Glob|Grep|Edit|Write|Bash");assert.equal(guardHook.hooks?.[0]?.command,"node ${CLAUDE_PLUGIN_ROOT}/scripts/uri-guard.mjs",diff --git a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjsindex d90c3d5f3..9dde7ff43 100644--- a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs@@ -11,7 +11,6 @@ const DEFAULT_URI_KEYS = ["uri","target_uri","targetUri",- "pattern",];export function normalizeToolName(value) {@@ -81,6 +80,17 @@ export function buildGuardMessage(uri, hint = {}) {return lines.join("\n");}+export function buildGuardNotice(uri, hint = {}) {+ const lines = [+ `[OpenViking memory plugin] URI guard: this shell command contains the viking:// URI ${uri}.`,+ "viking:// URIs are OpenViking virtual paths, not local files, so cat, ls, grep and other file commands cannot open them.",+ `If you meant to read or search OpenViking content, use ${hint.tool || "the OpenViking MCP tools"} instead.`,+ ];+ if (hint.example) lines.push(`Example: ${hint.example}`);+ lines.push("If the URI is intentional data (an ov CLI argument, an HTTP payload, a search pattern), ignore this notice.");+ return lines.join("\n");+}+/** The hints a host gets when it names no table of its own. */export const DEFAULT_TOOL_HINTS = {read: {@@ -99,6 +109,14 @@ export const DEFAULT_TOOL_HINTS = {`grep(uri="${uri}", pattern="${String(input.pattern ?? "").replaceAll('"', '\\"')}")`),},+ edit: {+ tool: "OpenViking MCP edit",+ example: (uri) => `edit(uri="${uri}", old_string="...", new_string="...")`,+ },+ write: {+ tool: "OpenViking MCP write",+ example: (uri) => `write(uri="${uri}", content="...")`,+ },bash: {tool: "OpenViking MCP read or search",example: (uri) => `read(uris="${uri}")`,@@ -113,30 +131,54 @@ export const DEFAULT_TOOL_HINTS = {},};-/**- * The guard decision for one tool call, or null when the call may proceed.- *- * `hints` carries the host's replacement tool names and example calls; `guarded`- * narrows which tool names the host guards at all, because the set is not the- * same everywhere — claude-code and opencode leave the shell alone (their- * matchers never see it), pi guards it.- */-export function evaluateUriGuard(toolName, input = {}, { hints = DEFAULT_TOOL_HINTS, guarded } = {}) {+// Tools whose argument is a command line rather than a location. A viking:// URI+// in one is data (an `ov` argument, an HTTP payload, a grep pattern) as often as+// a path the model hoped to open, so the command runs and the model gets a notice.+const SHELL_TOOL_NAMES = new Set(["bash", "shell", "runcommand"]);++// `pattern` is where glob looks but what grep looks for: a grep for the text+// "viking://" in a local tree is not a path. The generic sweep still reaches+// glob's pattern.+const TEXT_ARGS_BY_TOOL = { grep: ["pattern"] };++function resolveGuardedUri(toolName, input, { hints = DEFAULT_TOOL_HINTS } = {}) {const name = normalizeToolName(toolName);- if (guarded && !guarded.has(name)) return null;const hint = hints[name];if (!hint) return null;- const uri = findVikingUri(input);+ const textArgs = TEXT_ARGS_BY_TOOL[name];+ const uri = findVikingUri(input, DEFAULT_URI_KEYS, textArgs ? [...DEFAULT_CONTENT_KEYS, ...textArgs] : DEFAULT_CONTENT_KEYS);if (!uri) return null;return {uri,- reason: buildGuardMessage(uri, {+ shell: SHELL_TOOL_NAMES.has(name),+ hint: {tool: hint.tool,example: typeof hint.example === "function" ? hint.example(uri, input) : hint.example,- }),+ },};}+/**+ * The deny decision for one tool call, or null when the call may proceed.+ *+ * A file tool whose path is a viking:// URI cannot succeed, and a write would+ * leave a junk local file, so it is denied. A shell tool is never denied here;+ * `evaluateUriNotice` covers it. `hints` carries the host's replacement tool+ * names and example calls, and a tool without a hint is not guarded.+ */+export function evaluateUriGuard(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match || match.shell) return null;+ return { uri: match.uri, reason: buildGuardMessage(match.uri, match.hint) };+}++/** The notice for a shell command that carries a viking:// URI, or null. The command still runs. */+export function evaluateUriNotice(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match?.shell) return null;+ return { uri: match.uri, reason: buildGuardNotice(match.uri, match.hint) };+}+/** The PreToolUse deny envelope claude-code, trae and zcode all read. */export function denyHookSpecificOutput(reason) {return {@@ -148,11 +190,31 @@ export function denyHookSpecificOutput(reason) {};}-/** Cursor's deny envelope; its shell hook also wants the reason for the agent. */-export function denyCursorPermission(reason, { agentMessage = false } = {}) {- const output = { permission: "deny", user_message: reason };- if (agentMessage) output.agent_message = reason;- return output;+/** The PreToolUse notice envelope: no permissionDecision, so the host's own permission flow still runs. */+export function noticeHookSpecificOutput(reason) {+ return { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: reason } };+}++/** A hook event's tool name and input, under any of the spellings the hosts use. */+export function readToolEvent(event = {}) {+ return {+ toolName: event.tool_name ?? event.toolName ?? event.name ?? event.tool,+ toolInput: event.tool_input ?? event.toolInput ?? event.input ?? {},+ };+}++/** The whole PreToolUse guard: a deny envelope, a notice envelope, or {}. */+export function preToolUseOutput(event = {}, opts = {}) {+ const { toolName, toolInput } = readToolEvent(event);+ const denied = evaluateUriGuard(toolName, toolInput, opts);+ if (denied) return denyHookSpecificOutput(denied.reason);+ const notice = evaluateUriNotice(toolName, toolInput, opts);+ return notice ? noticeHookSpecificOutput(notice.reason) : {};+}++/** Cursor's beforeReadFile deny envelope. */+export function denyCursorPermission(reason) {+ return { permission: "deny", user_message: reason };}function readHookInput() {diff --git a/examples/claude-code-memory-plugin/scripts/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/uri-guard.mjsindex 0bf14896e..8ad6eaadf 100644--- a/examples/claude-code-memory-plugin/scripts/uri-guard.mjs+++ b/examples/claude-code-memory-plugin/scripts/uri-guard.mjs@@ -1,21 +1,7 @@#!/usr/bin/env node-import {- denyHookSpecificOutput,- evaluateUriGuard,- runUriGuardHook,-} from "./shared/uri-guard.mjs";+import { preToolUseOutput, runUriGuardHook } from "./shared/uri-guard.mjs";-// Claude Code names the same MCP tools as the shared hints, so only the guarded-// set is host data: Bash is left alone, a viking:// URI inside a shell command-// reaches the model.-const GUARDED_TOOLS = new Set(["read", "glob", "grep"]);--export function evaluatePreToolUse(input = {}) {- const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;- const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};- const decision = evaluateUriGuard(toolName, toolInput, { guarded: GUARDED_TOOLS });- return decision ? denyHookSpecificOutput(decision.reason) : {};-}+export const evaluatePreToolUse = (input = {}) => preToolUseOutput(input);runUriGuardHook(import.meta.url, evaluatePreToolUse);diff --git a/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs b/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjsindex 4b130a3be..40645040d 100644--- a/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs+++ b/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs@@ -13,7 +13,49 @@ test("Claude URI guard denies filesystem Read on viking URI", () => {assert.match(out.hookSpecificOutput?.permissionDecisionReason ?? "", /OpenViking MCP read/);});-test("Claude URI guard allows local paths and unrelated tools", () => {+test("Claude URI guard denies Write to a viking URI path", () => {+ const out = evaluatePreToolUse({+ tool_name: "Write",+ tool_input: { file_path: "viking://resources/project/new.md", content: "hello" },+ });++ assert.equal(out.hookSpecificOutput?.permissionDecision, "deny");+ assert.match(out.hookSpecificOutput?.permissionDecisionReason ?? "", /OpenViking MCP write/);+});++test("Claude URI guard lets Bash carrying a viking URI run with a notice", () => {+ const out = evaluatePreToolUse({+ tool_name: "Bash",+ tool_input: { command: "ov read viking://resources/a.md" },+ });++ assert.equal(out.hookSpecificOutput?.hookEventName, "PreToolUse");+ assert.equal(out.hookSpecificOutput?.permissionDecision, undefined);+ assert.equal(out.hookSpecificOutput?.permissionDecisionReason, undefined);+ assert.match(out.hookSpecificOutput?.additionalContext ?? "", /viking:\/\/resources\/a\.md/);+ assert.match(out.hookSpecificOutput?.additionalContext ?? "", /ignore this notice/);+});++test("Claude URI guard allows local paths, URI text in content and unrelated tools", () => {assert.deepEqual(evaluatePreToolUse({ tool_name: "Read", tool_input: { file_path: "/tmp/a.md" } }), {});- assert.deepEqual(evaluatePreToolUse({ tool_name: "Bash", tool_input: { command: "cat viking://resources/a.md" } }), {});+ assert.deepEqual(evaluatePreToolUse({ tool_name: "Bash", tool_input: { command: "ls -la /tmp" } }), {});+ assert.deepEqual(+ evaluatePreToolUse({+ tool_name: "Edit",+ tool_input: {+ file_path: "/repo/README.md",+ old_string: "local/path",+ new_string: "viking://resources/a.md",+ },+ }),+ {},+ );+ assert.deepEqual(+ evaluatePreToolUse({ tool_name: "Grep", tool_input: { pattern: "viking://", path: "/repo" } }),+ {},+ );+ assert.deepEqual(+ evaluatePreToolUse({ tool_name: "WebFetch", tool_input: { url: "viking://resources/a.md" } }),+ {},+ );});diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.jsonindex 59b17d1fc..d85e5d27e 100644--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openviking-memory",- "version": "0.9.0",+ "version": "0.9.1","description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.","author": {"name": "OpenViking",diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex b751e9738..f0a413498 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -11,6 +11,7 @@ This is the Codex counterpart to [`claude-code-memory-plugin`](../claude-code-me- **Session-start profile injection** on `startup`, `clear`, and `resume`: load `profile.md` plus abstract-annotated indexes of `preferences/` and `entities/` through the shared CJK-aware profile builder.- **Auto-recall** relevant memories on every `UserPromptSubmit` and inject them via `hookSpecificOutput.additionalContext`+- **`viking://` notice on `PreToolUse` (`Bash`)**: a shell command that carries a `viking://` URI still runs, and the model is told that the URI is an OpenViking virtual path and which MCP tool reads it.- **Incremental capture on `Stop`** (turn end): append the new user/assistant turns to a deterministic OpenViking session id `cx-<codex_session_id>`. When `pending_tokens` reaches `OPENVIKING_COMMIT_TOKEN_THRESHOLD`, commit while keeping a recent live tail.- **Commit on `PreCompact`**: trigger OpenViking's memory extractor on the full pre-compact transcript before Codex summarizes it.- **Commit on `SessionEnd`** (Codex ≥ 0.145): when a thread shuts down gracefully, catch up any turns `Stop` never sent and commit the OV session, so the extractor runs on the whole conversation the moment you leave.@@ -332,6 +333,14 @@ Client-side knobs can also live in `~/.openviking/ovcli.conf` underlayers; resolution order is env vars → the workspace layers → `plugin.codex` →`plugin` → the legacy `codex` block in `ov.conf` → defaults.+### viking:// URI notice (PreToolUse on Bash)++`viking://` URIs are OpenViking virtual paths, so `cat viking://…` or `ls viking://…` cannot open them. `uri-guard.mjs` runs before every `Bash` call. When the command contains a `viking://` URI, it returns `hookSpecificOutput.additionalContext` without a `permissionDecision`: the command runs unchanged, and the model is told which OpenViking MCP tool reads the URI and to ignore the notice when the URI is intentional data (an `ov` CLI argument, an HTTP payload, a search pattern). A command without a `viking://` URI gets no output.++Nothing is denied: Codex edits files through `apply_patch`, whose input is a patch body rather than a path (Codex's `Edit` / `Write` matchers are aliases for it), so there is no path argument to guard.++> **Upgrading to 0.9.1**: `PreToolUse` is a newly registered hook event. Run `/hooks` in Codex after updating and approve it; until then shell commands run without the notice.+### Stop (turn end → `add_message`, threshold commit)`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append. Tool calls and results become dedicated `tool` parts and `tool_output` is reported verbatim — the server externalizes anything larger than `tool_output_externalization.threshold_chars` (default `20000`) and leaves a synopsis stub plus `tool_output_ref`, so the original stays readable via `/api/v1/sessions/{id}/tool-results`. `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default `1000000`) is only a guard against pathological payloads. Configured `captureFilters` rules run last, just before the payload is sent — see [Input filters](#input-filters).@@ -368,6 +377,7 @@ Codex's hook output schema differs from Claude Code's. Notably:|------|------------------------|--------------------------------------|| `SessionStart` | `source` (`startup`/`resume`/`clear`), `session_id`, `cwd` | `hookSpecificOutput.additionalContext`; may also include `systemMessage` when an orphaned session was committed || `UserPromptSubmit` | `prompt`, `session_id` | `hookSpecificOutput.additionalContext` |+| `PreToolUse` (`Bash`) | `tool_name`, `tool_input.command` | `hookSpecificOutput.additionalContext` with no `permissionDecision`, so the command still runs; no output when the command has no `viking://` URI || `Stop` | `last_assistant_message`, `transcript_path`, `session_id` | `systemMessage` (only) || `PreCompact` | `trigger` (`manual`/`auto`), `transcript_path`, `session_id` | `systemMessage` (only) || `SessionEnd` | `session_id`, `transcript_path`, `cwd`, `reason` (constant `other`) | none — Codex ignores the output; the script prints `{}` for symmetry |@@ -427,9 +437,9 @@ codex-memory-plugin/├── .codex-plugin/│ └── plugin.json # Plugin manifest (hooks + mcp wiring)├── hooks/-│ └── hooks.json # SessionStart + UserPromptSubmit + Stop + SessionEnd-│ + PreCompact (uses Codex's native ${PLUGIN_ROOT}-│ token; no rendering needed on modern Codex)+│ └── hooks.json # SessionStart + UserPromptSubmit + PreToolUse + Stop+│ + SessionEnd + PreCompact (uses Codex's native+│ ${PLUGIN_ROOT} token; no rendering needed on modern Codex)├── skills/│ ├── openviking-memory/ # How to use the memory tools│ ├── ov-experience-memory/@@ -447,6 +457,7 @@ codex-memory-plugin/│ ├── session-start-commit.mjs # SessionStart hook (profile + fallback sweep + resume archive)│ ├── session-end.mjs # SessionEnd hook (mark + detached catch-up + commit)│ ├── pre-compact-capture.mjs # PreCompact hook+│ ├── uri-guard.mjs # PreToolUse hook (viking:// notice on Bash)│ └── *.test.mjs # node --test suites (session-end, pre-compact, ...)├── servers/│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp bridgediff --git a/examples/codex-memory-plugin/hooks/hooks.json b/examples/codex-memory-plugin/hooks/hooks.jsonindex 6a1470dc7..4117d3b5f 100644--- a/examples/codex-memory-plugin/hooks/hooks.json+++ b/examples/codex-memory-plugin/hooks/hooks.json@@ -24,6 +24,18 @@]}],+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/scripts/uri-guard.mjs\"",+ "timeout": 5+ }+ ]+ }+ ],"Stop": [{"matcher": "*",diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjsindex d1cc3047d..1c8b5b54a 100644--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs@@ -125,6 +125,8 @@ test("required plugin files are present", () => {"skills/ov-memory-doctor/reference.md","scripts/ov-memory-doctor.mjs","scripts/shared/doctor-core.mjs",+ "scripts/uri-guard.mjs",+ "scripts/shared/uri-guard.mjs",]) {assert.ok(existsSync(join(pluginDir, rel)), `missing required plugin file: ${rel}`);}@@ -156,7 +158,7 @@ test("hooks.json uses Codex's native ${PLUGIN_ROOT}, not the legacy placeholder".flat().flatMap((group) => group.hooks || []).map((h) => h.command || "");- assert.ok(commands.length >= 5, "expected at least 5 hook commands (SessionStart/UserPromptSubmit/Stop/SessionEnd/PreCompact)");+ assert.ok(commands.length >= 6, "expected at least 6 hook commands (SessionStart/UserPromptSubmit/PreToolUse/Stop/SessionEnd/PreCompact)");for (const cmd of commands) {assert.match(cmd,@@ -175,6 +177,18 @@ test("hooks.json registers SessionEnd within Codex's clamped budget", () => {assert.ok(entries[0].timeout <= 3, `SessionEnd timeout must be <= 3, got ${entries[0].timeout}`);});+test("hooks.json registers the PreToolUse URI guard on Bash only", () => {+ // Codex's Edit and Write matchers are aliases for apply_patch, whose input is+ // a patch body with no path argument to guard.+ const parsed = JSON.parse(readFileSync(join(pluginDir, "hooks", "hooks.json"), "utf-8"));+ const groups = parsed.hooks?.PreToolUse || [];+ assert.deepEqual(groups.map((group) => group.matcher), ["Bash"]);+ const entries = groups.flatMap((group) => group.hooks || []);+ assert.equal(entries.length, 1, "expected exactly one PreToolUse hook");+ assert.equal(entries[0].command, 'node "${PLUGIN_ROOT}/scripts/uri-guard.mjs"');+ execFileSync("node", ["--check", join(pluginDir, "scripts", "uri-guard.mjs")], { stdio: "pipe" });+});+test(".mcp.json starts the stdio MCP proxy from the plugin root", () => {const mcp = readJson(join(pluginDir, ".mcp.json"));const server = mcp.mcpServers?.[PLUGIN_NAME];diff --git a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjsindex 74181b42c..ca4760a47 100644--- a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs+++ b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs@@ -52,8 +52,8 @@ const LEGACY_MARKETPLACE = "openviking-plugins-local";const CODEX_DIR = join(homedir(), ".codex");const CODEX_CONFIG = process.env.CODEX_CONFIG_FILE || join(CODEX_DIR, "config.toml");const CACHE_DIR = join(CODEX_DIR, "plugins", "cache", MARKETPLACE, PLUGIN_NAME);-const HOOK_EVENTS = ["session_start", "user_prompt_submit", "stop", "session_end", "pre_compact"];-const REQUIRED_PLUGIN_FILES = [".codex-plugin/plugin.json", "hooks/hooks.json", ".mcp.json", "servers/mcp-proxy.mjs", "scripts/config.mjs", "scripts/auto-recall.mjs", "scripts/auto-capture.mjs", "scripts/session-end.mjs", "scripts/ov-session.mjs"];+const HOOK_EVENTS = ["session_start", "user_prompt_submit", "pre_tool_use", "stop", "session_end", "pre_compact"];+const REQUIRED_PLUGIN_FILES = [".codex-plugin/plugin.json", "hooks/hooks.json", ".mcp.json", "servers/mcp-proxy.mjs", "scripts/config.mjs", "scripts/auto-recall.mjs", "scripts/auto-capture.mjs", "scripts/session-end.mjs", "scripts/ov-session.mjs", "scripts/uri-guard.mjs"];/*** Minimal TOML reader — enough for config.toml's [section] headers (including@@ -275,7 +275,7 @@ function checkInstall(report, { cliOnPath }) {else trusted.push(event);}if (disabled.length) report.fail(`hooks disabled in [hooks.state]: ${disabled.join(", ")}`, "", `remove enabled = false from those [hooks.state] sections in ${homeShort(CODEX_CONFIG)}`);- if (untrusted.length) report.info(`hooks without a trust record yet: ${untrusted.join(", ")} (Codex records trusted_hash the first time a hook is approved; a changed hooks.json — including a newly added event such as session_end — needs re-approval)`);+ if (untrusted.length) report.info(`hooks without a trust record yet: ${untrusted.join(", ")} (Codex records trusted_hash the first time a hook is approved; a changed hooks.json — including a newly added event such as pre_tool_use — needs re-approval)`);if (trusted.length === HOOK_EVENTS.length) report.ok(`all ${HOOK_EVENTS.length} hooks have trust records in config.toml`);const legacyKeys = Object.keys(toml).filter((k) => k.includes(LEGACY_MARKETPLACE));if (legacyKeys.length) report.info(`config.toml still has ${legacyKeys.length} section(s) for the legacy id ${LEGACY_MARKETPLACE} (harmless)`);diff --git a/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs b/examples/codex-memory-plugin/scripts/shared/uri-guard.mjsnew file mode 100644index 000000000..9dde7ff43--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs@@ -0,0 +1,250 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import { readFileSync, realpathSync } from "node:fs";+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";++const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++// Arguments that carry file CONTENT rather than a location. The sweep below+// looks past the known path keys so an unusual one (`paths`, a nested target)+// is still caught, but text a tool is asked to WRITE is not a path: a local+// `write` whose body merely mentions viking://user/default/ was denied, and no+// file was created. Skipped by name at any depth.+const DEFAULT_CONTENT_KEYS = [+ "content",+ "contents",+ "text",+ "body",+ "old_string",+ "oldString",+ "new_string",+ "newString",+ "old_str",+ "new_str",+ "file_text",+ "insert_line",+ "replacement",+];++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args, new Set(contentKeys));+}++export function findVikingUriInValue(value, skipKeys) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item, skipKeys);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const [key, item] of Object.entries(value)) {+ if (skipKeys?.has(key)) continue;+ const uri = findVikingUriInValue(item, skipKeys);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}++export function buildGuardNotice(uri, hint = {}) {+ const lines = [+ `[OpenViking memory plugin] URI guard: this shell command contains the viking:// URI ${uri}.`,+ "viking:// URIs are OpenViking virtual paths, not local files, so cat, ls, grep and other file commands cannot open them.",+ `If you meant to read or search OpenViking content, use ${hint.tool || "the OpenViking MCP tools"} instead.`,+ ];+ if (hint.example) lines.push(`Example: ${hint.example}`);+ lines.push("If the URI is intentional data (an ov CLI argument, an HTTP payload, a search pattern), ignore this notice.");+ return lines.join("\n");+}++/** The hints a host gets when it names no table of its own. */+export const DEFAULT_TOOL_HINTS = {+ read: {+ tool: "OpenViking MCP read",+ example: (uri) => `read(uris="${uri}")`,+ },+ glob: {+ tool: "OpenViking MCP glob or list",+ example: (uri, input = {}) => (+ `glob(pattern="${String(input.pattern ?? "**/*").replaceAll('"', '\\"')}", uri="${uri}")`+ ),+ },+ grep: {+ tool: "OpenViking MCP grep or search",+ example: (uri, input = {}) => (+ `grep(uri="${uri}", pattern="${String(input.pattern ?? "").replaceAll('"', '\\"')}")`+ ),+ },+ edit: {+ tool: "OpenViking MCP edit",+ example: (uri) => `edit(uri="${uri}", old_string="...", new_string="...")`,+ },+ write: {+ tool: "OpenViking MCP write",+ example: (uri) => `write(uri="${uri}", content="...")`,+ },+ bash: {+ tool: "OpenViking MCP read or search",+ example: (uri) => `read(uris="${uri}")`,+ },+ runcommand: {+ tool: "OpenViking MCP read or search",+ example: (uri) => `read(uris="${uri}")`,+ },+ shell: {+ tool: "OpenViking MCP read or search",+ example: (uri) => `read(uris="${uri}")`,+ },+};++// Tools whose argument is a command line rather than a location. A viking:// URI+// in one is data (an `ov` argument, an HTTP payload, a grep pattern) as often as+// a path the model hoped to open, so the command runs and the model gets a notice.+const SHELL_TOOL_NAMES = new Set(["bash", "shell", "runcommand"]);++// `pattern` is where glob looks but what grep looks for: a grep for the text+// "viking://" in a local tree is not a path. The generic sweep still reaches+// glob's pattern.+const TEXT_ARGS_BY_TOOL = { grep: ["pattern"] };++function resolveGuardedUri(toolName, input, { hints = DEFAULT_TOOL_HINTS } = {}) {+ const name = normalizeToolName(toolName);+ const hint = hints[name];+ if (!hint) return null;+ const textArgs = TEXT_ARGS_BY_TOOL[name];+ const uri = findVikingUri(input, DEFAULT_URI_KEYS, textArgs ? [...DEFAULT_CONTENT_KEYS, ...textArgs] : DEFAULT_CONTENT_KEYS);+ if (!uri) return null;+ return {+ uri,+ shell: SHELL_TOOL_NAMES.has(name),+ hint: {+ tool: hint.tool,+ example: typeof hint.example === "function" ? hint.example(uri, input) : hint.example,+ },+ };+}++/**+ * The deny decision for one tool call, or null when the call may proceed.+ *+ * A file tool whose path is a viking:// URI cannot succeed, and a write would+ * leave a junk local file, so it is denied. A shell tool is never denied here;+ * `evaluateUriNotice` covers it. `hints` carries the host's replacement tool+ * names and example calls, and a tool without a hint is not guarded.+ */+export function evaluateUriGuard(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match || match.shell) return null;+ return { uri: match.uri, reason: buildGuardMessage(match.uri, match.hint) };+}++/** The notice for a shell command that carries a viking:// URI, or null. The command still runs. */+export function evaluateUriNotice(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match?.shell) return null;+ return { uri: match.uri, reason: buildGuardNotice(match.uri, match.hint) };+}++/** The PreToolUse deny envelope claude-code, trae and zcode all read. */+export function denyHookSpecificOutput(reason) {+ return {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: reason,+ },+ };+}++/** The PreToolUse notice envelope: no permissionDecision, so the host's own permission flow still runs. */+export function noticeHookSpecificOutput(reason) {+ return { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: reason } };+}++/** A hook event's tool name and input, under any of the spellings the hosts use. */+export function readToolEvent(event = {}) {+ return {+ toolName: event.tool_name ?? event.toolName ?? event.name ?? event.tool,+ toolInput: event.tool_input ?? event.toolInput ?? event.input ?? {},+ };+}++/** The whole PreToolUse guard: a deny envelope, a notice envelope, or {}. */+export function preToolUseOutput(event = {}, opts = {}) {+ const { toolName, toolInput } = readToolEvent(event);+ const denied = evaluateUriGuard(toolName, toolInput, opts);+ if (denied) return denyHookSpecificOutput(denied.reason);+ const notice = evaluateUriNotice(toolName, toolInput, opts);+ return notice ? noticeHookSpecificOutput(notice.reason) : {};+}++/** Cursor's beforeReadFile deny envelope. */+export function denyCursorPermission(reason) {+ return { permission: "deny", user_message: reason };+}++function readHookInput() {+ try {+ const raw = readFileSync(0, "utf8").trim();+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++/**+ * Run a guard as a hook process: read the event off stdin, print the envelope.+ *+ * A guard is also imported by its harness tests, so the body only runs when the+ * module is the process entrypoint. An empty envelope prints nothing — every+ * host treats unrecognized or empty output as "no opinion", and one of them+ * rejects any key it does not know.+ */+function isEntrypoint(moduleUrl) {+ if (!process.argv[1]) return false;+ try {+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(moduleUrl));+ } catch {+ return resolve(process.argv[1]) === fileURLToPath(moduleUrl);+ }+}++export function runUriGuardHook(moduleUrl, evaluate) {+ if (!isEntrypoint(moduleUrl)) return;+ const output = evaluate(readHookInput());+ if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);+}diff --git a/examples/codex-memory-plugin/scripts/uri-guard.mjs b/examples/codex-memory-plugin/scripts/uri-guard.mjsnew file mode 100644index 000000000..8ad6eaadf--- /dev/null+++ b/examples/codex-memory-plugin/scripts/uri-guard.mjs@@ -0,0 +1,7 @@+#!/usr/bin/env node++import { preToolUseOutput, runUriGuardHook } from "./shared/uri-guard.mjs";++export const evaluatePreToolUse = (input = {}) => preToolUseOutput(input);++runUriGuardHook(import.meta.url, evaluatePreToolUse);diff --git a/examples/codex-memory-plugin/scripts/uri-guard.test.mjs b/examples/codex-memory-plugin/scripts/uri-guard.test.mjsnew file mode 100644index 000000000..d942fc5e8--- /dev/null+++ b/examples/codex-memory-plugin/scripts/uri-guard.test.mjs@@ -0,0 +1,57 @@+import test from "node:test";+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { evaluatePreToolUse } from "./uri-guard.mjs";++const scriptPath = join(dirname(fileURLToPath(import.meta.url)), "uri-guard.mjs");++function codexEvent(toolName, toolInput) {+ return {+ session_id: "019a0000-0000-7000-8000-000000000000",+ turn_id: "turn-1",+ tool_use_id: "call-1",+ hook_event_name: "PreToolUse",+ cwd: "/repo",+ permission_mode: "default",+ tool_name: toolName,+ tool_input: toolInput,+ };+}++test("Codex URI guard lets Bash carrying a viking URI run with a notice", () => {+ const out = evaluatePreToolUse(codexEvent("Bash", { command: "ov read viking://resources/a.md" }));++ assert.equal(out.hookSpecificOutput?.hookEventName, "PreToolUse");+ assert.equal(out.hookSpecificOutput?.permissionDecision, undefined);+ assert.equal(out.hookSpecificOutput?.permissionDecisionReason, undefined);+ assert.match(out.hookSpecificOutput?.additionalContext ?? "", /viking:\/\/resources\/a\.md/);+ assert.match(out.hookSpecificOutput?.additionalContext ?? "", /ignore this notice/);+});++test("Codex URI guard notices a command given as an argv array", () => {+ const out = evaluatePreToolUse(codexEvent("Bash", { command: ["bash", "-lc", "cat viking://user/memories/a.md"] }));++ assert.equal(out.hookSpecificOutput?.permissionDecision, undefined);+ assert.match(out.hookSpecificOutput?.additionalContext ?? "", /viking:\/\/user\/memories\/a\.md/);+});++test("Codex URI guard stays silent for plain commands and apply_patch", () => {+ assert.deepEqual(evaluatePreToolUse(codexEvent("Bash", { command: "ls -la /tmp" })), {});+ assert.deepEqual(+ evaluatePreToolUse(codexEvent("apply_patch", {+ command: "*** Begin Patch\n*** Update File: README.md\n@@\n-local/path\n+viking://resources/docs\n*** End Patch\n",+ })),+ {},+ );+});++test("Codex URI guard hook prints the notice envelope and nothing otherwise", () => {+ const run = (event) => execFileSync("node", [scriptPath], { input: JSON.stringify(event), encoding: "utf-8" });++ const notice = JSON.parse(run(codexEvent("Bash", { command: "curl -d '{\"uri\":\"viking://resources/a\"}' http://127.0.0.1:1933" })));+ assert.deepEqual(Object.keys(notice), ["hookSpecificOutput"]);+ assert.deepEqual(Object.keys(notice.hookSpecificOutput).sort(), ["additionalContext", "hookEventName"]);+ assert.equal(run(codexEvent("Bash", { command: "echo hello" })), "");+});diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.mdindex fd8c646a1..9fa7cb31b 100644--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md@@ -14,7 +14,7 @@ and `CODEX_CONFIG_FILE` relocate individual pieces.| `~/.openviking/ovcli.conf.<name>` | Saved CLI profiles (`ov config switch` copies one over `ovcli.conf`). `ovcli.conf.bak.<epoch>` are installer backups. || `<repo root>/.openviking/config.json` / `config.local.json` | Workspace config layers, `version: 1` required: `peer.source`, `peer.id`, `recall.*`, `capture.*`, `bypass.session_patterns`, `labels`. `config.json` is committed and shared; `config.local.json` is private and gitignored. Trusted without a prompt, but connection and credential keys (`url`, `api_key`, `account`, `user`, `extra_headers`, …) are stripped with a warning and `${VAR}` is never expanded. A blanket `.openviking/` rule in `.gitignore` stops `config.json` from ever being committed — narrow it to `.openviking/media/` and `.openviking/downloads/`. || `~/.openviking/workspaces/<slot>.json` | Per-machine workspace registry, one file per workspace (`<dir name>-<hash>.json`, mode 0600). Outranks both workspace files, and nothing writes it — a user creates the file by hand. An entry recorded for a different repository is ignored, not inherited. |-| `~/.codex/config.toml` | `[features] hooks` (or legacy `plugin_hooks`), `[plugins."openviking-memory@openviking"] enabled`, `[marketplaces.openviking]` (source, ref), `[hooks.state."openviking-memory@openviking:hooks/hooks.json:<event>:0:0"] trusted_hash` for `session_start`, `user_prompt_submit`, `stop`, `session_end`, `pre_compact`. |+| `~/.codex/config.toml` | `[features] hooks` (or legacy `plugin_hooks`), `[plugins."openviking-memory@openviking"] enabled`, `[marketplaces.openviking]` (source, ref), `[hooks.state."openviking-memory@openviking:hooks/hooks.json:<event>:0:0"] trusted_hash` for `session_start`, `user_prompt_submit`, `pre_tool_use`, `stop`, `session_end`, `pre_compact`. || `~/.codex/plugins/cache/openviking/openviking-memory/<version>/` | The copy Codex runs hooks from. Keyed by `plugin.json` version. || `~/.codex/.tmp/marketplaces/openviking/` | Git clone of the marketplace (GitHub/TOS dist); `examples/codex-memory-plugin` inside it is what `codex plugin list` reports as the source path. || `~/.openviking/codex-plugin-state/<session_id>.json` | Per-session state: `ovSessionId` (`cx-<session_id>`, null once committed), `transcriptPath` (last rollout seen, used by the SessionStart sweep to catch up unsent turns), `capturedTurnCount`, `lastUpdatedAt`. |@@ -50,9 +50,10 @@ Codex plugin. Disable features with `OPENVIKING_AUTO_RECALL=0`,`codex plugin remove openviking-memory@openviking` / `enabled = false`.Hook budgets in `hooks/hooks.json`: SessionStart 70s, UserPromptSubmit 130s,-Stop 30s, SessionEnd 3s (Codex clamps it there; the hook detaches a worker),-PreCompact 60s. `recallTimeoutMs` (default 120000) must stay below-130s and `captureTimeoutMs` (default 30000) at or below 30s.+PreToolUse 5s (`Bash` only, the `viking://` notice), Stop 30s, SessionEnd 3s+(Codex clamps it there; the hook detaches a worker), PreCompact 60s.+`recallTimeoutMs` (default 120000) must stay below 130s and `captureTimeoutMs`+(default 30000) at or below 30s.Sent headers: `Authorization: Bearer <key>`, `X-OpenViking-Account/User` (trustedmode only), `X-OpenViking-Actor-Peer`, `User-Agent: openviking-memory-codex/<version>`.diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.mdindex 1f4502f7a..fc6a6c19a 100644--- a/examples/dsh-memory-plugin/README.md+++ b/examples/dsh-memory-plugin/README.md@@ -201,7 +201,8 @@ The patch can also carry plugin config:- `skipSubagentSessions: true` excludes sessions marked with `header.origin: subagent` from automatic profile, recall, capture, and commit; it defaults to `false`.- `syncTurns: false` stops every new write: no captured messages, no threshold or shutdown commit. Writes queued while the toggle was on are still replayed by the background drainer once the server recovers — they were captured with the toggle on. Profile injection and recall are unaffected; it defaults to `true`.- Failed writes enter the shared OpenViking pending queue. A background drainer (default every 60s, `OPENVIKING_PENDING_DRAIN_INTERVAL_MS`) probes the server health and replays the queue in-process, so a transient write failure recovers without restarting dsh; it does not consume the session-start retry budget. Session-start replays keep consuming retries as before.-- `tools/pre-execute` blocks DSH filesystem and shell tools from treating `viking://` URIs as local paths, pointing the model at the bridged `mcp__openviking__*` tools instead.+- `tools/pre-execute` denies a DSH filesystem tool (`read`, `glob`, `grep`, `edit`, `write`, `str_replace_editor`) whose path argument is a `viking://` URI, pointing the model at the bridged `mcp__openviking__*` tools instead. A `grep` whose pattern is `viking://` text still runs.+- `tools/post-execute` lets a `bash` command that carries a `viking://` URI run unchanged and attaches a notice for the model: use the bridged tools if it meant OpenViking content, or ignore the notice when the URI is intentional data such as an `ov` argument or an HTTP payload.Each DSH session maps to `dsh-<session-id>` in OpenViking. Workspace-derived actor peers are resolved per session and sent on every session-specific request: the peer is the git identity of the session's workspace — the normalized `origin` URL (`[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`), else the repository root path, that fallback keeping the older rule where every non-letter-or-digit character becomes `-`. Outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space `viking://user/<you>/memories`. One repository therefore keeps one peer across subdirectories, worktrees, clones and machines, while a fork's different origin keeps it separate. DSH does not read workspace `.openviking/config.json` files, so a `peer.id` written there has no effect; pin a peer with `OPENVIKING_PEER_ID` instead. Memories written under the older path-derived peer stay reachable: the default `recallPeerScope: all` sweeps every peer under the user.diff --git a/examples/dsh-memory-plugin/capture.mjs b/examples/dsh-memory-plugin/capture.mjsindex abe0e90d1..445ccbde6 100644--- a/examples/dsh-memory-plugin/capture.mjs+++ b/examples/dsh-memory-plugin/capture.mjs@@ -1,3 +1,4 @@+import { createUserMessage } from "@deepseek-ai/dsh-llm";import {extractPartsFromPayload,extractTextFromPayload,@@ -6,6 +7,19 @@ import {export const OPENVIKING_PLUGIN_SOURCE = "openviking-memory";+export function pluginMessage(content, source) {+ // dsh's own constructor: identity, normalization, and any future Message+ // invariants come from the pinned peer instead of a hand-built object.+ return createUserMessage({+ content: [{ type: "text", text: content }],+ source: {+ kind: "plugin",+ plugin: OPENVIKING_PLUGIN_SOURCE,+ ...source,+ },+ });+}+export function captureEvent(event, config, toolNames = new Map()) {if (!event || typeof event !== "object") return null;if (event.type === "tool/call") {diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjsindex 528fd2d5d..0661354dc 100644--- a/examples/dsh-memory-plugin/config.mjs+++ b/examples/dsh-memory-plugin/config.mjs@@ -1,7 +1,7 @@import { buildPluginConfig } from "./shared/plugin-config.mjs";import { loadCredentialFiles } from "./shared/credentials.mjs";-export const PLUGIN_VERSION = "0.4.1";+export const PLUGIN_VERSION = "0.4.2";/*** Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tooldiff --git a/examples/dsh-memory-plugin/index.mjs b/examples/dsh-memory-plugin/index.mjsindex f6a738efd..b8f001a0a 100644--- a/examples/dsh-memory-plugin/index.mjs+++ b/examples/dsh-memory-plugin/index.mjs@@ -4,7 +4,7 @@ import { injectStartupProfile } from "./lifecycle.mjs";import { mountOpenVikingMcp } from "./mcp.mjs";import { OpenVikingRuntime } from "./runtime.mjs";import { mountOpenVikingSkills } from "./skills.mjs";-import { guardVikingUri } from "./uri-guard.mjs";+import { guardVikingUri, noticeVikingUri } from "./uri-guard.mjs";export const name = "openviking-memory";export const inject = ["agents", "sessions", "tools"];@@ -71,6 +71,7 @@ export function apply(ctx, input = {}) {});ctx.on("tools/pre-execute", guardVikingUri);+ ctx.on("tools/post-execute", noticeVikingUri);// Mounted last, and deliberately not awaited: the bridge's apply blocks on// its first tools/list, so a server that accepts the connection but neverdiff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.jsonindex f49682e2b..1b7159249 100644--- a/examples/dsh-memory-plugin/package-lock.json+++ b/examples/dsh-memory-plugin/package-lock.json@@ -1,12 +1,12 @@{"name": "@openviking/dsh-memory-plugin",- "version": "0.4.1",+ "version": "0.4.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@openviking/dsh-memory-plugin",- "version": "0.4.1",+ "version": "0.4.2","license": "Apache-2.0","devDependencies": {"@deepseek-ai/dsh-llm": "0.1.0-rc.6",diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.jsonindex 196aba006..6ed5b32f9 100644--- a/examples/dsh-memory-plugin/package.json+++ b/examples/dsh-memory-plugin/package.json@@ -1,6 +1,6 @@{"name": "@openviking/dsh-memory-plugin",- "version": "0.4.1",+ "version": "0.4.2","description": "OpenViking memory and context bundle for DeepSeek Harness","type": "module","main": "index.mjs",diff --git a/examples/dsh-memory-plugin/runtime.mjs b/examples/dsh-memory-plugin/runtime.mjsindex ff8c99491..e1c7207d1 100644--- a/examples/dsh-memory-plugin/runtime.mjs+++ b/examples/dsh-memory-plugin/runtime.mjs@@ -1,4 +1,3 @@-import { createUserMessage } from "@deepseek-ai/dsh-llm";import { isCaptureEnabled } from "./shared/capture-utils.mjs";import { buildProfileBlock } from "./shared/profile-inject.mjs";import { buildRecallBlock, isRecallEnabled } from "./shared/recall-core.mjs";@@ -14,6 +13,7 @@ import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";import {captureEvent,OPENVIKING_PLUGIN_SOURCE,+ pluginMessage,promptText,} from "./capture.mjs";@@ -122,7 +122,7 @@ export class OpenVikingRuntime {return null;}state.profileDelivered = true;- return pluginMessage(state.profileBlock, "instructions");+ return pluginMessage(state.profileBlock, { form: "instructions" });}async recallMessage(agent, messages) {@@ -141,7 +141,7 @@ export class OpenVikingRuntime {log: (stage, data) => this.log(stage, data),},);- return block ? pluginMessage(block, "recall") : null;+ return block ? pluginMessage(block, { form: "recall" }) : null;}capture(session, event) {@@ -404,19 +404,6 @@ export class OpenVikingRuntime {}}-function pluginMessage(content, form) {- // dsh's own constructor: identity, normalization, and any future Message- // invariants come from the pinned peer instead of a hand-built object.- return createUserMessage({- content: [{ type: "text", text: content }],- source: {- kind: "plugin",- plugin: OPENVIKING_PLUGIN_SOURCE,- form,- },- });-}-function hasStartupProfile(agent) {const session = agent.session;const ownEvents = typeof session?.ownEvents === "function"diff --git a/examples/dsh-memory-plugin/uri-guard.mjs b/examples/dsh-memory-plugin/uri-guard.mjsindex 701dc88c4..4f29124e7 100644--- a/examples/dsh-memory-plugin/uri-guard.mjs+++ b/examples/dsh-memory-plugin/uri-guard.mjs@@ -1,5 +1,7 @@+import { boundContextSummary } from "@deepseek-ai/dsh-llm";+import { pluginMessage } from "./capture.mjs";import { MCP_SERVER_NAME } from "./config.mjs";-import { evaluateUriGuard } from "./shared/uri-guard.mjs";+import { evaluateUriGuard, evaluateUriNotice } from "./shared/uri-guard.mjs";/** Model-facing name of a bridged OpenViking MCP tool. */const mcp = rawName => `mcp__${MCP_SERVER_NAME}__${rawName}`;@@ -42,6 +44,22 @@ export async function guardVikingUri(exec, next) {return { kind: "deny", reason: decision.reason };}+// Delegates first so a later listener's block or content replacement survives;+// the notice only rides along as one more context.+export async function noticeVikingUri(exec, _result, next) {+ const notice = evaluateUriNotice(exec.name, exec.arguments, { hints: GUARDED_TOOLS });+ if (!notice) return next();+ const decision = await next();+ const context = pluginMessage(notice.reason, {+ form: "notice",+ summary: boundContextSummary(`OpenViking URI guard: shell command contains ${notice.uri}`),+ });+ return {+ ...decision,+ additionalContexts: [...(decision.additionalContexts ?? []), context],+ };+}+function escapeText(value) {return String(value || "").replaceAll('"', '\\"');}diff --git a/examples/dsh-memory-plugin/uri-guard.test.mjs b/examples/dsh-memory-plugin/uri-guard.test.mjsindex 75271d96d..d93c9aa63 100644--- a/examples/dsh-memory-plugin/uri-guard.test.mjs+++ b/examples/dsh-memory-plugin/uri-guard.test.mjs@@ -1,15 +1,14 @@import assert from "node:assert/strict";import test from "node:test";-import { guardVikingUri } from "./uri-guard.mjs";+import { guardVikingUri, noticeVikingUri } from "./uri-guard.mjs";-test("uri guard blocks every DSH filesystem and shell tool that accepts paths", async () => {+test("uri guard blocks every DSH filesystem tool that accepts paths", async () => {const cases = [["read", { file_path: "viking://user/default/memories/profile.md" }],["write", { file_path: "viking://user/default/memories/profile.md" }],["edit", { file_path: "viking://user/default/memories/profile.md" }],["glob", { path: "viking://user/default/memories" }],["grep", { path: "viking://user/default/memories", pattern: "profile" }],- ["bash", { command: "cat viking://user/default/memories/profile.md" }],["str_replace_editor", {command: "view",path: "viking://user/default/memories/profile.md",@@ -98,8 +97,6 @@ test("uri guard still denies a viking URI used as a location", async () => {// A path key the list does not know about is still swept, so the fallback// keeps its reason to exist.["glob", { targets: { primary: "viking://user/default/memories" } }],- // bash carries its path inside `command`, which is not content.- ["bash", { command: "cat viking://user/default/memories/p.md" }],];for (const [name, args] of cases) {@@ -107,3 +104,86 @@ test("uri guard still denies a viking URI used as a location", async () => {assert.equal(decision.kind, "deny", name);}});++test("uri guard lets grep search for viking URI text in a local tree", async () => {+ const exec = { name: "grep", arguments: { pattern: "viking://user/default", path: "/tmp" } };+ const next = async () => ({ kind: "allow", marker: true });+ assert.deepEqual(await guardVikingUri(exec, next), { kind: "allow", marker: true });+ const accepted = { kind: "accept" };+ assert.equal(await noticeVikingUri(exec, okResult(), async () => accepted), accepted);+});++test("shell commands carrying a viking URI run and get a notice", async () => {+ const exec = {+ name: "bash",+ arguments: { command: "ov read viking://user/default/memories/profile.md" },+ };+ let delegated = false;+ await guardVikingUri(exec, async () => {+ delegated = true;+ return { kind: "allow" };+ });+ assert.equal(delegated, true);++ const decision = await noticeVikingUri(exec, okResult(), async () => ({ kind: "accept" }));+ assert.equal(decision.kind, "accept");+ assert.equal(decision.additionalContexts.length, 1);+ const [context] = decision.additionalContexts;+ assert.equal(context.role, "user");+ assert.equal(context.source.kind, "plugin");+ assert.equal(context.source.plugin, "openviking-memory");+ assert.equal(context.source.form, "notice");+ assert.match(context.source.summary, /viking:\/\/user\/default\/memories\/profile\.md/);+ assert.match(context.content[0].text, /ignore this notice/);+ assert.match(context.content[0].text, /mcp__openviking__read/);+});++test("the notice summary stays within dsh's context summary bound", async () => {+ const uri = `viking://resources/${"deep/".repeat(60)}file.md`;+ const decision = await noticeVikingUri(+ { name: "bash", arguments: { command: `cat ${uri}` } },+ okResult(),+ async () => ({ kind: "accept" }),+ );+ const { summary } = decision.additionalContexts[0].source;+ assert.ok(summary.length > 0);+ assert.ok(summary.length <= 120, `summary is ${summary.length} chars`);+});++test("the notice keeps a downstream decision and its contexts", async () => {+ const exec = { name: "bash", arguments: { command: "cat viking://user/default/memories/p.md" } };+ const earlier = { id: "earlier-context" };+ const feedback = [{ type: "text", text: "blocked downstream" }];+ const decision = await noticeVikingUri(exec, okResult(), async () => ({+ kind: "block",+ feedback,+ additionalContexts: [earlier],+ }));+ assert.equal(decision.kind, "block");+ assert.equal(decision.feedback, feedback);+ assert.equal(decision.additionalContexts.length, 2);+ assert.equal(decision.additionalContexts[0], earlier);+ assert.equal(decision.additionalContexts[1].source.form, "notice");+});++test("the notice leaves file tools, plain shell commands, and denied reads alone", async () => {+ const cases = [+ [{ name: "read", arguments: { file_path: "viking://user/default/memories/p.md" } }, {+ isError: true,+ error: { message: "viking:// URIs are OpenViking virtual paths" },+ content: [{ type: "text", text: "Error: viking:// URIs are OpenViking virtual paths" }],+ }],+ [{ name: "write", arguments: { file_path: "/tmp/a.md", content: "viking://user/default/" } }, okResult()],+ [{ name: "bash", arguments: { command: "ls /tmp" } }, okResult()],+ [{ name: "mcp__openviking__read", arguments: { uris: "viking://user/default/" } }, okResult()],+ ];++ for (const [exec, result] of cases) {+ const downstream = { kind: "accept" };+ assert.equal(await noticeVikingUri(exec, result, async () => downstream), downstream, exec.name);+ }+});++function okResult() {+ return { isError: false, value: "", content: [{ type: "text", text: "" }] };+}diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjsindex 70e7ec71f..77a7a1400 100644--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs@@ -265,9 +265,17 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", (const traeHooks = join(home, ".trae", "hooks.json");const traeCnHooks = join(home, ".trae-cn", "hooks.json");const zcodeConfig = join(home, ".zcode", "cli", "config.json");+ const thirdPartyShellHook = { command: "third-party shell audit" };writeJson(cursorHooks, { version: 1, hooks: {stop: [{ command: "third-party stop" }],postToolUse: [{ command: "node /tmp/openviking/cursor-hook.mjs postToolUse # openviking-memory" }],+ beforeShellExecution: [+ thirdPartyShellHook,+ {+ command: "OPENVIKING_INTEGRATION_ID='openviking-memory' OPENVIKING_INTEGRATION_VERSION='0.3.0' OPENVIKING_HOOK_SOURCE='cursor' 'node' '/tmp/openviking/agent-integrations/cursor/scripts/uri-guard.mjs' cursor # openviking-memory",+ timeout: 5,+ },+ ],} });writeJson(traeHooks, { version: 1, hooks: { Stop: [{ hooks: [{ type: "command", command: "third-party trae" }] },@@ -300,7 +308,7 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", (assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes("OPENVIKING_INTEGRATION_ID='openviking-memory'")));assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes("OPENVIKING_HOOK_SOURCE='cursor'")));assert.equal(cursor.hooks.beforeReadFile.filter((entry) => entry.command.includes("uri-guard.mjs")).length, 1);- assert.equal(cursor.hooks.beforeShellExecution.filter((entry) => entry.command.includes("uri-guard.mjs")).length, 1);+ assert.deepEqual(cursor.hooks.beforeShellExecution, [thirdPartyShellHook]);assert.equal(Boolean(cursor.hooks.postToolUse), false);for (const [file, label] of [[traeHooks, "trae"], [traeCnHooks, "trae-cn"]]) {@@ -355,7 +363,7 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", ([join(home, ".openviking", "agent-integrations", "cursor", "scripts", "ov-memory-doctor.mjs"), "cursor", "--offline", "--no-color"],{ env: { ...process.env, HOME: home }, encoding: "utf8" },);- assert.match(doctor.stdout, /version 0\.3\.0, client cursor/);+ assert.match(doctor.stdout, /version 0\.3\.1, client cursor/);// A hooks.json entry that names a script the install did not put on disk// fails only when the host first runs it, so the rendered commands are// checked against the tree they were rendered for.@@ -425,9 +433,8 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", (// Every event the installer wrote has to come back empty, the URI guard's// included: a surviving entry runs a script the uninstall just deleted.const cursorEventsAfter = JSON.parse(readFileSync(cursorHooks, "utf8")).hooks;- for (const event of ["beforeReadFile", "beforeShellExecution"]) {- assert.deepEqual(cursorEventsAfter[event] || [], [], event);- }+ assert.deepEqual(cursorEventsAfter.beforeReadFile || [], [], "beforeReadFile");+ assert.deepEqual(cursorEventsAfter.beforeShellExecution, [thirdPartyShellHook]);for (const [file, label] of [[traeHooks, "trae"], [traeCnHooks, "trae-cn"]]) {assert.deepEqual(JSON.parse(readFileSync(file, "utf8")).hooks.PreToolUse || [], [], label);}diff --git a/examples/memory-plugin-shared/lib/install/host-json-config.mjs b/examples/memory-plugin-shared/lib/install/host-json-config.mjsindex b75180b62..1e0eb5abe 100644--- a/examples/memory-plugin-shared/lib/install/host-json-config.mjs+++ b/examples/memory-plugin-shared/lib/install/host-json-config.mjs@@ -79,6 +79,12 @@ const OPENVIKING_HOOK_SCRIPTS = ["claude-code-memory-plugin/scripts/session-start.mjs",];+// Events an earlier release installed and the templates no longer name. An+// install rewrites only the template's events, so these are pruned separately.+const RETIRED_HOOK_EVENTS = {+ cursor: ["postToolUse", "beforeShellExecution"],+};+/** Whether a host's hook entry is one this installer owns. */export function ownsHook(value) {const text = JSON.stringify(value || {});@@ -155,12 +161,11 @@ export function writeHostJsonConfigs({ kind, hooksPath, mcpPath, root, clientId,...renderHookValue(entries),];}- if (kind === "cursor") {- if (Array.isArray(hooksConfig.hooks.postToolUse)) {- const remaining = hooksConfig.hooks.postToolUse.filter((item) => !ownsHook(item));- if (remaining.length) hooksConfig.hooks.postToolUse = remaining;- else delete hooksConfig.hooks.postToolUse;- }+ for (const event of RETIRED_HOOK_EVENTS[kind] || []) {+ if (!Array.isArray(hooksConfig.hooks[event])) continue;+ const remaining = hooksConfig.hooks[event].filter((item) => !ownsHook(item));+ if (remaining.length) hooksConfig.hooks[event] = remaining;+ else delete hooksConfig.hooks[event];}atomicWrite(hooksPath, hooksConfig);diff --git a/examples/memory-plugin-shared/lib/uri-guard.mjs b/examples/memory-plugin-shared/lib/uri-guard.mjsindex 2912ae77d..36fdb3a91 100644--- a/examples/memory-plugin-shared/lib/uri-guard.mjs+++ b/examples/memory-plugin-shared/lib/uri-guard.mjs@@ -10,7 +10,6 @@ const DEFAULT_URI_KEYS = ["uri","target_uri","targetUri",- "pattern",];export function normalizeToolName(value) {@@ -80,6 +79,17 @@ export function buildGuardMessage(uri, hint = {}) {return lines.join("\n");}+export function buildGuardNotice(uri, hint = {}) {+ const lines = [+ `[OpenViking memory plugin] URI guard: this shell command contains the viking:// URI ${uri}.`,+ "viking:// URIs are OpenViking virtual paths, not local files, so cat, ls, grep and other file commands cannot open them.",+ `If you meant to read or search OpenViking content, use ${hint.tool || "the OpenViking MCP tools"} instead.`,+ ];+ if (hint.example) lines.push(`Example: ${hint.example}`);+ lines.push("If the URI is intentional data (an ov CLI argument, an HTTP payload, a search pattern), ignore this notice.");+ return lines.join("\n");+}+/** The hints a host gets when it names no table of its own. */export const DEFAULT_TOOL_HINTS = {read: {@@ -98,6 +108,14 @@ export const DEFAULT_TOOL_HINTS = {`grep(uri="${uri}", pattern="${String(input.pattern ?? "").replaceAll('"', '\\"')}")`),},+ edit: {+ tool: "OpenViking MCP edit",+ example: (uri) => `edit(uri="${uri}", old_string="...", new_string="...")`,+ },+ write: {+ tool: "OpenViking MCP write",+ example: (uri) => `write(uri="${uri}", content="...")`,+ },bash: {tool: "OpenViking MCP read or search",example: (uri) => `read(uris="${uri}")`,@@ -112,30 +130,54 @@ export const DEFAULT_TOOL_HINTS = {},};-/**- * The guard decision for one tool call, or null when the call may proceed.- *- * `hints` carries the host's replacement tool names and example calls; `guarded`- * narrows which tool names the host guards at all, because the set is not the- * same everywhere — claude-code and opencode leave the shell alone (their- * matchers never see it), pi guards it.- */-export function evaluateUriGuard(toolName, input = {}, { hints = DEFAULT_TOOL_HINTS, guarded } = {}) {+// Tools whose argument is a command line rather than a location. A viking:// URI+// in one is data (an `ov` argument, an HTTP payload, a grep pattern) as often as+// a path the model hoped to open, so the command runs and the model gets a notice.+const SHELL_TOOL_NAMES = new Set(["bash", "shell", "runcommand"]);++// `pattern` is where glob looks but what grep looks for: a grep for the text+// "viking://" in a local tree is not a path. The generic sweep still reaches+// glob's pattern.+const TEXT_ARGS_BY_TOOL = { grep: ["pattern"] };++function resolveGuardedUri(toolName, input, { hints = DEFAULT_TOOL_HINTS } = {}) {const name = normalizeToolName(toolName);- if (guarded && !guarded.has(name)) return null;const hint = hints[name];if (!hint) return null;- const uri = findVikingUri(input);+ const textArgs = TEXT_ARGS_BY_TOOL[name];+ const uri = findVikingUri(input, DEFAULT_URI_KEYS, textArgs ? [...DEFAULT_CONTENT_KEYS, ...textArgs] : DEFAULT_CONTENT_KEYS);if (!uri) return null;return {uri,- reason: buildGuardMessage(uri, {+ shell: SHELL_TOOL_NAMES.has(name),+ hint: {tool: hint.tool,example: typeof hint.example === "function" ? hint.example(uri, input) : hint.example,- }),+ },};}+/**+ * The deny decision for one tool call, or null when the call may proceed.+ *+ * A file tool whose path is a viking:// URI cannot succeed, and a write would+ * leave a junk local file, so it is denied. A shell tool is never denied here;+ * `evaluateUriNotice` covers it. `hints` carries the host's replacement tool+ * names and example calls, and a tool without a hint is not guarded.+ */+export function evaluateUriGuard(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match || match.shell) return null;+ return { uri: match.uri, reason: buildGuardMessage(match.uri, match.hint) };+}++/** The notice for a shell command that carries a viking:// URI, or null. The command still runs. */+export function evaluateUriNotice(toolName, input = {}, opts = {}) {+ const match = resolveGuardedUri(toolName, input, opts);+ if (!match?.shell) return null;+ return { uri: match.uri, reason: buildGuardNotice(match.uri, match.hint) };+}+/** The PreToolUse deny envelope claude-code, trae and zcode all read. */export function denyHookSpecificOutput(reason) {return {@@ -147,11 +189,31 @@ export function denyHookSpecificOutput(reason) {};}-/** Cursor's deny envelope; its shell hook also wants the reason for the agent. */-export function denyCursorPermission(reason, { agentMessage = false } = {}) {- const output = { permission: "deny", user_message: reason };- if (agentMessage) output.agent_message = reason;- return output;+/** The PreToolUse notice envelope: no permissionDecision, so the host's own permission flow still runs. */+export function noticeHookSpecificOutput(reason) {+ return { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: reason } };+}++/** A hook event's tool name and input, under any of the spellings the hosts use. */+export function readToolEvent(event = {}) {+ return {+ toolName: event.tool_name ?? event.toolName ?? event.name ?? event.tool,+ toolInput: event.tool_input ?? event.toolInput ?? event.input ?? {},+ };+}++/** The whole PreToolUse guard: a deny envelope, a notice envelope, or {}. */+export function preToolUseOutput(event = {}, opts = {}) {+ const { toolName, toolInput } = readToolEvent(event);+ const denied = evaluateUriGuard(toolName, toolInput, opts);+ if (denied) return denyHookSpecificOutput(denied.reason);+ const notice = evaluateUriNotice(toolName, toolInput, opts);+ return notice ? noticeHookSpecificOutput(notice.reason) : {};+}++/** Cursor's beforeReadFile deny envelope. */+export function denyCursorPermission(reason) {+ return { permission: "deny", user_message: reason };}function readHookInput() {diff --git a/examples/memory-plugin-shared/plugin-config.test.mjs b/examples/memory-plugin-shared/plugin-config.test.mjsindex 956c43b2f..864c13a47 100644--- a/examples/memory-plugin-shared/plugin-config.test.mjs+++ b/examples/memory-plugin-shared/plugin-config.test.mjs@@ -47,7 +47,7 @@ const LOADERS = {pi: {harness: "pi",load: (cwd) => loadPi(cwd),- options: { version: "0.3.0", deriveEffectivePeer: true },+ options: { manifestUrl: new URL("../pi-coding-agent-extension/package.json", import.meta.url), deriveEffectivePeer: true },owns: ["peerId"],},cursor: { harness: "cursor", load: (cwd) => loadAgentHookConfig("cursor", cwd), options: { logFile: "cursor-hooks.log" }, owns: [] },diff --git a/examples/memory-plugin-shared/uri-guard.test.mjs b/examples/memory-plugin-shared/uri-guard.test.mjsindex 449ae3c5c..60a4c22a4 100644--- a/examples/memory-plugin-shared/uri-guard.test.mjs+++ b/examples/memory-plugin-shared/uri-guard.test.mjs@@ -2,12 +2,17 @@ import test from "node:test"import assert from "node:assert/strict"import {buildGuardMessage,+ buildGuardNotice,denyCursorPermission,denyHookSpecificOutput,evaluateUriGuard,+ evaluateUriNotice,findVikingUri,findVikingUriInValue,+ noticeHookSpecificOutput,normalizeToolName,+ preToolUseOutput,+ readToolEvent,} from "./lib/uri-guard.mjs"test("findVikingUri detects common path and URI argument keys", () => {@@ -47,17 +52,51 @@ test("evaluateUriGuard denies a guarded tool and passes everything else", () =>assert.equal(evaluateUriGuard("Read", { file_path: "/tmp/a.md" }), null)assert.equal(evaluateUriGuard("Task", { file_path: "viking://resources/a.md" }), null)+ assert.equal(evaluateUriGuard("Write", { file_path: "viking://resources/a.md", content: "x" })?.uri, "viking://resources/a.md")+ assert.equal(evaluateUriGuard("Write", { file_path: "/tmp/a.md", content: "see viking://resources/a.md" }), null)})-// The guarded set is per host: claude-code and opencode never see the shell in-// their matchers, pi does. Each of them pins its own half in its own tests.-test("evaluateUriGuard only guards the tools the host names", () => {- const call = ["bash", { command: "cat viking://resources/a.md" }]- assert.equal(evaluateUriGuard(...call, { guarded: new Set(["read", "glob", "grep"]) }), null)+test("a shell command that carries a viking:// URI gets a notice, never a deny", () => {+ for (const [tool, input] of [+ ["Bash", { command: "ov read viking://resources/a.md" }],+ ["RunCommand", { command: "cat viking://resources/a.md" }],+ ["shell", { command: ["curl", "-d", "{\"uri\":\"viking://resources/a.md\"}", "http://127.0.0.1:1933"] }],+ ]) {+ assert.equal(evaluateUriGuard(tool, input), null, tool)+ const notice = evaluateUriNotice(tool, input)+ assert.equal(notice?.uri, "viking://resources/a.md", tool)+ assert.match(notice?.reason ?? "", /ignore this notice/, tool)+ }+ assert.equal(evaluateUriNotice("Bash", { command: "cat /tmp/a.md" }), null)+})++test("a file tool on a viking:// path is denied, never noticed", () => {+ const input = { file_path: "viking://resources/a.md" }+ assert.equal(evaluateUriGuard("Read", input)?.uri, "viking://resources/a.md")+ assert.equal(evaluateUriNotice("Read", input), null)+ assert.equal(evaluateUriNotice("Task", { command: "viking://resources/a.md" }), null)+})++test("grep's pattern is search text while glob's pattern is a location", () => {+ assert.equal(evaluateUriGuard("Grep", { pattern: "viking://", path: "/repo" }), null)assert.equal(- evaluateUriGuard(...call, { guarded: new Set(["read", "bash"]) })?.uri,- "viking://resources/a.md",+ evaluateUriGuard("Grep", { pattern: "viking://", path: "viking://resources/project/" })?.uri,+ "viking://resources/project/",)+ assert.equal(evaluateUriGuard("Glob", { pattern: "viking://resources/**" })?.uri, "viking://resources/**")+})++test("buildGuardNotice names the plugin, the URI, the replacement and the way out", () => {+ const notice = buildGuardNotice("viking://resources/a.md", {+ tool: "openviking_read",+ example: 'openviking_read(uris=["viking://resources/a.md"])',+ })+ assert.match(notice, /OpenViking memory plugin/)+ assert.match(notice, /viking:\/\/resources\/a\.md/)+ assert.match(notice, /use openviking_read instead/)+ assert.match(notice, /Example: openviking_read/)+ assert.match(notice, /ignore this notice/)+ assert.doesNotMatch(buildGuardNotice("viking://resources/a.md"), /Example:/)})test("evaluateUriGuard takes the host's own replacement tools and examples", () => {@@ -79,13 +118,40 @@ test("deny envelopes carry only the keys their host recognizes", () => {},})assert.deepEqual(denyCursorPermission("because"), { permission: "deny", user_message: "because" })- assert.deepEqual(denyCursorPermission("because", { agentMessage: true }), {- permission: "deny",- user_message: "because",- agent_message: "because",+})++test("the notice envelope leaves the permission decision to the host", () => {+ assert.deepEqual(noticeHookSpecificOutput("because"), {+ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: "because" },})})+test("preToolUseOutput denies file paths, notices shell commands, and passes the rest", () => {+ const denied = preToolUseOutput({ tool_name: "Read", tool_input: { file_path: "viking://resources/a.md" } })+ assert.equal(denied.hookSpecificOutput?.permissionDecision, "deny")++ const noticed = preToolUseOutput({ tool_name: "Bash", tool_input: { command: "ov read viking://resources/a.md" } })+ assert.equal(noticed.hookSpecificOutput?.permissionDecision, undefined)+ assert.match(noticed.hookSpecificOutput?.additionalContext ?? "", /ignore this notice/)++ assert.deepEqual(preToolUseOutput({ tool_name: "Bash", tool_input: { command: "ls" } }), {})+ assert.deepEqual(preToolUseOutput({ tool_name: "Task", tool_input: { prompt: "viking://resources/a.md" } }), {})+ assert.deepEqual(preToolUseOutput(), {})+})++test("readToolEvent accepts each host's spelling", () => {+ const input = { file_path: "/tmp/a.md" }+ for (const event of [+ { tool_name: "Read", tool_input: input },+ { toolName: "Read", toolInput: input },+ { name: "Read", input },+ { tool: "Read", input },+ ]) {+ assert.deepEqual(readToolEvent(event), { toolName: "Read", toolInput: input })+ }+ assert.deepEqual(readToolEvent({}), { toolName: undefined, toolInput: {} })+})+test("normalizeToolName trims and lowercases", () => {assert.equal(normalizeToolName(" Read "), "read")})diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex b24139820..475b36eb4 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -209,6 +209,7 @@ curl http://localhost:1933/health- 探索目录结构用 `openviking_list`- 删除前必须先获得用户明确确认,再调用 `openviking_forget`- 如果 agent 误用 OpenCode 本地 `read`、`glob`、`grep` 工具访问 `viking://` URI,插件会阻止这次本地文件系统调用,并提示改用 MCP 工具。+- `bash` 命令里带 `viking://` URI 时照常执行,插件会在输出末尾附一段提示,建议改用 MCP 工具;URI 本来就是命令参数时,agent 可以忽略这段提示。## `openviking_add_resource` 本地文件diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex 844ab2123..b9c2a8680 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -206,6 +206,7 @@ Usage guidance:- Use `openviking_list` to explore directory structure.- Before deleting anything, obtain explicit user confirmation first; then call `openviking_forget`.- If an agent tries to use OpenCode's local `read`, `glob`, or `grep` tools on a `viking://` URI, the plugin blocks that call and points it to the MCP tools.+- A `bash` command that contains a `viking://` URI still runs; the plugin appends a notice pointing to the MCP tools to its output, which the agent can ignore when the URI is intentional.## Local Files with `openviking_add_resource`diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex d20c88f14..d096836de 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -18,7 +18,7 @@ The plugin uses OpenCode hooks for lifecycle behavior and registers OpenViking's- Captures user and assistant text messages into OpenViking.- Commits sessions at lifecycle boundaries for memory extraction.- Automatically recalls relevant memories and injects them as hidden synthetic context for the current user message.-- Blocks accidental local filesystem reads of `viking://` URIs and points the agent back to `openviking_read`, `openviking_glob`, or `openviking_search`.+- 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.## Files@@ -192,7 +192,10 @@ It does not add or overwrite OpenCode's `mcp.openviking` entry.OpenCode's local `read`, `glob`, and `grep` tools cannot read `viking://` URIs.When the agent accidentally tries that, the plugin blocks the filesystem tool-call and points it to the OpenViking MCP tools.+call and points it to the OpenViking MCP tools. A `bash` command that contains a+`viking://` URI is not blocked, because the URI is often data (an `ov` argument,+an HTTP payload); the command runs and the plugin appends a notice naming the+MCP tools to its output.## MCP Toolsdiff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjsindex ade8d93e0..a02a3edbc 100644--- a/examples/opencode-plugin/index.mjs+++ b/examples/opencode-plugin/index.mjs@@ -5,7 +5,7 @@ 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 } from "./lib/viking-uri-guard.mjs"+import { createVikingUriGuard, createVikingUriNotice } from "./lib/viking-uri-guard.mjs"import { injectOpenVikingMcpConfig } from "./lib/mcp-config.mjs"import { loadConfig, resolveDataDir } from "./lib/config.mjs"import { isRecallEnabled } from "./lib/shared/recall-core.mjs"@@ -28,6 +28,7 @@ export async function OpenVikingPlugin({ client, directory }) {const recall = createMemoryRecall({ config, sessionManager })const sessionInject = createSessionInject({ config, sessionManager })const vikingUriGuard = createVikingUriGuard()+ const vikingUriNotice = createVikingUriNotice()await sessionManager.init()const toast = makeToast(client)@@ -57,6 +58,7 @@ export async function OpenVikingPlugin({ client, directory }) {},"tool.execute.before": vikingUriGuard,+ "tool.execute.after": vikingUriNotice,"experimental.chat.system.transform": (_input, output) => {const prompt = repoContext.getRepoSystemPrompt()diff --git a/examples/opencode-plugin/lib/viking-uri-guard.mjs b/examples/opencode-plugin/lib/viking-uri-guard.mjsindex 5f3bc297e..0ccafc29f 100644--- a/examples/opencode-plugin/lib/viking-uri-guard.mjs+++ b/examples/opencode-plugin/lib/viking-uri-guard.mjs@@ -1,5 +1,5 @@import { log } from "./utils.mjs"-import { evaluateUriGuard, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs"+import { evaluateUriGuard, evaluateUriNotice, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs"const FILESYSTEM_TOOL_HINTS = {read: {@@ -14,6 +14,10 @@ const FILESYSTEM_TOOL_HINTS = {tool: "openviking_search",example: (uri, args = {}) => `openviking_search(query="${String(args.pattern ?? "").replaceAll('"', '\\"')}", target_uri="${uri}")`,},+ bash: {+ tool: "openviking_read or openviking_search",+ example: (uri) => `openviking_read(uris=["${uri}"])`,+ },}export function createVikingUriGuard() {@@ -31,4 +35,18 @@ export function createVikingUriGuard() {}}+export function createVikingUriNotice() {+ return async (input, output) => {+ const toolName = normalizeToolName(input?.tool ?? input?.name)+ const notice = evaluateUriNotice(toolName, input?.args ?? {}, { hints: FILESYSTEM_TOOL_HINTS })+ if (!notice || !output) return++ log("INFO", "viking-uri-guard", "Attached viking URI notice to shell tool output", {+ tool: toolName,+ uri: notice.uri,+ })+ output.output = output.output ? `${output.output}\n\n${notice.reason}` : notice.reason+ }+}+export { findVikingUri, normalizeToolName }diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.jsonindex 5d3e04c46..fa5184658 100644--- a/examples/opencode-plugin/package.json+++ b/examples/opencode-plugin/package.json@@ -1,6 +1,6 @@{"name": "@openviking/opencode-plugin",- "version": "0.3.0",+ "version": "0.3.1","author": "@openviking","description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory","type": "module",diff --git a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs b/examples/opencode-plugin/tests/viking-uri-guard.test.mjsindex 41e4cff83..12771b8b7 100644--- a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs+++ b/examples/opencode-plugin/tests/viking-uri-guard.test.mjs@@ -1,6 +1,6 @@import test from "node:test"import assert from "node:assert/strict"-import { createVikingUriGuard, findVikingUri } from "../lib/viking-uri-guard.mjs"+import { createVikingUriGuard, createVikingUriNotice, findVikingUri } from "../lib/viking-uri-guard.mjs"test("viking uri guard blocks filesystem tools on virtual URIs", async () => {const guard = createVikingUriGuard()@@ -23,4 +23,44 @@ test("viking uri guard blocks filesystem tools on virtual URIs", async () => {await assert.doesNotReject(() => guard({ tool: "read" }, { args: { filePath: "/tmp/file.md" } }))await assert.doesNotReject(() => guard({ tool: "bash" }, { args: { command: "cat viking://resources/project/file.md" } }))+ await assert.doesNotReject(() => guard({ tool: "grep" }, { args: { pattern: "viking://", path: "/repo" } }))+})++test("viking uri notice appends to shell output and keeps the original text", async () => {+ const notice = createVikingUriNotice()+ const output = { title: "cat", output: "cat: viking://resources/project/file.md: No such file or directory", metadata: {} }++ await notice({ tool: "bash", args: { command: "cat viking://resources/project/file.md" } }, output)++ assert.ok(output.output.startsWith("cat: viking://resources/project/file.md: No such file or directory\n\n"))+ assert.match(output.output, /viking:\/\/resources\/project\/file\.md/)+ assert.match(output.output, /openviking_read\(uris=\["viking:\/\/resources\/project\/file\.md"\]\)/)+ assert.match(output.output, /ignore this notice/)+ assert.equal(output.title, "cat")+})++test("viking uri notice fills empty shell output", async () => {+ const notice = createVikingUriNotice()+ const output = { title: "ov", output: "", metadata: {} }++ await notice({ tool: "bash", args: { command: "ov read viking://resources/project/file.md" } }, output)++ assert.match(output.output, /^\[OpenViking memory plugin\] URI guard/)+ assert.match(output.output, /ignore this notice/)+})++test("viking uri notice leaves file tools and plain shell commands alone", async () => {+ const notice = createVikingUriNotice()+ const cases = [+ { tool: "read", args: { filePath: "viking://resources/project/file.md" } },+ { tool: "grep", args: { pattern: "viking://", path: "/repo" } },+ { tool: "bash", args: { command: "ls /tmp" } },+ { tool: "openviking_read", args: { uris: ["viking://resources/project/file.md"] } },+ ]++ for (const input of cases) {+ const output = { title: "t", output: "original", metadata: {} }+ await notice(input, output)+ assert.equal(output.output, "original", input.tool)+ }})diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.mdindex 1020021af..b080e592e 100644--- a/examples/pi-coding-agent-extension/DESIGN.md+++ b/examples/pi-coding-agent-extension/DESIGN.md@@ -173,6 +173,7 @@ The entry point. It loads the config, returns immediately when disabled, constru| `before_agent_start` | Await startup, queue the prompt for recall, compose system-prompt additions || `context` | Run the pending recall, apply the takeover transform, inject recall || `tool_call` | Redirect host file tools that were handed a `viking://` URI |+| `tool_result` | Append a notice to a `bash` result whose command carried a `viking://` URI || `turn_end` | Sync the branch, feed the token estimate to takeover, update the status line || `session_before_compact` | Takeover compaction, or a commit plus a fresh overview || `session_shutdown` | Persist takeover state, or a final commit |@@ -184,7 +185,7 @@ The entry point. It loads the config, returns immediately when disabled, constru**System prompt.** `before_agent_start` appends the profile block built by the shared `profile-inject.mjs` and capped at `profileTokenBudget`; outside takeover, the archive overview cached at resume or after a pre-compact commit; and one line naming the seven tools. Under takeover the overview reaches the model through the `context` hook instead, so it is not appended twice.-**Tool guard.** `guardVikingUriToolCall` (`lib/uri-guard-adapter.mjs`) watches for a `viking://` URI handed to a host tool that cannot read one — `read`, `grep`, `find`, `ls`, `bash` — and blocks the call with the equivalent `viking_*` invocation spelled out. Without it the model burns turns on a file path that does not exist on disk.+**Tool guard.** `guardVikingUriToolCall` (`lib/uri-guard-adapter.mjs`) watches for a `viking://` URI handed as a path to a host file tool that cannot read one — `read`, `grep`, `find`, `ls` — and blocks the call with the equivalent `viking_*` invocation spelled out. Without it the model burns turns on a file path that does not exist on disk. A grep `pattern` is search text, not a path, so grepping a local tree for `viking://` is not blocked. `bash` is not blocked either: a URI in a command is as often data (an `ov` argument, an HTTP payload, a search pattern) as a path the model hoped to open. The command runs, and on `tool_result` `noticeVikingUriToolResult` appends a text block to its output that names `viking_read` / `viking_search` and tells the model to ignore the notice when the URI was intentional.**Surface.** The status line reports connection, entries added on the last turn, and either takeover coverage against its threshold or the plain commit threshold. `/viking` prints that same state; `/viking commit` forces a flush and commit, which under takeover also advances the boundary.diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex c5d6c8fdb..8540ca1db 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -19,7 +19,7 @@ import { RecallLedger } from "./lib/recall-ledger.mjs";import { SyncManager } from "./sync.js";import { buildProfileBlock } from "./shared/profile-inject.mjs";import { isBypassed } from "./shared/session-model.mjs";-import { guardVikingUriToolCall } from "./lib/uri-guard-adapter.mjs";+import { guardVikingUriToolCall, noticeVikingUriToolResult } from "./lib/uri-guard-adapter.mjs";import { registerTools } from "./tools.js";import { createTakeoverManager } from "./takeover.js";@@ -225,6 +225,13 @@ export default async function (pi: ExtensionAPI) {return decision;});+ // --- tool_result ---+ pi.on("tool_result", async (event, _ctx) => {+ const notice = noticeVikingUriToolResult(event);+ if (!notice) return;+ return notice;+ });+// --- turn_end ---pi.on("turn_end", async (event, ctx) => {if (!connected || bypassed || !isCaptureEnabled(config)) return;diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mts b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mtsindex f19a7b460..7bead4fdd 100644--- a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mts+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mts@@ -1 +1,2 @@export function guardVikingUriToolCall(event: any): { block: true; reason: string } | null;+export function noticeVikingUriToolResult(event: any): { content: any[] } | null;diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjsindex bf08df2ed..91436b994 100644--- a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs@@ -1,4 +1,4 @@-import { evaluateUriGuard } from "../shared/uri-guard.mjs";+import { evaluateUriGuard, evaluateUriNotice } from "../shared/uri-guard.mjs";const VIKING_URI_TOOL_HINTS = {read: {@@ -23,9 +23,25 @@ const VIKING_URI_TOOL_HINTS = {},};+function readPiToolEvent(event) {+ return {+ toolName: event?.toolName ?? event?.tool_name ?? event?.name,+ input: event?.input ?? event?.args ?? event?.params ?? {},+ };+}+export function guardVikingUriToolCall(event) {- const toolName = event?.toolName ?? event?.tool_name ?? event?.name;- const input = event?.input ?? event?.args ?? event?.params ?? {};+ const { toolName, input } = readPiToolEvent(event);const decision = evaluateUriGuard(toolName, input, { hints: VIKING_URI_TOOL_HINTS });return decision ? { block: true, reason: decision.reason } : null;}++// A tool_result handler's content replaces the result's content, so the+// original blocks are carried over and the notice is appended after them.+export function noticeVikingUriToolResult(event) {+ const { toolName, input } = readPiToolEvent(event);+ const notice = evaluateUriNotice(toolName, input, { hints: VIKING_URI_TOOL_HINTS });+ if (!notice) return null;+ const content = Array.isArray(event?.content) ? event.content : [];+ return { content: [...content, { type: "text", text: notice.reason }] };+}diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.jsonindex 9a5801222..1cb40086f 100644--- a/examples/pi-coding-agent-extension/package.json+++ b/examples/pi-coding-agent-extension/package.json@@ -1,6 +1,6 @@{"name": "openviking-pi-extension",- "version": "0.3.0",+ "version": "0.3.1","description": "OpenViking memory and context extension for the pi coding agent","private": true,"type": "module"diff --git a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjsindex 0338dcc5f..e45c82573 100644--- a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs+++ b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs@@ -1,6 +1,6 @@import test from "node:test"import assert from "node:assert/strict"-import { guardVikingUriToolCall } from "../lib/uri-guard-adapter.mjs"+import { guardVikingUriToolCall, noticeVikingUriToolResult } from "../lib/uri-guard-adapter.mjs"test("pi URI guard blocks builtin file tools on viking URIs", () => {const decision = guardVikingUriToolCall({@@ -14,18 +14,46 @@ test("pi URI guard blocks builtin file tools on viking URIs", () => {assert.match(decision?.reason ?? "", /Use viking_read instead/)})-test("pi URI guard blocks bash commands containing viking URI", () => {+test("pi URI guard lets bash commands containing viking URI run", () => {const decision = guardVikingUriToolCall({type: "tool_call",toolName: "bash",input: { command: "cat viking://resources/project/file.md" },})- assert.equal(decision?.block, true)- assert.match(decision?.reason ?? "", /Use viking_read or viking_search instead/)+ assert.equal(decision, null)})test("pi URI guard allows normal local paths and OpenViking native tools", () => {assert.equal(guardVikingUriToolCall({ toolName: "read", input: { path: "/tmp/file.md" } }), null)assert.equal(guardVikingUriToolCall({ toolName: "viking_read", input: { uri: "viking://resources/file.md" } }), null)+ assert.equal(guardVikingUriToolCall({ toolName: "grep", input: { pattern: "viking://", path: "/repo" } }), null)+})++test("pi URI guard appends a notice to bash results whose command carried a viking URI", () => {+ const original = [{ type: "text", text: "cat: viking://resources/project/file.md: No such file or directory" }]+ const result = noticeVikingUriToolResult({+ type: "tool_result",+ toolName: "bash",+ toolCallId: "call-1",+ input: { command: "cat viking://resources/project/file.md" },+ content: original,+ isError: true,+ })++ assert.equal(result?.content.length, 2)+ assert.deepEqual(result.content[0], original[0])+ assert.equal(result.content[1].type, "text")+ assert.match(result.content[1].text, /viking:\/\/resources\/project\/file\.md/)+ assert.match(result.content[1].text, /use viking_read or viking_search instead/)+ assert.match(result.content[1].text, /viking_read\(uri="viking:\/\/resources\/project\/file\.md", level="overview"\)/)+ assert.match(result.content[1].text, /ignore this notice\.$/)+ assert.equal(original.length, 1)+})++test("pi URI guard leaves other tool results alone", () => {+ const content = [{ type: "text", text: "ok" }]+ assert.equal(noticeVikingUriToolResult({ toolName: "bash", input: { command: "ls /tmp" }, content }), null)+ assert.equal(noticeVikingUriToolResult({ toolName: "read", input: { path: "viking://resources/file.md" }, content }), null)+ assert.equal(noticeVikingUriToolResult({ toolName: "viking_read", input: { uri: "viking://resources/file.md" }, content }), null)})