Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(pi): mirror the server's MCP tool surface (#5272)
t0sakibbf2e37f88b8
diff --git a/.github/scripts/check-marketplace-archive.mjs b/.github/scripts/check-marketplace-archive.mjsindex 76b2c8426..f18d49601 100644--- a/.github/scripts/check-marketplace-archive.mjs+++ b/.github/scripts/check-marketplace-archive.mjs@@ -178,6 +178,10 @@ export async function requiredArchiveFiles(stagedNames) {continue;}for (const file of await pluginRequirements(root)) addIfStaged(file);+ if (name === "pi-coding-agent-extension") {+ addIfStaged(join(root, "package.json"));+ addIfStaged(join(root, "package-lock.json"));+ }}// The plugins that vendor a copy of the shared runtime ship what the sync putdiff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex e8d43f4e8..5a6e6463a 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -36,6 +36,7 @@ jobs:node-version: '24'- run: npm ci --prefix examples/dsh-memory-plugin+ - run: npm ci --prefix examples/pi-coding-agent-extension --ignore-scripts# The plugins published as packages keep no shared copies in git; they are# built on the way out, and the tests import them like the package would.diff --git a/docs/en/about/02-changelog.md b/docs/en/about/02-changelog.mdindex 6205dc0e8..964296cfd 100644--- a/docs/en/about/02-changelog.md+++ b/docs/en/about/02-changelog.md@@ -19,6 +19,7 @@ This changelog is automatically generated from [GitHub Releases](https://github.extraction correctly. Existing boolean-like values remain temporarily compatible andemit deprecation warnings; use JSON booleans for new configurations.- **Workspace peer derivation**: The coding-agent plugins now derive a workspace's peer from git instead of from the working directory. The new default, `peer.source: "git"`, uses the repository's normalized `origin` URL (`github.com-volcengine-openviking`), falling back to the repository root path, so every clone, worktree, and subdirectory of one repository shares a single peer while a fork keeps its own. A directory that is not a git repository now gets no peer at all, and what is remembered there goes to the user-level space instead of a fresh namespace per folder. Give such a directory a memory of its own by creating `.openviking/config.json` with `{"version": 1, "peer": {"id": "my-project"}}`. No migration is required: the previous cwd-derived id can always be recomputed locally, and the default `peer_scope: "all"` recall already sweeps every peer, so memories written under it keep coming back (with `peer_scope: "actor"`, the Claude Code, Codex, OpenCode, and DSH plugins query that id as well). Set `peer.source: "cwd"` — or `OPENVIKING_PEER_SOURCE=cwd` — to keep the old behavior.+- **Pi extension tool surface (breaking change)**: The pi extension 0.4.0 replaces its seven hand-written `viking_*` REST tools with the server's own MCP tools through the official MCP client, so the tool list now follows whatever the server's `tools/list` returns instead of a catalogue shipped with the extension. Every tool is `openviking_` plus the server's name (`viking_search` → `openviking_search`), with no alias period, and pi matches `--tools` and `--exclude-tools` entries by exact name, so an allowlist that still says `viking_search` loses that tool silently and has to be renamed by hand. The tools now behave as they do on every other MCP harness: `remember` commits a session of its own rather than appending to the live pi session, `read` returns full text only (the `level="abstract"` and `level="overview"` tiers are gone — `openviking_search(mode="context", detail="overview")` is the substitute), `forget` deletes the URI it is handed, and `add_resource` answers a local path with a one-time upload URL to POST the file to. A root api key is refused on `/mcp` with 403 and now leaves the session with no tools at all, where before the tools registered and every call came back empty; create a user or admin key for it. The shared `mcpEnabled: false` switch now takes effect for pi as well, and tools turned off that way are not reported as a failure. Recall, session capture, and context takeover keep working in all of these cases, and no other harness is affected. The extension README's [Upgrading from 0.3.x](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md#upgrading-from-03x) has the full list.- **External peer identity migration**: Mixed-script log-ingestion identities now uselossless `ext-<base64>` ids. The `ext-` namespace is reserved, so ASCII identities thatwould otherwise enter it are encoded as well. Older lossy peer directories are not readdiff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.mdindex 60e5b264a..fd104f798 100644--- a/docs/en/agent-integrations/01-overview.md+++ b/docs/en/agent-integrations/01-overview.md@@ -14,7 +14,7 @@ OpenViking can act as the long-term memory and context backend for many agent ru| **DeepSeek Harness (`dsh`)** | [DeepSeek Harness Memory Bundle](./17-dsh.md) — in-process Cordis plugin with pre-step recall, event capture, and the OpenViking MCP tools || **Hermes Agent** | [Hermes Agent](./05-hermes.md) — built-in OpenViking memory provider, no plugin install needed || **OpenCode** | [OpenCode Plugin](./10-opencode.md) — MCP tools plus lifecycle hooks for repo context, auto-recall, and capture |-| **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, and threshold commit |+| **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, threshold commit, and the server's MCP tools registered as native pi tools || **LangChain / LangGraph** | [LangChain and LangGraph](./07-langchain-langgraph.md) — retriever, tools, context backend, store, and middleware || **Multiple local coding agents / a desktop UI** | [OpenViking Helper](./14-openviking-helper.md) — visual agent setup, session inspection, and memory management || **Any Agent Plugins 1.0 client** | [Agent Plugins 1.0 Package](./15-agent-plugins.md) — one portable package: `openviking-memory` skill plus the OpenViking MCP tools |diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex c2c5fa731..4e621a364 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -1,6 +1,6 @@# pi Coding Agent Extension-Give [pi](https://github.com/earendil-works/pi) cross-session long-term memory and context takeover. The extension is built on pi's native extension API (pi does not support MCP): recall happens automatically before every prompt, conversation turns are captured after every turn, and OpenViking can replace committed local history with an archive overview in pi's `context` hook.+Give [pi](https://github.com/earendil-works/pi) cross-session long-term memory and context takeover. Recall, capture, and takeover run on pi's native extension API: recall happens automatically before every prompt, conversation turns are captured after every turn, and OpenViking can replace committed local history with an archive overview in pi's `context` hook. The extension uses the official MCP client and registers the server's MCP tools as native pi tools.Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)@@ -10,14 +10,18 @@ Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenV- **Every prompt** runs semantic recall against the OpenViking server and injects matching memories as hidden context.- **Every turn** captures user and assistant messages (including structured tool calls) into an OpenViking session; takeover mode commits once synced-token pressure crosses the threshold and then keeps only the recent live tail in model context.- **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`/`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`.+- **Model-callable tools** are whatever the server's MCP `tools/list` returns, each registered under an `openviking_` prefix — the same 15 tools the other memory plugins expose: `openviking_find`, `openviking_search`, `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`, `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`. The extension keeps no tool catalogue of its own, so a server that adds or drops a tool changes pi's tool surface at the next session, with no extension release. The shared `mcpEnabled: false` turns the tool surface off and leaves recall, capture, and takeover running.+- The tool handshake never fails startup. When it fails — server down, credentials rejected, no `/mcp` endpoint — the session keeps recall, capture, and takeover and simply has no OpenViking tools; the bridge retries on a later turn, so a server started after pi is picked up without a restart.+- A footer status segment (`OV ✓ …`) shows connection and capture state, plus `tools ✗` when the handshake failed; the `/viking` command prints status, including the registered tool count or the last handshake error, and `/viking commit` forces a commit.+- Accidental `read`/`grep`/`find`/`ls`/`write`/`edit` calls whose path is a `viking://` URI are blocked with a hint pointing to the matching `openviking_*` tool. A `bash` command that carries a `viking://` URI still runs, and its result ends with a notice suggesting `openviking_read` / `openviking_search`.++Extension 0.4.0 replaced the seven hand-written `viking_*` REST tools with this mirrored surface, with no alias period: a `--tools` / `--exclude-tools` allowlist that pins the old names must be updated by hand, or those tools silently disappear. Some semantics moved with the names — `openviking_remember` writes through its own session that the server commits immediately, `openviking_read` returns full text only (the old `level="abstract"` / `"overview"` tiers are gone; use `openviking_search(mode="context", detail="overview")` or `openviking_tree(include_abstract=true)` for the condensed views), and `openviking_forget` deletes the URI you give it instead of the strongest match of a query. Context takeover still injects the archive overview itself over REST, so that path is unchanged.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).## Prerequisites+- Node.js 22.19.0+ and npm- pi coding agent (`npm i -g @earendil-works/pi-coding-agent`)- An OpenViking HTTP server — verify with `curl http://localhost:1933/health`@@ -35,7 +39,7 @@ In regions where GitHub is hard to reach, run the same installer from the Volcenbash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```-The installer copies the extension into `~/.pi/agent/extensions/openviking` and configures `~/.openviking/ovcli.conf`. That directory is one of pi's auto-discovery roots, so pi loads the extension on the next start — no `pi install` needed. (Running `pi install` on the same path would load it twice — once via auto-discovery, once via the `packages` entry — producing a duplicate `/viking` command.)+The installer installs the locked npm dependencies before replacing the extension in `~/.pi/agent/extensions/openviking` and configures `~/.openviking/ovcli.conf`. That directory is one of pi's auto-discovery roots, so pi loads the extension on the next start — no `pi install` needed. (Running `pi install` on the same path would load it twice — once via auto-discovery, once via the `packages` entry — producing a duplicate `/viking` command.)Manual copy from a repo checkout also works:@@ -45,6 +49,7 @@ cd OpenVikingnode examples/memory-plugin-shared/sync.mjsmkdir -p ~/.pi/agent/extensions/openvikingcp -R examples/pi-coding-agent-extension/. ~/.pi/agent/extensions/openviking/+npm ci --prefix ~/.pi/agent/extensions/openviking --omit=dev --ignore-scripts```The extension imports its shared modules from a `shared/` directory that is not in git; `sync.mjs` generates it, so run it before copying. After a `git pull`, run `sync.mjs` again before copying the update.@@ -99,7 +104,7 @@ Takeover is fail-open: if pending writes cannot flush, commit fails, the archive## Verify-Start `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/viking` prints the current session mapping. Ask pi about something you mentioned in an earlier session to confirm recall.+Start `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/viking` prints the current session mapping and how many `openviking_*` tools registered. Ask pi about something you mentioned in an earlier session to confirm recall.## Troubleshooting@@ -111,6 +116,7 @@ Start `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/v| Load fails with a missing `shared/*.mjs` module (for example `shared/capture-utils.mjs`) | The copy was made without running `sync.mjs` first. Run `node examples/memory-plugin-shared/sync.mjs` from the repository root and copy again, or re-run the installer || Import errors mentioning `@mariozechner/*` | Stale copy from before pi's move to `@earendil-works/*` — re-run the installer || 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |+| `tools ✗` in the footer, or no `openviking_*` tools in the session | Run `/viking` for the full handshake error. A root API key is rejected on `/mcp` with 403 — create a user or admin key. `mcpEnabled: false` disables the tools deliberately and is not reported as a failure || Recall is empty | Confirm the server has indexed memories and the prompt is longer than `minQueryLength` |For the full tool, configuration, and design reference, see the [extension README](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension).diff --git a/docs/en/agent-integrations/15-agent-plugins.md b/docs/en/agent-integrations/15-agent-plugins.mdindex acff50c46..144b29080 100644--- a/docs/en/agent-integrations/15-agent-plugins.md+++ b/docs/en/agent-integrations/15-agent-plugins.md@@ -92,7 +92,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar| OpenCode | [OpenCode Plugin](./10-opencode.md) || Cursor | [Cursor Memory Integration](./12-cursor.md) || TRAE / TRAE CN | [TRAE Memory Integration](./13-trae.md) |-| pi | [pi Coding Agent Extension](./11-pi.md) |+| pi | [pi Coding Agent Extension](./11-pi.md) — uses the official MCP client and registers the server's tools natively || OpenClaw | [OpenClaw Plugin](./03-openclaw.md) — separate install flow || ZCode | [Community Integrations](./08-community-plugins.md) |diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex 84b4df4da..f9999f605 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -21,7 +21,7 @@## 1.1 Active tool surface (agentic calls)-- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode) share an identical active tool surface comprising 16 tools.** The server centrally defines these tools. The plugin reads `~/.openviking/ovcli.conf` via its proxy and establishes a connection to the server-defined MCP tools.+- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode, dsh, pi) share an identical active tool surface comprising 16 tools.** The server centrally defines these tools. The plugins read `~/.openviking/ovcli.conf` and connect to the server-defined MCP tools. pi uses the official MCP client inside its extension and registers the discovered tools as native pi tools.- `trae-cli` means TraeCode CLI 2.0 (2.0 only). It is installed via a `codex` plugin alias and maintains format compatibility with `codex`. Therefore, it is consolidated into the `codex` row in the matrices below.@@ -34,16 +34,15 @@| zcode | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² || opencode | MCP passthrough (host adds an `openviking_` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² || dsh | MCP passthrough (`@deepseek-ai/dsh-mcp-client` → the shared stdio proxy; host adds an `mcp__openviking__` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |-| pi | native registration (7 × `viking_*`) | 7 (registration runs preflight checks⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource` (URL only) | ❌ | no type distinction; delete by query needs score>0.8³ |-| openclaw | native registration (15 × `memory_*`/`ov_*` and friends) | 15 (14 on by default⁵) | ✅ `memory_recall` | ✅ `ov_search` (both scopes by default) | ✅ `ov_search` | ✅ `memory_store` | off by default⁵ | ✅ `add_skill` | memory-only allowlist + auto-delete only for a single candidate with score≥0.85 |+| pi | MCP mirror (official client; extension adds an `openviking_` prefix) | 16, i.e. whatever `tools/list` returns (registration has preconditions³) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |+| openclaw | native registration (15 × `memory_*`/`ov_*` and friends) | 15 (14 on by default⁴) | ✅ `memory_recall` | ✅ `ov_search` (both scopes by default) | ✅ `ov_search` | ✅ `memory_store` | off by default⁴ | ✅ `add_skill` | memory-only allowlist + auto-delete only for a single candidate with score≥0.85 || hermes | native registration (6 × `viking_*`) | 6 (all on once the provider is active) | ✅ | ✅ | ✅ | ✅ `viking_remember` (writes the file directly, no extraction) | ✅ multi-protocol ingest (HTTP/Git/SSH/local file/directory zip) | ❌ | memory-only + `.md` leaf check || ov CLI | CLI commands | ~40 command groups | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` executes directly (TUI deletion asks for confirmation and blocks root/scope deletes) |¹ MCP `write` rejects the user's own `skills/` subtree; under `viking://agent/skills` it writes a plain file that skips skill installation (no frontmatter abstract, no privacy extraction), so use `add_skill` there too. Skills are created, installed, and replaced through the MCP `add_skill` tool (inline SKILL.md text, a Git URL, or a signed upload of a local directory or zip), which shares one install implementation with REST `POST /api/v1/skills`.² MCP `forget` does not differentiate between memory, resource, and skill types. However, the storage layer protects namespace roots: deletion requests for bare `viking://`, `viking://user`, and `viking://agent` are rejected. See [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).-³ For `viking_forget` on pi: the `recursive` flag is strictly set to false (directories are never deleted), and deleting by query requires a match score > 0.8.-⁴ The `pi` harness registers its tools only if the session misses `bypassSessionPatterns`, `client.health()` passes, and `ensureSession` succeeds (`index.ts:66-108`). If the health check fails, no tools are registered for that session.-⁵ The `add_resource` tool in openclaw requires a double opt-in before activation.+³ The `pi` harness registers a tool only if the session misses `bypassSessionPatterns`, `client.health()` passes, `ensureSession` succeeds, and the `/mcp` handshake returns a tool list (`index.ts:150-205`); the shared `mcpEnabled: false` skips the bridge entirely and is not counted as a failure. A failed handshake costs the session its OpenViking tools and nothing else — recall, session sync and takeover carry on — and `before_agent_start` retries it on a later turn (`index.ts:252-255`), so a server started after pi is picked up without a restart. See [§3.6](#_3-6-degradation-and-fault-tolerance).+⁴ The `add_resource` tool in openclaw requires a double opt-in before activation.**Skill addition/deletion boundaries**: Skills can be added via the MCP `add_skill` tool, the openclaw `add_skill` tool (enabled by default), the `ov add-skill` CLI command, or the REST API. Deletion operates across four tiers, detailed in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).@@ -124,7 +123,7 @@ Core modules at a glance (detailed further in the per-dimension sections):|---|---|---|| `recall-core.mjs` | Handles recall request construction, three-tier degradation, and local fallback ranking/injection | All JS-based harnesses || `agent-hook-runtime.mjs` | All-in-one "thin hook" runtime handling configuration resolution through the shared schema, session ID derivation, cross-process locking, fetching, and commits | cc / codex / cursor / trae / trae-cn / zcode |-| `mcp-proxy-core.mjs` | stdio ↔ streamable-HTTP MCP proxy core | All MCP-based integrations + agent-plugins |+| `mcp-proxy-core.mjs` | stdio ↔ streamable-HTTP MCP proxy core | MCP integrations and agent-plugins that communicate with a child process; pi uses the official client directly || `ov-http.mjs` | The one path from a hook to the OpenViking server: headers, AbortController, envelope | All JS-based + agent-plugins || `pending-queue.mjs` | On-disk offline queueing and replay at session start | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `batch-send.mjs` | Executes writes in batches of 100, handles per-message degradation on 404/405 errors, and queues the leading contiguous prefix | cc / codex / opencode + the agent-hook family |@@ -485,7 +484,7 @@ There are three primary guards on MCP `write` and REST `content/write` (`content**Tier 1: The universal server-side defense (shared by every delete entry point).** The first statement of `VikingFS.rm`, `_ensure_delete_access` (`_access.py:182-229`), enforces five checks: namespace accessibility; ongoing user deletions (returns `FailedPrecondition`); actor-peer hidden views (returns `PermissionDenied`); namespace root protection (bare `viking://`, along with the `viking://user` and `viking://agent` roots, are unconditionally refused); and restricting deletes in `viking://temp` to ROOT only. This tier defends exclusively at the namespace root level and does not differentiate between memory, resource, or skill types. Those type-level distinctions are enforced on the client side by the subsequent three tiers.-**Tier 2: No client-side additions (the MCP surface + dsh / pi / langchain / ov rm).** Here, the differences lie purely in the parameters. In Pi's `viking_forget`, `recursive` is hardcoded to false (preventing directory deletion), and semantic query deletions require a score > 0.8. LangChain's `viking_forget` exposes `recursive` as a model-controllable parameter, although the tool is not exposed by default. The CLI command `ov rm -r` explicitly enables recursion without a confirmation prompt, whereas the TUI's `d` key enforces a y/n confirmation and bans the deletion of root or scope directories.+**Tier 2: No client-side additions (the MCP surface — which dsh and pi now reach as well — plus langchain / ov rm).** Here, the differences lie purely in the parameters. MCP `forget` deletes the URI it is handed, with `recursive=False` by default and no score guard of any kind; dsh and pi both dropped the hand-written `viking_forget` that used to pin `recursive` to false and require a match score > 0.8 before deleting by query, so neither adds anything to this tier any more. LangChain's `viking_forget` exposes `recursive` as a model-controllable parameter, although the tool is not exposed by default. The CLI command `ov rm -r` explicitly enables recursion without a confirmation prompt, whereas the TUI's `d` key enforces a y/n confirmation and bans the deletion of root or scope directories.**Tier 3: The two memory-only delete surfaces.**@@ -506,7 +505,7 @@ There are three primary guards on MCP `write` and REST `content/write` (`content| cursor/trae×2/zcode | Fetch errors are swallowed as `status:0`, and catch returns an empty injection; silently skips if the lock isn't acquired within 5s | context-face 6h (no negative cache for unreachable servers; every turn waits the full 15s) | None | No || opencode | All paths catch exceptions → WARN; the `event`/`dispose` hooks lack try/catch blocks (non-retryable commit failures bubble up to the host) | context-face 6h only; `/health` is uncached (one round trip per turn) | No synchronous retry; the MCP proxy retries once each for 401/403 and 400/404 | Mostly no (except `event`/`dispose`) || dsh | The client swallows all exceptions; `ensureState` failures are not cached (when the server is unreachable, each pre-step makes two 5s health calls) | context-face 6h + an in-process user-space cache that never expires | None; pending queue replays 3 times across processes | Yes (pre-step runs profile+recall serially; session/flush blocks) |-| pi | On health failure, `start()` returns early; subsequent prompts silently retry the connection | context-face 6h | None; pending queue only | Partly (`session_shutdown` is awaited: ~0s with takeover, max 30s without; on a `turn_end` network error, each message waits 10s) |+| pi | On health failure, `start()` returns early and registers no tools; subsequent prompts silently retry the connection. A `/mcp` handshake that fails on its own (401/403, timeout, no `/mcp`) never fails startup: recall, sync and takeover carry on, the status line shows `tools ✗`, and `/viking` prints the full error | context-face 6h; the handshake has none, so a still-failing bridge is retried once per turn and can spend its 5s budget before recall is queued | Hooks: none, pending queue only. A failed MCP transport is discarded and the next invocation reconnects; the failed call is never replayed | Partly (`session_shutdown` is awaited: ~0s with takeover, max 30s without, plus closing the MCP client; on a `turn_end` network error, each message waits 10s) || openclaw | Client construction never fails; health checks swallow exceptions; recall is skipped if the 500ms precheck fails | No negative cache (one 500ms health precheck per turn) | None (a single fetch); Phase2 polling in commit/afterTurn | No (except when `memory_store` re-raises; `compact()` blocks for up to 5 minutes) || hermes | `_client=None` acts as the runtime negative cache (stops retrying in the current process, except for the local auto-start waiter) | No separate structure (`_client=None` handles this) | One retry with a trusted identity, one retry with a fresh sync client, multi-tier degradation; failed commits are not retried | No (a single background worker + per-provider try/except) || ov CLI | Mostly exits with 1; `ov status` in table mode always exits with 0; `ov health` exits with 0 even when unhealthy | None | Only one retry on a gateway 401 challenge | n/a (no host) |@@ -609,10 +608,10 @@ Each card serves as a quick-reference entry point. It records only the facts and## 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 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.3.+- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). The extension uses the official MCP client and republishes every descriptor from the server's `tools/list` as a pi tool named `openviking_<tool>`: 16 today ([§2.1](#_2-1-server-side-mcp-tool-surface)). Nothing in the extension enumerates tools, so a server that gains or drops one changes pi's surface at the next session with no plugin release. Recall, session sync, profile injection and takeover still go over REST. It features 9 events + a `/viking` command; `tool_call` blocks read/grep/find/ls/write/edit 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.4.0.- **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.+- **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`, `ensureSession` and a `/mcp` handshake ([§1.1](#_1-1-active-tool-surface-agentic-calls)); a root API key is refused on `/mcp` with a 403, so a credential chain ending at `ov.conf`'s `server.root_api_key` produces a session with no tools — before 0.4.0 the REST tools registered and quietly answered "No results found." instead. `openviking_remember` runs on the MCP surface, meaning its own one-shot session committed immediately rather than a write folded into pi's session ([§2.1](#_2-1-server-side-mcp-tool-surface)). `openviking_add_resource` ingests a remote URL directly; for a local path the server returns an upload instruction whose URL the model has to POST the bytes to with `bash`, as on every other MCP harness. `openviking_read` returns full text only: a directory URI comes back as `Cannot render …: URI points to a directory`, and the old `level="abstract"/"overview"` tiers have no MCP equivalent — use `openviking_search(mode="context", detail="overview")` or `openviking_tree(include_abstract=true)`, while takeover keeps injecting the archive overview itself over REST. A tool call is bounded by the shared `timeoutMs` (15000ms, `OPENVIKING_TIMEOUT_MS`), which a `write`/`edit` with `wait=true` or a synchronous `add_resource` ingest can outlast; a timeout or ESC fails the call locally only, so the request it already sent runs to completion and a write may have landed anyway. Upgrading from 0.3.x renames every tool with no alias period, so a `--tools` / `--exclude-tools` allowlist that pinned `viking_*` has to be rewritten or the tools silently disappear. 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. The shared `mcpEnabled: false` now takes effect here as well: no bridge, no tools, and `/viking` reports that as a setting rather than a fault.- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | takeover [§3.4.2](#_3-4-2-pi-takeover) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).## openclawdiff --git a/docs/en/agent-integrations/18-plugin-development.md b/docs/en/agent-integrations/18-plugin-development.mdindex bbb4d5b3b..906f8317b 100644--- a/docs/en/agent-integrations/18-plugin-development.md+++ b/docs/en/agent-integrations/18-plugin-development.md@@ -74,6 +74,7 @@ Mark each capability as verified, supported with a fallback, or unsupported, and| Hooks and MCP are installed through configuration files; the common dispatcher can express the lifecycle | Add an adapter and host configuration under `agent-hook-plugin/hosts/` | [agent-hook-plugin](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md) || A native plugin needs its own manifest, directory, and lifecycle entrypoints | A separate plugin directory whose entrypoints call the shared runtime | [Claude Code](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md), [Codex](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) || Host SDK callbacks require persistent state or dispose/idle callbacks | A host extension package using shared capabilities and explicit session scheduling | [OpenCode](https://github.com/volcengine/OpenViking/blob/main/examples/opencode-plugin/README.md), [DSH](https://github.com/volcengine/OpenViking/blob/main/examples/dsh-memory-plugin/README.md) |+| The host registers native tools but has no MCP support | Use the official MCP client and register the server's `tools/list` as native host tools under an `openviking_` prefix; do not hand-maintain a tool catalogue | [pi](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md) || MCP is available, but automatic injection or complete session records are not | An MCP-only integration with documented limits | [Agent Plugins](https://github.com/volcengine/OpenViking/blob/main/agent-plugins/README.md) |A new host name does not justify copying the Claude Code or Codex directory. Conversely, a host with a distinct session state machine should not be forced into the common dispatcher through accumulating `isFoo` or `specialStop` flags.diff --git a/docs/zh/about/02-changelog.md b/docs/zh/about/02-changelog.mdindex 04701fe8b..6356ee1a4 100644--- a/docs/zh/about/02-changelog.md+++ b/docs/zh/about/02-changelog.md@@ -16,6 +16,7 @@ OpenViking 的所有重要变更都将记录在此文件中。- **Session policy 兼容性**:字符串 `"false"` 现在会正确关闭对应的记忆抽取开关。现有 boolean-like 值暂时保持兼容并产生弃用警告;新配置应使用 JSON 布尔值。- **工作区 peer 派生规则**:coding agent 插件不再按工作目录派生工作区 peer,改为按 git 派生。新的默认值 `peer.source: "git"` 取仓库归一化后的 `origin` URL(`github.com-volcengine-openviking`),其次回退到仓库根路径,因此同一个仓库的每个 clone、worktree 和子目录共用同一个 peer,而 fork 仍是独立的 peer。不在 git 仓库中的目录现在完全不发送 peer,在那里记下的内容进入用户级空间,而不是为每个目录新建一个命名空间。要让这样的目录拥有独立记忆,在其中创建 `.openviking/config.json`,写入 `{"version": 1, "peer": {"id": "my-project"}}`。无需任何迁移:此前按工作目录派生的 id 随时可以在本地重新算出,而默认的 `peer_scope: "all"` 召回本来就会扫描所有 peer,因此写在旧 id 下的记忆照常召回(`peer_scope: "actor"` 时,Claude Code、Codex、OpenCode 和 DSH 插件会额外查询该 id)。设置 `peer.source: "cwd"`(或 `OPENVIKING_PEER_SOURCE=cwd`)即可保持旧行为。+- **pi 扩展的工具面(不兼容变更)**:pi 扩展 0.4.0 移除自己手写的 7 个 `viking_*` REST 工具,改用官方 MCP 客户端连接服务端,因此工具清单由服务端 `tools/list` 的返回决定,不再来自扩展自带的目录。每个工具的名字是 `openviking_` 加服务端的工具名(`viking_search` → `openviking_search`),不保留旧名别名期;pi 的 `--tools` 和 `--exclude-tools` 按名字精确匹配,白名单里仍写 `viking_search` 的话,对应工具会静默消失,需要手动改名。这些工具的行为与其他 MCP harness 一致:`remember` 另开一个会话并立即提交,不再追加到当前 pi 会话;`read` 只返回全文(`level="abstract"` 和 `level="overview"` 两档已移除,替代路径是 `openviking_search(mode="context", detail="overview")`);`forget` 直接删除传入的 URI;`add_resource` 对本地路径返回一次性上传 URL,由模型把文件 POST 上去。root api key 在 `/mcp` 上被拒绝(403),现在会导致整个会话一个工具都没有,而此前是工具照常注册、每次调用都返回空结果,这类部署需要改用 user 或 admin key。共享开关 `mcpEnabled: false` 现在对 pi 同样生效,以这种方式关掉工具不计作故障。以上各种情况下,recall、会话采集和上下文接管都照常工作,其他 harness 不受影响。完整的改名对照和升级说明见扩展 README 的 [Upgrading from 0.3.x](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md#upgrading-from-03x)。- **外部 peer identity 迁移**:日志导入中的混合文字标识改用无损的`ext-<base64>` id。`ext-` 命名空间为编码身份保留,因此原本会进入该命名空间的ASCII 身份也会被编码。系统不会自动读取旧的有损 peer 目录,因为多个身份可能彼此冲突,diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.mdindex e1591a0b7..7cea38c7b 100644--- a/docs/zh/agent-integrations/01-overview.md+++ b/docs/zh/agent-integrations/01-overview.md@@ -14,7 +14,7 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端| **DeepSeek Harness(`dsh`)** | [DeepSeek Harness 记忆插件](./17-dsh.md) — 进程内 Cordis 插件,pre-step 召回、事件捕获与 OpenViking MCP 工具 || **Hermes Agent** | [Hermes Agent](./05-hermes.md) — 内置 OpenViking 记忆提供方,无需安装插件 || **OpenCode** | [OpenCode 插件](./10-opencode.md) — MCP 工具 + 生命周期 hooks,覆盖仓库上下文、自动召回与捕获 |-| **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获与阈值 commit |+| **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获、阈值 commit,并把服务端的 MCP 工具注册为 pi 原生工具 || **LangChain / LangGraph** | [LangChain 和 LangGraph](./07-langchain-langgraph.md) — retriever、tools、context backend、store 和 middleware || **多个本地开发 Agent / 希望使用桌面界面** | [OpenViking Helper](./14-openviking-helper.md) — 可视化完成 Agent 接入、会话分析和记忆管理 || **任意支持 Agent Plugins 1.0 的客户端** | [Agent Plugins 1.0 插件包](./15-agent-plugins.md) — 一个可移植的包:`openviking-memory` 技能 + OpenViking MCP 工具 |diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex 38f68f292..e44539933 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -1,6 +1,6 @@# pi Coding Agent 扩展-为 [pi](https://github.com/earendil-works/pi) 提供跨会话长期记忆和 context takeover。扩展基于 pi 原生扩展 API 构建(pi 不支持 MCP):每个 prompt 前自动召回、每个 turn 后自动捕获,并可由 OpenViking 在 pi 的 `context` hook 中用归档 overview 替换已 commit 的本地历史。+为 [pi](https://github.com/earendil-works/pi) 提供跨会话长期记忆和 context takeover。召回、捕获和 takeover 基于 pi 原生扩展 API:每个 prompt 前自动召回、每个 turn 后自动捕获,并可由 OpenViking 在 pi 的 `context` hook 中用归档 overview 替换已 commit 的本地历史。扩展使用官方 MCP 客户端,把服务端的 MCP 工具注册成 pi 原生工具。源码:[examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)@@ -10,14 +10,18 @@- **每个 prompt** 向 OpenViking server 做语义召回,把命中的记忆作为隐藏上下文注入。- **每个 turn** 把用户与助手消息(含结构化工具调用)捕获进 OpenViking session;takeover 模式会在 synced token 压力超过阈值后 commit,并在模型上下文中只保留近期 live tail。- **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`/`grep`/`find`/`ls` 访问 `viking://` URI 路径时,调用会被拦截,并提示改用对应的 `viking_*` 工具;`bash` 命令带 `viking://` URI 时照常执行,结果末尾附一条提示,建议改用 `viking_read` / `viking_search`。+- **模型可调用工具**就是服务端 MCP `tools/list` 返回的工具,注册时统一加 `openviking_` 前缀——与其他记忆插件同一套 15 个工具:`openviking_find`、`openviking_search`、`openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`、`openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`。扩展自己不再维护工具清单,服务端增删工具后,下一次 pi 会话即生效,无需发布新版扩展。共享键 `mcpEnabled: false` 可关掉整个工具面,召回、捕获和 takeover 不受影响。+- 工具握手失败不会影响启动。服务端不可达、凭据被拒、没有 `/mcp` 端点时,召回、捕获和 takeover 照常工作,只是这次会话没有 OpenViking 工具;桥接会在后续 turn 重试,所以 pi 启动之后才拉起的服务端不必重启 pi 也能接上。+- 底部状态栏显示 `OV ✓ …` 连接与捕获状态,握手失败时还会追加 `tools ✗`;`/viking` 命令查看状态,包括已注册的工具数量或最近一次握手错误,`/viking commit` 强制 commit。+- 模型用本地 `read`/`grep`/`find`/`ls`/`write`/`edit` 访问 `viking://` URI 路径时,调用会被拦截,并提示改用对应的 `openviking_*` 工具;`bash` 命令带 `viking://` URI 时照常执行,结果末尾附一条提示,建议改用 `openviking_read` / `openviking_search`。++扩展 0.4.0 用这套镜像工具面替换了原先手写的 7 个 `viking_*` REST 工具,且不保留别名:`--tools` / `--exclude-tools` 白名单里写死旧名字的,必须手动改过来,否则这些工具会静默消失。部分语义也随之改变——`openviking_remember` 写入独立 session 并由服务端立即 commit,`openviking_read` 只返回全文(旧的 `level="abstract"` / `"overview"` 两档已移除,需要精简视图改用 `openviking_search(mode="context", detail="overview")` 或 `openviking_tree(include_abstract=true)`),`openviking_forget` 直接删除给定 URI,而不是删除某个 query 的最强匹配。Context takeover 的归档 overview 仍由扩展经 REST 注入,这条路径不变。工具调用和结果会作为独立的 `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) 读回。## 前置条件+- Node.js 22.19.0+ 和 npm- pi coding agent(`npm i -g @earendil-works/pi-coding-agent`)- OpenViking HTTP server——用 `curl http://localhost:1933/health` 确认可达@@ -35,7 +39,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/ebash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```-安装器会把扩展复制到 `~/.pi/agent/extensions/openviking`,并配置 `~/.openviking/ovcli.conf`。该目录是 pi 的自动发现根目录之一,复制到位后 pi 会在下次启动时自动加载,无需再执行 `pi install`。(对同一路径再跑 `pi install` 会让扩展被加载两遍——一次来自自动发现,一次来自 `packages` 条目——出现重复的 `/viking` 命令。)+安装器会先安装 lockfile 中锁定的 npm 依赖,再将扩展放到 `~/.pi/agent/extensions/openviking`,并配置 `~/.openviking/ovcli.conf`。该目录是 pi 的自动发现根目录之一,复制到位后 pi 会在下次启动时自动加载,无需再执行 `pi install`。(对同一路径再跑 `pi install` 会让扩展被加载两遍——一次来自自动发现,一次来自 `packages` 条目——出现重复的 `/viking` 命令。)也可以从仓库 checkout 手动复制:@@ -45,6 +49,7 @@ cd OpenVikingnode examples/memory-plugin-shared/sync.mjsmkdir -p ~/.pi/agent/extensions/openvikingcp -R examples/pi-coding-agent-extension/. ~/.pi/agent/extensions/openviking/+npm ci --prefix ~/.pi/agent/extensions/openviking --omit=dev --ignore-scripts```扩展从 `shared/` 目录 import 共享模块,这个目录不在 git 里,由 `sync.mjs` 生成,所以复制前必须先运行它。之后 `git pull` 更新时,也要先重新运行 `sync.mjs` 再复制。@@ -99,7 +104,7 @@ Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、arc## 验证-启动 `pi`。连接成功后底部状态栏出现 `OV ✓` 段,`/viking` 会打印当前 session 映射。问 pi 一个你在早前会话里提到过的事情,确认召回生效。+启动 `pi`。连接成功后底部状态栏出现 `OV ✓` 段,`/viking` 会打印当前 session 映射和已注册的 `openviking_*` 工具数量。问 pi 一个你在早前会话里提到过的事情,确认召回生效。## 故障排查@@ -111,6 +116,7 @@ Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、arc| 加载时报找不到 `shared/*.mjs`(例如 `shared/capture-utils.mjs`) | 手动复制前没有运行 `sync.mjs`。在仓库根目录运行 `node examples/memory-plugin-shared/sync.mjs` 后重新复制,或者重跑安装器 || 报错提到 `@mariozechner/*` | pi 迁移到 `@earendil-works/*` 之前的旧副本——重跑安装器 || OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |+| 状态栏显示 `tools ✗`,或会话里没有 `openviking_*` 工具 | 用 `/viking` 查看完整的握手错误。root API key 访问 `/mcp` 会被 403 拒绝——请改用 user 或 admin key。`mcpEnabled: false` 是主动关闭工具面,不算故障 || recall 为空 | 确认 server 中已有记忆,且 prompt 长度超过 `minQueryLength` |完整工具、配置与设计说明见 [扩展 README](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)。diff --git a/docs/zh/agent-integrations/15-agent-plugins.md b/docs/zh/agent-integrations/15-agent-plugins.mdindex 4a1586d97..630a7ef5c 100644--- a/docs/zh/agent-integrations/15-agent-plugins.md+++ b/docs/zh/agent-integrations/15-agent-plugins.md@@ -92,7 +92,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar| OpenCode | [OpenCode 插件](./10-opencode.md) || Cursor | [Cursor 记忆集成](./12-cursor.md) || TRAE / TRAE CN | [TRAE 记忆集成](./13-trae.md) |-| pi | [pi Coding Agent 扩展](./11-pi.md) |+| pi | [pi Coding Agent 扩展](./11-pi.md) — 使用官方 MCP 客户端,把服务端工具注册为原生工具 || OpenClaw | [OpenClaw 插件](./03-openclaw.md) — 独立安装流程 || ZCode | [社区集成](./08-community-plugins.md) |diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex 15f641a96..36a6cdec8 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -21,7 +21,7 @@## 1.1 主动工具面(Agentic 调用能力)-- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode)的主动工具面完全一致,共 16 个工具**:这些工具由服务端统一定义,插件通过代理获得 `~/.openviking/ovcli.conf` 配置后连接服务器定义的 MCP 工具。+- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode、dsh、pi)的主动工具面完全一致,共 16 个工具**:这些工具由服务端统一定义,各插件读取 `~/.openviking/ovcli.conf` 并连接服务端 MCP 工具;pi 在扩展中使用官方 MCP 客户端,再把发现的工具注册成 pi 原生工具。- trae-cli 指 TraeCode CLI 2.0(仅支持 2.0),经 codex 插件别名安装,插件与 codex 格式兼容,下文矩阵并入 codex 行。@@ -34,16 +34,15 @@| zcode | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² || opencode | MCP 透传(宿主加 `openviking_` 前缀) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² || dsh | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |-| pi | 原生注册(7 个 `viking_*`) | 7(注册需前置检查⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource`(仅 URL) | ❌ | 无类型区分;query 删除需 score>0.8³ |-| openclaw | 原生注册(15 个 `memory_*`/`ov_*` 等) | 15(默认开 14⁵) | ✅ `memory_recall` | ✅ `ov_search`(默认双 scope) | ✅ `ov_search` | ✅ `memory_store` | 默认关⁵ | ✅ `add_skill` | memory-only 白名单 + 单候选 score≥0.85 才自动删 |+| pi | MCP 镜像(官方客户端;扩展加 `openviking_` 前缀) | 16,即 `tools/list` 返回什么就是什么(注册有前置条件³) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |+| openclaw | 原生注册(15 个 `memory_*`/`ov_*` 等) | 15(默认开 14⁴) | ✅ `memory_recall` | ✅ `ov_search`(默认双 scope) | ✅ `ov_search` | ✅ `memory_store` | 默认关⁴ | ✅ `add_skill` | memory-only 白名单 + 单候选 score≥0.85 才自动删 || hermes | 原生注册(6 个 `viking_*`) | 6(provider 激活即全开) | ✅ | ✅ | ✅ | ✅ `viking_remember`(直写文件,不走抽取) | ✅ 多协议摄取(HTTP/Git/SSH/本地文件/目录 zip) | ❌ | memory-only + `.md` 叶子校验 || ov CLI | CLI 命令 | ~40 命令组 | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` 直接执行(TUI 删除有确认 + root/scope 禁删) |¹ MCP `write` 拒绝写用户自己的 `skills/` 子树;写 `viking://agent/skills` 时会生成一个绕过 skill 安装流程的普通文件(没有 frontmatter abstract,也不做 privacy 抽取),所以共享 skill 同样要走 `add_skill`。skill 的新建、安装和替换走 MCP `add_skill` 工具(内联 SKILL.md 文本、Git URL,或本地目录/zip 的签名上传),它和 REST `POST /api/v1/skills` 共用同一套安装实现。² MCP `forget` 不区分 memory/resource/skill 类型;存储层保留了命名空间根保护机制(裸 `viking://`、`viking://user`、`viking://agent` 根拒删),详见 [§3.5](#_3-5-写入与删除的类型边界)。-³ pi 的 `viking_forget`:其 `recursive` 参数固定为 false(不删除目录),按 query 删除要求匹配分 >0.8。-⁴ pi 工具注册前置:需未命中 `bypassSessionPatterns`、`client.health()` 通过、`ensureSession` 成功(`index.ts:66-108`);health 未通过时本轮不注册工具面。-⁵ openclaw 的 `add_resource` 需经过双重 opt-in 后方可开启。+³ pi 工具注册前置:需未命中 `bypassSessionPatterns`、`client.health()` 通过、`ensureSession` 成功,且 `/mcp` 握手取回工具清单(`index.ts:150-205`);共享键 `mcpEnabled: false` 则整个桥接都不发起,不算失败。握手失败只让本次会话没有 OpenViking 工具,召回、会话同步与 takeover 照常,`before_agent_start` 会在后续轮次重试(`index.ts:252-255`),因此 pi 启动之后才拉起的 server 不必重启 pi 就能接上。详见 [§3.6](#_3-6-降级与容错)。+⁴ openclaw 的 `add_resource` 需经过双重 opt-in 后方可开启。**skill 的增删边界**:新增入口包含 MCP `add_skill`、openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;删除边界分四档,详见 [§3.5](#_3-5-写入与删除的类型边界)。@@ -125,7 +124,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章|---|---|---|| `recall-core.mjs` | 召回请求构造 + 三级降级 + 本地兜底排序注入 | 全部 JS 系 harness || `agent-hook-runtime.mjs` | "瘦 hook"一体化运行时(配置经共享 schema 解析、session id 派生、跨进程锁、fetch、commit) | cc / codex / cursor / trae / trae-cn / zcode |-| `mcp-proxy-core.mjs` | stdio↔streamable-HTTP MCP 代理内核 | 全部 MCP 型 + agent-plugins |+| `mcp-proxy-core.mjs` | stdio↔streamable-HTTP MCP 代理内核 | 使用子进程通信的 MCP 集成与 agent-plugins;pi 直接使用官方客户端 || `ov-http.mjs` | hook 到 OpenViking 服务端的唯一出网路径:请求头、AbortController、信封解析 | 全部 JS 系 + agent-plugins || `pending-queue.mjs` | 磁盘离线队列 + 会话启动重放 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi || `batch-send.mjs` | 100 条/批写入 + 404/405 逐条降级 + 连续前缀入队 | cc / codex / opencode + agent-hook 系 |@@ -465,7 +464,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可**第一档:服务端通用防线(所有删除入口共享)**。`VikingFS.rm` 第一句 `_ensure_delete_access`(`_access.py:182-229`)实施 5 道检查:命名空间可访问性;用户删除进行中 → FailedPrecondition;actor-peer 隐藏视图 → PermissionDenied;命名空间根保护:裸 `viking://`、`viking://user` 根、`viking://agent` 根一律拒删;非 ROOT 删 `viking://temp` 拒。这一档按命名空间根设防,不区分 memory/resource/skill 类型——类型级差异由后三档在客户端实施。-**第二档:客户端零附加(MCP 面 + dsh/pi/langchain/ov rm)**。差异只在参数面:pi 的 `viking_forget` 里 `recursive` 固定 false(不删除目录),且 query 删除需 score>0.8;LangChain `viking_forget` 的 `recursive` 是模型可控参数(但默认不在工具面);`ov rm -r` 则显式开递归、无确认提示(TUI 的 `d` 键有 y/n 确认 + root/scope 目录禁删)。+**第二档:客户端零附加(MCP 面——dsh 与 pi 现在也走它——外加 langchain/ov rm)**。差异只在参数面:MCP `forget` 按给定 URI 删除,`recursive` 默认 false,没有任何分数门槛;dsh 与 pi 都已经把自己手写的 `viking_forget` 撤下工具面(旧实现把 `recursive` 固定为 false,按 query 删除还要求匹配分 >0.8),这一档因此不再有客户端附加。LangChain `viking_forget` 的 `recursive` 是模型可控参数(但默认不在工具面);`ov rm -r` 则显式开递归、无确认提示(TUI 的 `d` 键有 y/n 确认 + root/scope 目录禁删)。**第三档:memory-only 的两个删除面**。@@ -487,7 +486,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可| cursor/trae×2/zcode | fetch 吞成 status:0,catch 返回空注入;锁 5s 拿不到则静默跳过 | context-face 6h(服务端整体不可达时无负缓存,每轮等满 15s) | 无 | 否 || opencode | 各路径 catch→WARN;`event`/`dispose` hook 无 try/catch(不可重试的 commit 失败会冒泡宿主) | 仅 context-face 6h;`/health` 无缓存(每轮一次往返) | 无同步重试;MCP 代理 401/403、400/404 各一次 | 基本否(event/dispose 例外) || dsh | client 全吞异常;`ensureState` 失败不缓存(服务端不可达时每 pre-step 两次 health 各 5s) | context-face 6h + user-space 缓存进程内不过期 | 无;pending 跨进程重放 3 次 | 是(pre-step 串行 profile+recall;session/flush 阻塞) |-| pi | health 失败时 start() 提前返回,此后每 prompt 静默重试连接 | context-face 6h | 无;仅 pending queue | 部分(session_shutdown 被 await:takeover 近 0、非 takeover 最坏 30s;turn_end 网络异常时逐条各等 10s) |+| pi | health 失败时 start() 提前返回,本轮也不注册工具,此后每 prompt 静默重试连接;`/mcp` 握手单独失败(401/403、超时、server 无 `/mcp`)不影响启动:召回、同步、takeover 照常,状态栏显示 `tools ✗`,`/viking` 打印完整错误 | context-face 6h;握手没有负缓存,一直失败就每轮重试一次,最多占满 5s 握手预算才轮到排队召回 | hook 侧无,只有 pending queue;传输失败后丢弃当前 MCP 连接,下次调用重新连接;失败的工具调用不会自动重放 | 部分(session_shutdown 被 await:takeover 近 0、非 takeover 最坏 30s,外加关闭 MCP 客户端;turn_end 网络异常时逐条各等 10s) || openclaw | client 构造永不失败;health 吞异常;召回 500ms precheck 失败跳过 | 无负缓存(每轮一次 500ms health 预检) | 无(单次 fetch);commit/afterTurn 的 Phase2 轮询 | 否(`memory_store` 重抛例外;`compact()` 最长阻塞 5 分钟) || hermes | `_client=None` 即运行期负缓存(本进程不再重试,除本地自启 waiter 外) | 无独立结构(`_client=None` 承担) | trusted 补身份 1 次、sync 全新 client 1 次、多档降级;commit 失败不重试 | 否(后台单 worker + 逐 provider try/except) || ov CLI | 多数 exit 1;`ov status` 表格模式始终退 0;`ov health` 即使 unhealthy 也退 0 | 无 | 仅网关 401 挑战重试 1 次 | n/a(无宿主) |@@ -591,10 +590,10 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## pi(pi Coding Agent Extension)- **集成文档**:[pi Coding Agent 扩展](./11-pi.md)-- **形态**: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.3。+- **形态**:pi 原生扩展(目录装载,jiti 直译 TS)。扩展使用 `@modelcontextprotocol/client`,把服务端 `tools/list` 的每个描述符注册成名为 `openviking_<tool>` 的 pi 工具,当前 16 个([§2.1](#_2-1-服务端-mcp-工具面))。扩展里没有任何工具目录,服务端增删工具,pi 下一次会话即跟上,不需要发插件版本。召回、会话同步、profile 注入与 takeover 仍走 REST。9 事件 + `/viking` 命令;tool_call 拦截路径是 `viking://` URI 的 read/grep/find/ls/write/edit,bash 命令带 `viking://` URI 时,tool_result 在结果末尾追加提示。版本 0.4.0。- **能力亮点**: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` 仍可读)。+- **行为要点**:默认 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 与 `/mcp` 握手三项前置([§1.1](#_1-1-主动工具面-agentic-调用能力)),ROOT 角色的 API key 访问 `/mcp` 会被 403 拒绝,凭据链最终落到 `ov.conf` 的 `server.root_api_key` 时本次会话就没有工具——0.4.0 之前是 REST 工具照常注册、每次调用静默返回 "No results found.";`openviking_remember` 走 MCP 面,即自建一次性会话并立即提交,不再并入 pi 的会话([§2.1](#_2-1-服务端-mcp-工具面));`openviking_add_resource` 可直接摄取远端 URL,本地路径则由服务端返回一条上传指引,需要模型用 `bash` 把文件 POST 上去,与其他 MCP harness 一致;`openviking_read` 只返回全文,目录 URI 会得到 `Cannot render …: URI points to a directory`,旧的 `level="abstract"/"overview"` 两档在 MCP 面没有对应工具,替代路径是 `openviking_search(mode="context", detail="overview")` 或 `openviking_tree(include_abstract=true)`,takeover 的归档 overview 仍由扩展自己经 REST 注入;单次工具调用受共享的 `timeoutMs` 约束(15000ms,`OPENVIKING_TIMEOUT_MS` 可调),`write`/`edit` 带 `wait=true` 或 `add_resource` 同步 ingest 有可能超过,而超时或 ESC 只让本地调用失败,已经发出的请求会跑完,写入仍可能已经生效;从 0.3.x 升级时全部工具改名且没有别名期,`--tools` / `--exclude-tools` 白名单里写死的 `viking_*` 必须手工替换,否则工具会静默消失;非 takeover 模式下 `pi -c` 续跑会重新上报整条 branch。+- **配置**:env + ovcli.conf `plugin.pi` + workspace 文件(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));bypass 走共享 `isBypassed` 的 glob 匹配,键名 `bypassSessionPatterns`(旧名 `bypassPatterns` 仍可读);共享键 `mcpEnabled: false` 现在对 pi 也生效:不发起桥接、不注册工具,`/viking` 标注成配置而非故障。- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |takeover [§3.4.2](#_3-4-2-pi-takeover) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。## openclawdiff --git a/docs/zh/agent-integrations/18-plugin-development.md b/docs/zh/agent-integrations/18-plugin-development.mdindex 24e78032f..8330466e1 100644--- a/docs/zh/agent-integrations/18-plugin-development.md+++ b/docs/zh/agent-integrations/18-plugin-development.md@@ -74,6 +74,7 @@ Task: <describe the plugin addition, fix, or maintenance change>| 通过配置文件安装 hook 和 MCP;公共调度足够表达生命周期 | 在 `agent-hook-plugin/hosts/` 增加适配器及宿主配置 | [agent-hook-plugin](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md) || 原生插件要求独立 manifest、目录和生命周期入口 | 独立插件目录,入口调用共享运行时 | [Claude Code](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md)、[Codex](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) || 以宿主 SDK 回调运行,需要常驻状态或 dispose/idle 回调 | 使用宿主扩展包,复用共享能力,明确自己的会话调度 | [OpenCode](https://github.com/volcengine/OpenViking/blob/main/examples/opencode-plugin/README.md)、[DSH](https://github.com/volcengine/OpenViking/blob/main/examples/dsh-memory-plugin/README.md) |+| 宿主能注册原生工具,但自身没有 MCP 支持 | 使用官方 MCP 客户端,把服务端的 `tools/list` 注册成加 `openviking_` 前缀的宿主原生工具;不得自行维护工具目录 | [pi](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md) || 只有 MCP,没有自动注入或完整会话记录 | 交付 MCP-only 集成,明确能力范围 | [Agent Plugins](https://github.com/volcengine/OpenViking/blob/main/agent-plugins/README.md) |只因新增宿主名称,不应复制 Claude Code 或 Codex 的整个目录。反过来,如果宿主有独立的会话状态机,也不应不断往公共 dispatcher 加 `isFoo`、`specialStop` 一类开关来容纳它。diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex 54f9aff1a..50773c5db 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -2322,13 +2322,20 @@ install_pi() {warn "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"return 0fi+ command -v npm >/dev/null 2>&1 || { err "pi: npm is required to install the MCP client"; return 1; }+ "$NODE_BIN" -e 'const [major, minor] = process.versions.node.split(".").map(Number); process.exit(major > 22 || (major === 22 && minor >= 19) ? 0 : 1)' || {+ err "pi: Node.js 22.19.0 or newer is required"+ return 1+ }local plugin_dir dest tmpplugin_dir="$(plugin_dir_on_disk pi-coding-agent-extension)" || {warn "$(t 'pi extension sources not found; skipping.' '未找到 pi 扩展源码,跳过。')"return 0}sync_shared_runtime- if [ ! -f "$plugin_dir/shared/credentials.mjs" ]; then+ if [ ! -f "$plugin_dir/shared/credentials.mjs" ] \+ || [ ! -f "$plugin_dir/shared/ov-http.mjs" ] \+ || [ ! -f "$plugin_dir/shared/mcp-proxy-config.mjs" ]; thenwarn "$(t 'pi extension shared runtime is missing; run node examples/memory-plugin-shared/sync.mjs and retry.' '未找到 pi 扩展的共享运行时;请先运行 node examples/memory-plugin-shared/sync.mjs 再重试。')"return 0fi@@ -2337,6 +2344,12 @@ install_pi() {rm -rf "$tmp"mkdir -p "$tmp"(cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - .) | (cd "$tmp" && tar -xf -)+ if ! (cd "$tmp" && npm ci --omit=dev --ignore-scripts --no-audit --no-fund \+ && "$NODE_BIN" --input-type=module -e 'await import("./lib/mcp-bridge.mjs")'); then+ err "pi: dependency installation failed; the existing extension was kept"+ rm -rf "$tmp"+ return 1+ firm -rf "$dest"mkdir -p "$(dirname "$dest")"mv "$tmp" "$dest"@@ -2585,6 +2598,11 @@ EOFif [ -f "$HOME/.pi/agent/extensions/openviking/shared/recall-core.mjs" ]; thennode --check "$HOME/.pi/agent/extensions/openviking/shared/recall-core.mjs" || ok=0fi+ (cd "$HOME/.pi/agent/extensions/openviking" && "$NODE_BIN" --input-type=module \+ -e 'await import("./lib/mcp-bridge.mjs")') || ok=0+ if [ -f "$HOME/.pi/agent/extensions/openviking/shared/mcp-proxy-config.mjs" ]; then+ node --check "$HOME/.pi/agent/extensions/openviking/shared/mcp-proxy-config.mjs" || ok=0+ fifiif contains_harness dsh && command -v dsh >/dev/null 2>&1; thenlocal dsh_profile="${DSH_PROFILE:-$DSH_PROFILE_DEFAULT}"diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjsindex 5e4e3eef9..3974a6779 100644--- a/examples/memory-plugin-shared/release-marketplace.test.mjs+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { spawnSync } from "node:child_process";-import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve, sep } from "node:path";import test from "node:test";@@ -19,7 +19,7 @@ function run(command, args, options = {}) {});}-test("release marketplace archive supports a ZCode TOS install", () => {+test("release marketplace archive supports ZCode and pi TOS installs", () => {const tmp = mkdtempSync(join(tmpdir(), "openviking-zcode-release-"));try {const stage = join(tmp, "memory-plugin-marketplace");@@ -97,6 +97,33 @@ test("release marketplace archive supports a ZCode TOS install", () => {assert.ok(script, `${command} names no script`);assert.ok(existsSync(script), `${script} is missing after install`);}++ const bin = join(tmp, "bin");+ mkdirSync(bin);+ writeFileSync(join(bin, "pi"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });+ const piArgs = [installer, "--harness", "pi", "--dist", "tos", "--source", "archive",+ "--lang", "en", "--url", "http://127.0.0.1:1933", "--api-key", "", "--yes"];+ const piEnv = { ...process.env, HOME: home, PATH: bin + ":" + process.env.PATH,+ OPENVIKING_HOME: join(home, ".openviking"),+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: "file://" + join(tmp, "memory-plugin-marketplace.zip") };+ const piInstalled = run("bash", piArgs, { env: piEnv });+ assert.equal(piInstalled.status, 0, piInstalled.stdout + piInstalled.stderr);+ const piRoot = join(home, ".pi", "agent", "extensions", "openviking");+ const imported = run("node", ["--input-type=module", "-e", 'await import("./lib/mcp-bridge.mjs"); await import("./tools.ts")'], { cwd: piRoot });+ assert.equal(imported.status, 0, imported.stdout + imported.stderr);+ assert.ok(existsSync(join(piRoot, "package-lock.json")));+ assert.equal(existsSync(join(piRoot, "shared", "mcp-proxy-core.mjs")), false);++ // Both an npm failure and a false-success npm must leave the old install usable.+ writeFileSync(join(piRoot, "installed-before-upgrade"), "keep");+ for (const exitCode of [1, 0]) {+ writeFileSync(join(bin, "npm"), "#!/bin/sh\nexit " + exitCode + "\n", { mode: 0o755 });+ const failed = run("bash", piArgs, { env: piEnv });+ assert.notEqual(failed.status, 0, failed.stdout + failed.stderr);+ assert.equal(readFileSync(join(piRoot, "installed-before-upgrade"), "utf8"), "keep");+ assert.equal(existsSync(piRoot + ".tmp"), false);+ assert.match(failed.stdout + failed.stderr, /existing extension was kept/);+ }} finally {rmSync(tmp, { recursive: true, force: true });}@@ -124,6 +151,16 @@ test("staging rejects an archive missing a generated shared copy", () => {assert.ok(existsSync(join(stage, file)), `${file} is not in the staged tree`);}+ const piPackage = JSON.parse(readFileSync(join(stage, "pi-coding-agent-extension", "package.json")));+ const lockPath = join(stage, "pi-coding-agent-extension", "package-lock.json");+ const lock = readFileSync(lockPath);+ assert.deepEqual(JSON.parse(lock).packages[""].dependencies, piPackage.dependencies);+ rmSync(lockPath);+ const missingLock = run("node", [archiveCheck, stage, ...stagedDirs]);+ assert.equal(missingLock.status, 1);+ assert.match(missingLock.stderr, /pi-coding-agent-extension\/package-lock.json/);+ writeFileSync(lockPath, lock);+rmSync(join(stage, generated[0]));const rechecked = run("node", [archiveCheck, stage, ...stagedDirs]);assert.equal(rechecked.status, 1, `${rechecked.stdout}\n${rechecked.stderr}`);diff --git a/examples/memory-plugin-shared/uri-guard.test.mjs b/examples/memory-plugin-shared/uri-guard.test.mjsindex 30cacb529..012acd025 100644--- a/examples/memory-plugin-shared/uri-guard.test.mjs+++ b/examples/memory-plugin-shared/uri-guard.test.mjs@@ -101,12 +101,13 @@ test("buildGuardNotice names the plugin, the URI, the replacement and the way ou})test("evaluateUriGuard takes the host's own replacement tools and examples", () => {+ // The shape pi's adapter passes in.const hints = {- read: { tool: "viking_read", example: (uri) => `viking_read(uri="${uri}", level="overview")` },+ read: { tool: "openviking_read", example: (uri) => `openviking_read(uris=["${uri}"])` },}const decision = evaluateUriGuard("read", { path: "viking://resources/a.md" }, { hints })- assert.match(decision?.reason ?? "", /Use viking_read instead/)- assert.match(decision?.reason ?? "", /level="overview"/)+ assert.match(decision?.reason ?? "", /Use openviking_read instead/)+ assert.match(decision?.reason ?? "", /uris=\["viking:\/\/resources\/a\.md"\]/)assert.equal(evaluateUriGuard("glob", { pattern: "viking://resources/**" }, { hints }), null)})diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.mdindex 9ad32c28e..a88b9378f 100644--- a/examples/pi-coding-agent-extension/DESIGN.md+++ b/examples/pi-coding-agent-extension/DESIGN.md@@ -1,8 +1,8 @@# Pi OpenViking Extension — Design-The extension gives a [pi](https://github.com/earendil-works/pi) session long-term memory and, when takeover is on, lets OpenViking own the session's committed history. It is a directory of TypeScript modules loaded directly by pi's `jiti` transpiler: no build step, no dependencies beyond what pi already provides, no MCP server. Everything reaches OpenViking over its REST API.+The extension gives a pi session long-term memory and lets OpenViking own committed history when takeover is enabled. TypeScript loads directly through pi's jiti transpiler. Recall, session capture, commits, context takeover and health checks use REST; model-facing tools use the official MCP client SDK over Streamable HTTP.-README.md is the operator's document — installation, every configuration knob, the tool list. This one is the maintainer's: what each module is responsible for, how the pieces meet at pi's event boundaries, and the reasons behind the choices that the code cannot state for itself.+README.md is the operator's document — installation, every configuration knob, the tool surface. This one is the maintainer's: what each module is responsible for, how the pieces meet at pi's event boundaries, and the reasons behind the choices that the code cannot state for itself.## Design ancestry@@ -27,15 +27,23 @@ pi-coding-agent-extension/├── recall.ts # per-prompt recall search and injection├── sync.ts # capture, delivery, pending queue, commit├── takeover.ts # binds the takeover state machine to pi-├── tools.ts # the seven model-facing viking_* tools+├── tools.ts # publishes the bridge's tool descriptors as pi tools├── index.ts # entry point: event handlers and the /viking command├── package.json # name and version; pi loads index.ts regardless├── lib/ # pi-specific logic kept out of the event handlers+│ ├── mcp-bridge.mjs # official SDK connection lifecycle+│ ├── mcp-result.mjs # pi content conversion and output limit+│ ├── takeover-core.mjs # the context-takeover state machine+│ ├── recall-ledger.mjs # injected recall blocks, keyed by pi entry id+│ ├── capture-adapter.mjs # a pi branch -> capture payloads+│ └── uri-guard-adapter.mjs # pi tool events -> the shared URI guard├── shared/ # generated copy of memory-plugin-shared/lib├── scripts/ # live e2e harness└── tests/ # node --test suites```+Modules imported by TypeScript have adjacent declarations; the result converter is internal to the JavaScript bridge. The bridge and tool registration can be tested without installing pi.+## Modules### config.ts@@ -52,7 +60,7 @@ The transport is built once in the constructor by `createOvHttp` from `shared/ovHeaders are built per request: `Authorization: Bearer` when a key is configured, `X-OpenViking-Actor-Peer` for peer scoping, the shared `User-Agent`, and `X-OpenViking-Account` / `X-OpenViking-User` only when `sendIdentityHeaders` says the deployment is in trusted mode. Timeouts follow the class of call — 5s for health and session metadata, 10s for reads and message writes, 30s for commit and resource ingestion.-Above that sit thin methods for the endpoints this extension and its tools need: health, session metadata, session context, message append, commit, `search/find`, the three content tiers (abstract, overview, read), `fs/ls`, `fs/stat`, delete, and resource ingestion. Commit is exposed twice because two callers need different things from it: `commitSessionResponse` returns the whole envelope so a failure can be logged with its status and trace id, `commitSession` returns just the result.+Above that sit thin methods for the endpoints the extension itself needs: health, session metadata, session context, and commit through `commitSessionResponse`, which returns the whole envelope so a failure can be logged with its status and trace id. Search, content reads, filesystem operations and resource ingestion used to have wrappers here too; they are the model's business and reach the server over MCP now, so they are gone rather than kept as a second path to the same endpoints that would drift from the first.### recall.ts@@ -147,21 +155,21 @@ If any step fails the handler returns nothing and pi's default compaction runs.`scripts/e2e-live.sh` drives a real pi binary, a real OpenViking server and a real LLM endpoint (its required and optional environment variables are documented at the top of `scripts/e2e-live.mjs`). It runs three `pi -p` / `pi -c` turns with a tiny takeover threshold and asserts that the third provider payload carries `[OpenViking Session Context]` while the padding from the first turn is gone from the raw conversation history. Nothing in the unit suites covers that end to end, so it stays a manual gate.-### tools.ts+### MCP tools-Seven tools registered on pi's model, all sharing the one `OVClient`. Each handler answers "OpenViking server is not reachable." when the startup health check never succeeded, so a down server degrades to a message rather than an error.+The official `@modelcontextprotocol/client` SDK handles Streamable HTTP, initialization, JSON-RPC request pairing and cancellation. The small bridge owns a single connection and its startup promise. It does not run the shared stdio proxy or maintain a protocol implementation.-| Tool | Purpose |-|---|---|-| `viking_search` | Semantic search, optionally scoped to a `viking://` prefix |-| `viking_read` | Read one URI at `abstract`, `overview` or `full` detail |-| `viking_browse` | List a directory or stat an entry |-| `viking_remember` | Store a fact for cross-session persistence |-| `viking_forget` | Delete by URI, or by query when the match is strong |-| `viking_add_resource` | Ingest a URL into the knowledge base |-| `viking_archive_expand` | Expand an archived session back into detail |+`tools/list` supplies the catalogue, descriptions and input schemas. `tools.ts` registers names with the `openviking_` prefix once per session. SDK Ajv validation runs in `prepareArguments` before pi can coerce values or discard optional nulls; valid arguments are passed through unchanged. The original schema, including `additionalProperties`, is preserved. No repair rules or hand-written catalogue are maintained.++The bridge reuses shared configuration resolution and `buildOvHeaders`, including the same actor peer as REST recall. It reads configuration before connecting or calling a tool. Changes to the endpoint or request headers replace the connection. A failed transport is discarded for the next call; the failed call is never replayed. Protocol and tool errors do not cause reconnects. Tool registrations remain fixed until the next pi session.++Initialization, the initialized notification and tool discovery share a 5-second deadline. Calls share their configured `timeoutMs` budget with any necessary connection attempt. Cancellation stops local waiting; it does not guarantee that a server-side write was cancelled. Closing the client releases the transport. OpenViking's MCP endpoint is stateless, so no remote session cleanup protocol is needed.++`mcp-result.mjs` maps MCP content to pi's text/image blocks, avoids duplicate structured text and limits all result text together to 50 KiB / 2000 lines. MCP errors are reported as failed tools. No `promptSnippet` or `promptGuidelines` is added: tools discovered during `before_agent_start` would otherwise change pi's cached prompt prefix on the following turn. The existing prompt line names the registered tools immediately.++The extension's coexistence marker is owned by its instance and removed on shutdown, including reload. A pending startup cannot restore the marker or register tools after shutdown. MCP startup failure leaves REST recall, sync and takeover available.-Two of them are less direct than they look. `viking_remember` does not write a memory: it appends a `[Remember — <category>]` message to the live OV session, so extraction treats it like any other turn and the fact goes through the same pipeline as everything else. `viking_forget` by query deletes only when the top match scores above 0.8; below that it reports no strong match rather than guessing which memory to destroy. There is no `add_skill` tool — pi has a skill system of its own.+The npm client version is pinned in `package.json` and `package-lock.json`. Installation runs `npm ci` and imports the client in the staging directory before replacing an existing extension. Marketplace archives contain the lockfile, not `node_modules`.### index.ts@@ -176,16 +184,16 @@ The entry point. It loads the config, returns immediately when disabled, constru| `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 |+| `session_shutdown` | Close the MCP bridge, then persist takeover state or commit one last time || `agent_end` | Invalidate the recall cache |-**Two guards.** The bypass check runs the shared `isBypassed` against the cwd, so a scratch directory never pollutes long-term memory; the pattern syntax is the shared one, identical across harnesses. The health check runs once — if the server is unreachable the extension stays disconnected for the whole session, every handler returns early, and the tools say so. No retries, no repeated warnings.+**Two guards.** The bypass check runs the shared `isBypassed` against the cwd, so a scratch directory never pollutes long-term memory; the pattern syntax is the shared one, identical across harnesses. The health check runs once — if the server is unreachable the extension stays disconnected for the whole session, every handler returns early and no tools are registered. No retries, no repeated warnings. A bypassed directory never opens the bridge at all: bypass means this directory does not touch OpenViking.-**Startup is memoized, not awaited.** The startup chain — health check, session derivation, pending replay, profile build, takeover restore, tool registration — costs a couple of seconds against a remote server, and `session_start` does not await it, because that delay would land on every pi launch. `before_agent_start` awaits the same in-flight promise, so the first turn still gets its profile and recall. That is also the only startup path a `pi -c` continuation has: pi does not fire `session_start` for one.+**Startup is memoized, not awaited.** The startup chain — health check, session derivation, pending replay, profile build, takeover restore, tool registration — costs a couple of seconds against a remote server, and `session_start` does not await it, because that delay would land on every pi launch. `before_agent_start` awaits the same in-flight promise, so the first turn still gets its profile and recall. That is also the only startup path a `pi -c` continuation has: pi does not fire `session_start` for one. The MCP handshake is started right after the health check so it runs alongside the pending replay, the profile build and takeover recovery, and is joined at the end of the chain; when it failed, a separate branch in `before_agent_start` retries it once per turn until the session has tools. The list is never refreshed after that: pi has no `unregisterTool`, and adding or removing a tool mid-session rewrites the prompt's tool section and invalidates the provider's cached prefix. With the shared `mcpEnabled` key set to `false` there is no bridge at all, and the status line does not report that as a failure — it is what was asked for.-**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.+**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 OpenViking tools. That line is generated from the names that actually registered, so it can never promise a tool the server does not have, and it is omitted entirely when the handshake produced none. 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 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.+**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`, `write`, `edit` — and blocks the call with the equivalent `openviking_*` invocation spelled out, written to be valid against the server's own schemas. 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. `edit` is handed only its `path`: pi carries the replacement text in `edits[].oldText/newText`, which are not in the shared guard's content-key allowlist, so the generic sweep would read them as locations and block any edit whose new text merely mentions a `viking://` URI — which fires the moment somebody edits this repository's own docs. `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 `openviking_read` / `openviking_search` and tells the model to ignore the notice when the URI was intentional. A tool absent from the hint table is never guarded, which is why the `openviking_*` tools themselves need no allowlist.**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/README.md b/examples/pi-coding-agent-extension/README.mdindex 83e2226d8..fca956ac1 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -13,7 +13,7 @@ Long-term semantic memory and context takeover for [pi](https://github.com/earen### Prerequisites- **pi coding agent** installed (`npm i -g @earendil-works/pi-coding-agent`)-- **Node.js 18+** (for the extension's TypeScript runtime)+- **Node.js 22.19.0+** and **npm**- **An OpenViking server** reachable — local or remote### 1. Have an OpenViking server reachable@@ -34,7 +34,16 @@ Use the shared installer:bash examples/memory-plugin-shared/install.sh --harness pi```-The installer copies the extension to `~/.pi/agent/extensions/openviking`, which is one of pi's auto-discovery roots, so pi loads it on the next `pi` invocation — no `packages` entry is needed. (Registering the same path with `pi install` would load it twice, so the installer avoids that and clears any stale entry left by older versions.)+The installer installs the locked npm dependencies in a temporary directory before replacing the extension at `~/.pi/agent/extensions/openviking`, which is one of pi's auto-discovery roots, so pi loads it on the next `pi` invocation — no `packages` entry is needed. (Registering the same path with `pi install` would load it twice, so the installer avoids that and clears any stale entry left by older versions.)++For a manual copy, generate the shared runtime first, copy the extension, and install its dependencies:++```bash+node examples/memory-plugin-shared/sync.mjs+mkdir -p ~/.pi/agent/extensions/openviking+cp -R examples/pi-coding-agent-extension/. ~/.pi/agent/extensions/openviking/+npm ci --prefix ~/.pi/agent/extensions/openviking --omit=dev --ignore-scripts+```### 3. Configure (optional)@@ -108,7 +117,7 @@ Recall defaults to the broad mode: global memory, the current workspace, and othpi```-The extension shows an `[OpenViking]` status line on startup. Tools (`viking_search`, `viking_remember`, etc.) are registered automatically. Memories persist across sessions — no additional setup.+The extension shows an `[OpenViking]` status line on startup. The server's own MCP tools (`openviking_search`, `openviking_remember`, and the rest of whatever it exposes) are registered automatically. Memories persist across sessions — no additional setup.## Configuration Reference@@ -169,7 +178,7 @@ integrations should configure category `quotas` when they need exact ceilings.| `captureMode` | `"semantic"` | `"semantic"` (always capture) or `"keyword"` (trigger-based) || `captureMaxLength` | `24000` | Max sanitized text length for the capture decision || `captureAssistantTurns` | `true` | Include assistant turns (text + tool USE inputs) |-| `captureToolResults` | `false` | Include tool result output (noisy — off by default) |+| `captureToolResults` | `false` | Declared in the shared schema, but this extension never reads it: `lib/capture-adapter.mjs` keeps every structured tool part, so tool results are captured either way, bounded by `captureToolMaxChars` || `captureToolMaxChars` | `1000000` | Guard cap on one tool part's `tool_output`; the server externalizes oversized output || `commitTokenThreshold` | `20000` | Pending-token threshold for client-driven commit || `commitKeepRecentCount` | `10` | Live tail kept after commit |@@ -222,17 +231,23 @@ Bypass now runs through the same matcher every other OpenViking harness uses, so└────────┬──────────────────┬───────────┬──────────────┘│ │ ││ ┌───────────────▼───────────▼────────┐- │ │ extension modules (.ts) │- │ │ client / sync / recall / tools │──────► OpenViking- │ └─────────────────────────────────────┘ Server- │ (HTTP API)+ │ │ extension modules (.ts) │ OpenViking+ │ │ client / sync / recall / takeover │──────► REST API+ │ └─────────────────────────────────────┘ (recall, session+ │ sync, takeover,+ │ health)│ ┌──────────────────────────────────────┐- └──► 7 registered LLM tools │- │ viking_search / viking_read / … │+ └──► tools.ts + lib/mcp-bridge.mjs │──────► OpenViking+ │ the server's own tools/list, │ /mcp endpoint+ │ prefixed openviking_ │ (model tools)└──────────────────────────────────────┘```-The extension is a single directory of TypeScript files loaded by pi's `jiti` transpiler — no build step, no npm dependencies, no MCP server. All communication goes over HTTP to the OpenViking REST API.+The extension's TypeScript files are loaded by pi's `jiti` transpiler without a build step. Recall, session sync, context takeover and the startup health check use the REST API. Model-facing tools use the official `@modelcontextprotocol/client` SDK over Streamable HTTP and mirror the server's `/mcp` catalogue. Configuration and identity headers reuse the shared library.++MCP initialization and tool discovery share a 5-second deadline. Each tool call uses `timeoutMs` (15 seconds by default), including any reconnection. Credentials and connection settings are reloaded before calls; a transport failure is returned immediately and the next call reconnects. Calls are never automatically replayed. Cancellation ends the client's wait and cannot undo a write already accepted by the server.++Arguments are checked against the server's original schema before pi's own validation. Invalid nulls, scalar-to-array substitutions and stringified JSON are rejected rather than repaired. Text results share a 50 KiB / 2000-line limit across all content blocks.### Event Flow@@ -268,19 +283,47 @@ Tool capture preserves structured tool parts with bounded inputs and outputs. Th## LLM Tools-The extension registers 7 tools that pi's model can invoke on demand:+The extension keeps no tool catalogue of its own. At session start it asks the server's `/mcp` endpoint for `tools/list` and registers one pi tool per descriptor it gets back, named `openviking_` + the server's own name, with the server's description and argument schema. A server that gains, drops or re-documents a tool changes pi's tool surface at the next session, with no extension release.++Against a current server, that is these 15:++| Tool | Description |+|-----------------------------|-------------------------------------------------------------------------|+| `openviking_find` | Fast ranked retrieval across memories, resources and skills |+| `openviking_search` | Deep retrieval with session context and intent analysis; `mode="context"` returns an assembled block |+| `openviking_read` | Read one or more `viking://` file URIs, with line-based `offset`/`limit` |+| `openviking_list` | List one sorted page under a `viking://` directory |+| `openviking_tree` | Show a recursive directory tree, optionally with abstracts |+| `openviking_remember` | Store messages as long-term memory and commit them for extraction |+| `openviking_write` | Write text to a `viking://` file |+| `openviking_edit` | Replace an exact string in an existing `viking://` file |+| `openviking_add_resource` | Ingest a URL, repository or local file as a resource |+| `openviking_list_watches` | List the auto-refresh watch tasks visible to this user |+| `openviking_cancel_watch` | Cancel a watch task by its target URI |+| `openviking_grep` | Regex search inside `viking://` files |+| `openviking_glob` | Find `viking://` files matching a glob pattern |+| `openviking_forget` | Permanently delete a `viking://` URI |+| `openviking_health` | Check that the OpenViking server is healthy |++That table is a snapshot of one server, not a contract; `/viking` reports how many tools registered against your own.++The canonical `/viking` command (type `/viking` in pi's chat) displays connection status, session info, how many tools registered — or the handshake error when none did — and accepts `commit` for manual synchronous commit.++## Upgrading from 0.3.x++0.4.0 replaces the seven hand-written `viking_*` REST tools with the server's own MCP tool surface. There is no alias period: the old names are gone.-| Tool | Description |-|--------------------------|------------------------------------------------------------|-| `viking_search` | Semantic search across memories, resources, and skills |-| `viking_read` | Read a `viking://` URI at abstract / overview / full level |-| `viking_browse` | List directory contents or stat a `viking://` URI |-| `viking_remember` | Store a fact or preference into long-term memory |-| `viking_forget` | Delete a memory by URI or search query |-| `viking_add_resource` | Ingest a URL into OpenViking for indexed retrieval |-| `viking_archive_expand` | Expand an archived session back into raw conversation |+- **Tool names.** Every tool is now `openviking_` + the server's own name: `viking_search` → `openviking_search`, `viking_read` → `openviking_read`, `viking_remember` → `openviking_remember`, `viking_forget` → `openviking_forget`, `viking_add_resource` → `openviking_add_resource`. `viking_browse` is covered by `openviking_list`, `openviking_tree` and `openviking_glob`; its stat mode and `viking_archive_expand` have no successor.+- **`--tools` / `--exclude-tools` allowlists.** pi matches those by exact name, so an allowlist that still says `viking_search` drops the tool silently instead of erroring. Rename the entries by hand.+- **`remember` is its own session.** It used to append a message to the live pi session and wait for that session's commit. The MCP tool opens a dedicated `mcp-store-*` session, writes the messages and commits it immediately, so what you asked to remember goes into extraction on the spot.+- **`read` returns full text only.** The `level="abstract"` and `level="overview"` tiers are gone, and MCP `read` cannot read a directory's overview — `.overview.md` does not appear in `list` either. Use `openviking_search(mode="context", detail="overview")` or `openviking_tree(include_abstract=true)` instead. Context takeover is unaffected: the extension still fetches the archive overview itself over REST.+- **`forget` is URI-only.** It deletes the URI it is handed. The old deletion-by-query path, with its score > 0.8 guard and its `recursive=false` default, went with the tool that had it.+- **`add_resource` and local files.** For a filesystem path the server answers with a one-time upload URL, and the model has to POST the file there with `bash`. Remote URLs still ingest directly. This is how every other MCP harness behaves.+- **A ROOT api key now leaves the session with no tools.** Root keys are refused on `/mcp` with 403. Before, the REST tools registered and every call came back empty; now nothing registers, the status line shows `tools ✗`, and `/viking` names the 403. Create a user or admin key and put that in `ovcli.conf`.+- **`mcpEnabled: false` now applies to pi.** The shared key in `ovcli.conf`'s `plugin` section already turned the MCP surface off for other harnesses. Set for pi it means no handshake and no tools — and that is not reported as a failure; recall, capture and takeover carry on.+- **Already running pi-mcp-adapter?** Do not also point it at OpenViking. The same tools would then appear twice in one session under two different names.-The canonical `/viking` command (type `/viking` in pi's chat) displays connection status, session info, and accepts `commit` for manual synchronous commit.+A failed handshake never fails startup: recall, session sync and takeover keep working, the session simply has no OpenViking tools. The bridge retries on a later turn, so a server started after pi is picked up without restarting pi.## Compared to Pi's Built-in Memory@@ -303,7 +346,7 @@ Both plugins share the same core design (informed by each other):|---------------------|----------------------------------------|----------------------------------------|| Architecture | Hook scripts (.mjs) + MCP delegation | Native TypeScript extension || Recall timing | Synchronous (UserPromptSubmit hook) | Synchronous (context event) |-| Tool delivery | OV server's MCP endpoint (16 tools) | pi.registerTool() (7 tools) |+| Tool delivery | OV server's MCP endpoint (count follows the server) | Official MCP client, published through pi.registerTool() (same count) || Write path | Detached worker (async) | Async promise (pi's event loop) || Installation | `claude plugin install` + setup script | Copy directory → auto-discovered || Memory index | Shared profile block (memories + skills), injected at session start | Same block, folded into the system prompt every turn |@@ -320,16 +363,18 @@ pi-coding-agent-extension/├── sync.ts # Turn capture, write queue, session lifecycle├── recall.ts # Synchronous recall with ranking + budget├── takeover.ts # Thin pi binding around lib/takeover-core.mjs-├── tools.ts # 7 registered LLM tools + /viking command+├── tools.ts # Publishes the server's MCP tools as pi tools+├── lib/mcp-bridge.mjs # Official SDK connection lifecycle+├── lib/mcp-result.mjs # pi content conversion and output limit├── lib/takeover-core.mjs # Pure context-takeover state machine├── lib/recall-ledger.mjs # Injected recall blocks, replayed to keep prompt caches warm-├── index.ts # Extension entry point (event handlers)+├── index.ts # Extension entry point (event handlers + /viking command)├── package.json # Name and version (the User-Agent's, and the release gate's)├── DESIGN.md # Module-by-module design, including context takeover└── README.md```-All TypeScript files are loaded directly by pi's built-in `jiti` transpiler — zero dependencies beyond Node.js.+TypeScript is loaded directly by pi's jiti transpiler. The official MCP client is installed from the committed npm lockfile; node_modules is not bundled in marketplace archives.## Troubleshootingdiff --git a/examples/pi-coding-agent-extension/client.ts b/examples/pi-coding-agent-extension/client.tsindex 25e4b62ec..442ccd9bc 100644--- a/examples/pi-coding-agent-extension/client.ts+++ b/examples/pi-coding-agent-extension/client.ts@@ -5,38 +5,13 @@ import { createOvHttp } from "./shared/ov-http.mjs";// --- OV API Response Shapes ---// All OV responses wrap in: { status: "ok"|"error", result: T, error?: {...}, ... }// This client normalizes to { ok, result } internally.--export interface OVSearchResult {- uri: string;- context_type: string; // "memory" | "resource" | "skill"- score: number;- abstract: string;- overview: string | null;- level: number; // 0=L0, 1=L1, 2=L2- category: string;- match_reason: string;-}--export interface OVDirEntry {- uri: string;- name: string;- isDir: boolean;- size: number;- mode: number;- modTime: string;- abstract: string;-}--export interface OVStatInfo {- name: string;- size: number;- mode: number;- modTime: string;- isDir: boolean;- isLocked: boolean;- uri?: string;- count?: number; // directories only-}+//+// Scope: session plumbing only — health, the OV session and its commit, plus the+// raw `fetchJSON` the shared recall/sync/profile modules are built on. Search,+// content reads, filesystem operations and resource ingest are the model's+// business and reach the server over MCP (`lib/mcp-bridge.mjs`), so their REST+// wrappers are gone rather than kept as a second, drifting path to the same+// endpoints.export interface OVSessionMeta {session_id: string;@@ -133,16 +108,6 @@ export class OVClient {return res.ok ? res.result : null;}- /** POST /api/v1/sessions/{id}/messages — add a message (simple text mode) */- async addMessage(sessionId: string, role: string, content: string): Promise<boolean> {- const res = await this.fetchJSON<any>(- `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,- { method: "POST", body: JSON.stringify({ role, content }) },- { timeoutMs: 10000 },- );- return res.ok;- }-/** POST /api/v1/sessions/{id}/commit — commit session for archiving + extraction */async commitSessionResponse(sessionId: string,@@ -163,140 +128,4 @@ export class OVClient {status: res.status,};}-- async commitSession(- sessionId: string,- keepRecentCount = this.cfg.commitKeepRecentCount,- ): Promise<OVCommitResult | null> {- return (await this.commitSessionResponse(sessionId, keepRecentCount)).result;- }-- // ========== Search ==========-- /** POST /api/v1/search/find — basic vector search */- async find(- query: string,- opts?: { targetUri?: string; topK?: number; scoreThreshold?: number },- ): Promise<OVSearchResult[]> {- const body: Record<string, unknown> = { query };- if (opts?.targetUri) body.target_uri = opts.targetUri;- if (opts?.topK) body.limit = opts.topK;- if (opts?.scoreThreshold) body.score_threshold = opts.scoreThreshold;-- const res = await this.fetchJSON<any>("/api/v1/search/find", {- method: "POST", body: JSON.stringify(body),- }, { timeoutMs: 10000 });- if (!res.ok || !res.result) return [];-- // OV returns { memories: [...], resources: [...], skills: [...], total }- const all: OVSearchResult[] = [];- for (const bucket of ["memories", "resources", "skills"]) {- const items = res.result[bucket];- if (Array.isArray(items)) {- for (const m of items) {- all.push({- uri: m.uri ?? "",- context_type: m.context_type ?? (bucket === "memories" ? "memory" : bucket === "skills" ? "skill" : "resource"),- score: m.score ?? 0,- abstract: m.abstract ?? "",- overview: m.overview ?? null,- level: m.level ?? 0,- category: m.category ?? "",- match_reason: m.match_reason ?? "",- });- }- }- }- return all;- }-- // ========== Content ==========-- /** GET /api/v1/content/abstract — L0 summary */- async abstract(uri: string): Promise<string | null> {- const res = await this.fetchJSON<string>(- `/api/v1/content/abstract?uri=${encodeURIComponent(uri)}`,- undefined, { timeoutMs: 10000 },- );- return res.ok ? res.result : null;- }-- /** GET /api/v1/content/overview — L1 overview (directories only) */- async overview(uri: string): Promise<string | null> {- const res = await this.fetchJSON<string>(- `/api/v1/content/overview?uri=${encodeURIComponent(uri)}`,- undefined, { timeoutMs: 10000 },- );- return res.ok ? res.result : null;- }-- /** GET /api/v1/content/read — L2 full content (files only) */- async readContent(uri: string): Promise<string | null> {- const res = await this.fetchJSON<string>(- `/api/v1/content/read?uri=${encodeURIComponent(uri)}`,- undefined, { timeoutMs: 10000 },- );- return res.ok ? res.result : null;- }-- // ========== Filesystem ==========-- /** GET /api/v1/fs/ls — list directory */- async ls(uri: string): Promise<OVDirEntry[]> {- const res = await this.fetchJSON<any[]>(- `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}`,- undefined, { timeoutMs: 10000 },- );- if (!res.ok || !Array.isArray(res.result)) return [];- return res.result.map(e => ({- uri: e.uri ?? "",- name: e.name ?? uriBasename(e.uri ?? ""),- isDir: e.isDir ?? false,- size: e.size ?? 0,- mode: e.mode ?? 0,- modTime: e.modTime ?? "",- abstract: e.abstract ?? "",- }));- }-- /** GET /api/v1/fs/stat — file/directory metadata */- async stat(uri: string): Promise<OVStatInfo | null> {- const res = await this.fetchJSON<OVStatInfo>(- `/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,- undefined, { timeoutMs: 10000 },- );- return res.ok ? res.result : null;- }-- /** DELETE /api/v1/fs — remove file or directory */- async delete(uri: string, recursive = false): Promise<boolean> {- const res = await this.fetchJSON<any>(- `/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=${recursive}`,- { method: "DELETE" },- { timeoutMs: 10000 },- );- return res.ok;- }-- // ========== Resources ==========-- /** POST /api/v1/resources — ingest a URL or file path */- async addResource(- path: string, opts?: { to?: string },- ): Promise<{ root_uri: string } | null> {- const body: Record<string, unknown> = { path };- if (opts?.to) body.to = opts.to;- const res = await this.fetchJSON<{ root_uri: string }>(- "/api/v1/resources",- { method: "POST", body: JSON.stringify(body) },- { timeoutMs: 30000 },- );- return res.ok ? res.result : null;- }-}--function uriBasename(uri: string): string {- const cleaned = uri.replace(/\/+$/, "");- const last = cleaned.lastIndexOf("/");- return last >= 0 ? cleaned.slice(last + 1) : cleaned;}diff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.tsindex 46138518e..0cff597cc 100644--- a/examples/pi-coding-agent-extension/config.ts+++ b/examples/pi-coding-agent-extension/config.ts@@ -1,4 +1,5 @@import { readManifestVersion } from "./shared/credentials.mjs";+import { toMcpProxyConfig } from "./shared/mcp-proxy-config.mjs";import { buildPluginConfig } from "./shared/plugin-config.mjs";/** The version the User-Agent reports, read from the manifest the gate checks. */@@ -84,3 +85,8 @@ export function loadConfig(cwd: string = process.cwd()): OVConfig {peerId: config.effectivePeer.peerId,} as OVConfig;}++/** Tools use the same resolved identity and actor peer as REST recall. */+export function buildBridgeProxyConfig(cfg: OVConfig) {+ return toMcpProxyConfig(cfg, { peerId: cfg.peerId, debug: Boolean((cfg as any).debug || cfg.debugLogPath) });+}diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex 8c634a833..95b305592 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -10,9 +10,11 @@* (most mature, production-hardened), Hermes (anti-pattern: stale prefetch).*/import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";+import { dirname } from "node:path";+import { fileURLToPath } from "node:url";import { isCaptureEnabled } from "./shared/capture-utils.mjs";import { createLogger } from "./shared/debug-log.mjs";-import { loadConfig, type OVConfig } from "./config.js";+import { EXTENSION_VERSION, loadConfig, buildBridgeProxyConfig, type OVConfig } from "./config.js";import { OVClient } from "./client.js";import { RecallManager } from "./recall.js";import { RecallLedger } from "./lib/recall-ledger.mjs";@@ -20,13 +22,21 @@ import { SyncManager } from "./sync.js";import { buildProfileBlock } from "./shared/profile-inject.mjs";import { isBypassed } from "./shared/session-model.mjs";import { guardVikingUriToolCall, noticeVikingUriToolResult } from "./lib/uri-guard-adapter.mjs";-import { registerTools } from "./tools.js";+import { createMcpBridge, DEFAULT_HANDSHAKE_BUDGET_MS } from "./lib/mcp-bridge.mjs";+import { registerMcpTools } from "./tools.js";import { createTakeoverManager } from "./takeover.js";+/** This extension's directory, published for the experimental fork's probe. */+const EXTENSION_DIR = dirname(fileURLToPath(import.meta.url));+export default async function (pi: ExtensionAPI) {// --- Load config ---- const config = loadConfig();+ const cwd = process.cwd();+ const config = loadConfig(cwd);if (!config.enabled) return;+ // Shared key (`shared/config-schema.mjs`), already honoured by opencode: the+ // MCP tool surface is off, while recall, sync and takeover carry on.+ const mcpEnabled = (config as any).mcpEnabled !== false;// Env overrides@@ -50,22 +60,79 @@ export default async function (pi: ExtensionAPI) {log: (message: string) => logger.log("takeover", message),});+ // Re-read credentials before connecting or invoking a tool.+ const bridge = mcpEnabled+ ? createMcpBridge({+ readConfig: () => buildBridgeProxyConfig(loadConfig(cwd)),+ // No "memory" in the name: every plugin identity is moving to plain+ // `openviking`, and a new identifier starts out on the new spelling.+ clientInfo: { name: "openviking-pi", version: EXTENSION_VERSION },+ })+ : null;+// Session statelet connected = false;let bypassed = false;let profileBlock = "";let archiveOverview = "";+ let toolsReady = false;let toolsRegistered = false;+ let closed = false;+ const marker = { dir: EXTENSION_DIR };+ const toolNames: string[] = [];+ let toolFailureNotified = false;let compacted = false;let started = false;let startPromise: Promise<void> | null = null;+ /**+ * Take a finished handshake: register what the server listed, or report the+ * failure once.+ *+ * The tool list is never refreshed later in the session. pi has no+ * `unregisterTool`, and adding or removing a tool mid-session rewrites the+ * system prompt's tool section, which invalidates the provider's cached+ * prefix. A server that gained or lost a tool takes effect in the next pi+ * session.+ */+ const adoptBridgeTools = (+ ctx: any,+ state: { connected: boolean; error: string | null },+ ): void => {+ if (!bridge || closed || toolsRegistered) return;+ if (state.connected) {+ toolNames.push(...registerMcpTools(pi, bridge));+ toolsRegistered = true;+ toolsReady = toolNames.length > 0;+ logger.log("mcp_tools", { registered: toolNames.length });+ return;+ }+ // A dead, unauthorized or MCP-less server costs the session its tools and+ // nothing else, so it is said once and not repeated every turn.+ if (toolFailureNotified) return;+ toolFailureNotified = true;+ if (config.logLevel === "silent") return;+ ctx?.ui?.notify?.(+ `OpenViking: no tools this session — ${state.error || "handshake failed"}${rootKeyHint(state.error)}`,+ "warning",+ );+ };++ /** The `/viking` line about the tool surface: a count, or the last failure. */+ const toolsStatusLine = (): string => {+ if (!bridge) return "tools: disabled by mcpEnabled";+ if (toolNames.length) return `tools: ${toolNames.length}`;+ const error = bridge.state.error;+ if (!error) return "tools: none (handshake not finished)";+ return `tools: none — ${error}${rootKeyHint(error)}`;+ };+// ================================================================// Event Handlers// ================================================================const start = async (ctx: any): Promise<void> => {- if (started) return;+ if (started || closed) return;if (startPromise) return startPromise;startPromise = (async () => {@@ -78,6 +145,7 @@ export default async function (pi: ExtensionAPI) {// Health checkconnected = await client.health();+ if (closed) return;if (!connected) {if (config.logLevel === "info") {ctx.ui.notify("OpenViking: server not reachable", "warning");@@ -85,6 +153,15 @@ export default async function (pi: ExtensionAPI) {return;}+ // What the experimental fork probes to stand down. Set as soon as the+ // session is live, independently of any tool: a /mcp 401/403 leaves this+ // extension with zero tools while it still writes the OpenViking session,+ // and that is exactly the case the fork must not join.+ (globalThis as any).__OPENVIKING_PI_EXTENSION__ = marker;++ // Discover tools alongside REST startup; failure leaves REST available.+ const handshake = bridge ? bridge.connect(DEFAULT_HANDSHAKE_BUDGET_MS) : null;+// Ensure OV sessionconst piSessionId = ctx.sessionManager.getSessionId();recall.openLedger(piSessionId);@@ -111,12 +188,11 @@ export default async function (pi: ExtensionAPI) {archiveOverview = await fetchArchiveOverview(client, sync.sessionId, config);}- // Register tools (also needed for pi -c continuations).- if (!toolsRegistered) {- registerTools(pi, client, sync);- toolsRegistered = true;- }- updateStatus(ctx, connected, 0, sync.sessionId, config, takeover.state);+ // Join the handshake and publish whatever the server listed (also needed+ // for pi -c continuations, which never fire session_start).+ if (handshake) adoptBridgeTools(ctx, await handshake);+ if (closed) return;+ updateStatus(ctx, connected, 0, sync.sessionId, config, takeover.state, toolsReady);started = true;if (config.logLevel === "info") {@@ -143,10 +219,31 @@ export default async function (pi: ExtensionAPI) {// --- before_agent_start ---pi.on("before_agent_start", async (event, ctx) => {+ // Read before awaiting, because this is what separates the retry below+ // from the attempt start() makes: on the turn that runs the startup chain+ // this is false, and from the next turn on it is true. Testing `started`+ // after the await would be true on turn one as well, and the retry would+ // fire a second handshake in the same turn — a real one, since the bridge+ // clears its in-flight promise as soon as a failed attempt settles. That+ // costs the first turn a second handshake budget before recall is even+ // queued, for an answer start() already has.+ const wasStarted = started;+// session_start doesn't fire for pi -c continuations.await start(ctx);- if (!connected || bypassed) return;+ // Retry the handshake when the session is live but toolless — a server+ // started after pi, or a credential fixed mid-session. `bridge` is null+ // exactly when `mcpEnabled` is false, and a bypassed directory or a failed+ // health check never gets here: bypass means this directory does not touch+ // OpenViking at all. `connect()` re-handshakes only after a failure; after+ // a success it hands back the state it already has.+ if (bridge && wasStarted && connected && !bypassed && !closed && !toolsRegistered) {+ adoptBridgeTools(ctx, await bridge.connect(DEFAULT_HANDSHAKE_BUDGET_MS));+ updateStatus(ctx, connected, 0, sync.sessionId, config, takeover.state, toolsReady);+ }++ if (!connected || bypassed || closed) return;// Queue recall for the context hook. Pi renders the user message before// that hook, so recall latency does not delay the message appearing.@@ -158,7 +255,12 @@ export default async function (pi: ExtensionAPI) {if (!config.takeoverEnabled && archiveOverview && (compacted || archiveOverview.trim())) {parts.push(archiveOverview);}- parts.push("OpenViking tools: viking_search, viking_read, viking_browse, viking_remember, viking_forget, viking_add_resource, viking_archive_expand.");+ // Generated from what actually registered, so it can never name a tool the+ // server does not have. Omitted entirely when the handshake produced none,+ // which keeps the prefix free of a promise nothing can keep.+ if (toolNames.length) {+ parts.push(`OpenViking tools (use these for viking:// URIs): ${toolNames.join(", ")}.`);+ }const additions = parts.join("\n\n");if (!additions) return;@@ -240,7 +342,7 @@ export default async function (pi: ExtensionAPI) {const result = await sync.syncBranch(branch);logger.log("turn_end", { added: result.added, tokens: result.tokens });await takeover.onTurnSynced(result.tokens);- updateStatus(ctx, connected, result.added, sync.sessionId, config, takeover.state);+ updateStatus(ctx, connected, result.added, sync.sessionId, config, takeover.state, toolsReady);});// --- session_before_compact ---@@ -269,6 +371,19 @@ export default async function (pi: ExtensionAPI) {// --- session_shutdown ---pi.on("session_shutdown", async (_event, ctx) => {+ closed = true;+ if ((globalThis as any).__OPENVIKING_PI_EXTENSION__ === marker) {+ delete (globalThis as any).__OPENVIKING_PI_EXTENSION__;+ }+ // Release MCP requests without preventing the final REST commit.+ if (bridge) {+ try {+ await bridge.close();+ } catch (error) {+ logger.logError("session_shutdown", error);+ }+ }+if (!connected || bypassed) return;await sync.shutdown();@@ -321,7 +436,8 @@ export default async function (pi: ExtensionAPI) {? ` | takeover: ${t.coveredUserTurns}/${t.lastSeenUserTurns} turns archived, ~${t.pendingTokens} tokens pending`: "";ctx.ui.notify(- `OpenViking: ${connected ? "connected" : "disconnected"} | session: ${sid.slice(0, 12)}...${takeoverInfo}`,+ `OpenViking: ${connected ? "connected" : "disconnected"} | session: ${sid.slice(0, 12)}...`+ + `${takeoverInfo} | ${toolsStatusLine()}`,"info",);},@@ -374,6 +490,19 @@ async function fetchArchiveOverview(}}+/**+ * The extra line for a failed handshake that a root key explains.+ *+ * A root key authenticates fine and is then refused on `/mcp`, so the HTTP+ * status is the only clue, and without this the operator sees a 403 with no+ * way to act on it.+ */+function rootKeyHint(error: string | null): string {+ return error && /\b403\b/.test(error)+ ? "\nA root key cannot reach /mcp — use a user or admin key."+ : "";+}+function updateStatus(ctx: any,connected: boolean,@@ -381,6 +510,7 @@ function updateStatus(sessionId: string | null,config: OVConfig,takeoverState?: { pendingTokens?: number; coveredUserTurns?: number },+ toolsReady?: boolean,): void {const setter = ctx?.ui?.setStatus;if (typeof setter !== "function") return;@@ -390,7 +520,13 @@ function updateStatus(const pending = config.takeoverEnabled && takeoverState? ` · ctx ${takeoverState.coveredUserTurns ?? 0} · ~${takeoverState.pendingTokens ?? 0}/${threshold}`: ` · ✎ ${threshold}`;- const status = `${connected ? "OV ✓" : "OV ✗"} · ↩${added}${pending} · ${sessionId ? sessionId.slice(0, 12) : "none"}`;+ // Only worth a segment when tools were expected and are missing: `OV ✓` with+ // no tools is a working session whose OpenViking tools failed, and+ // `mcpEnabled: false` asked for that and is not a fault.+ const tools = connected && (config as any).mcpEnabled !== false && !toolsReady+ ? " · tools ✗"+ : "";+ const status = `${connected ? "OV ✓" : "OV ✗"}${tools} · ↩${added}${pending} · ${sessionId ? sessionId.slice(0, 12) : "none"}`;try {setter("openviking", status);} catch {diff --git a/examples/pi-coding-agent-extension/lib/mcp-bridge.d.mts b/examples/pi-coding-agent-extension/lib/mcp-bridge.d.mtsnew file mode 100644index 000000000..287de3020--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/mcp-bridge.d.mts@@ -0,0 +1,29 @@+import type { Tool } from "@modelcontextprotocol/client";++export const MCP_PROTOCOL_VERSION: "2025-06-18";+export const DEFAULT_TIMEOUT_MS: number;+export const DEFAULT_HANDSHAKE_BUDGET_MS: number;++export interface McpBridgeState {+ connected: boolean;+ closed: boolean;+ error: string | null;+ tools: Tool[];+}++export interface McpBridgeCallResult {+ content: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[];+ details: { tool: string; truncated: boolean };+}++export interface McpBridge {+ connect(budgetMs?: number): Promise<McpBridgeState>;+ callTool(name: string, args: Record<string, unknown>, options?: { signal?: AbortSignal }): Promise<McpBridgeCallResult>;+ close(): Promise<void>;+ readonly state: McpBridgeState;+}++export function createMcpBridge(options: {+ readConfig: () => any;+ clientInfo?: { name: string; version: string };+}): McpBridge;diff --git a/examples/pi-coding-agent-extension/lib/mcp-bridge.mjs b/examples/pi-coding-agent-extension/lib/mcp-bridge.mjsnew file mode 100644index 000000000..f242d313c--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/mcp-bridge.mjs@@ -0,0 +1,111 @@+/** Official MCP client with pi's connection lifecycle and result conversion. */+import { Client, ProtocolError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";+import { buildOvHeaders } from "../shared/ov-http.mjs";+import { toPiResult } from "./mcp-result.mjs";++export const MCP_PROTOCOL_VERSION = "2025-06-18";+export const DEFAULT_TIMEOUT_MS = 15000;+export const DEFAULT_HANDSHAKE_BUDGET_MS = 5000;++// connect() also sends an initialized notification, which has no SDK timeout.+function waitFor(promise, signal) {+ return new Promise((resolve, reject) => {+ const abort = () => reject(signal.reason);+ signal.addEventListener("abort", abort, { once: true });+ if (signal.aborted) abort();+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));+ });+}++const errorMessage = (error) => (error.status ? "HTTP " + error.status + ": " : "") + error.message;++export function createMcpBridge({ readConfig, clientInfo = { name: "openviking-pi", version: "0.0.0" } }) {+ const state = { connected: false, closed: false, error: null, tools: [] };+ let connection = null;++ function open(cfg, budgetMs) {+ if (state.closed) throw new Error("OpenViking MCP client is closed");+ const headers = buildOvHeaders(cfg, { actorPeerId: cfg.peerId, extraHeaders: cfg.extraHeaders });+ const key = JSON.stringify([cfg.mcpUrl, headers]);+ if (connection?.key === key) return connection;++ const previous = connection;+ connection = null;+ void previous?.client.close();+ state.connected = false;+ const client = new Client(clientInfo, { supportedProtocolVersions: [MCP_PROTOCOL_VERSION] });+ const transport = new StreamableHTTPClientTransport(new URL(cfg.mcpUrl), { requestInit: { headers } });+ const current = { key, client, ready: null };+ connection = current;+ client.onclose = () => {+ if (connection === current) {+ connection = null;+ state.connected = false;+ }+ };+ const signal = AbortSignal.timeout(budgetMs);+ current.ready = waitFor((async () => {+ await client.connect(transport, { signal, timeout: budgetMs });+ const listed = await client.listTools({}, { signal, timeout: budgetMs });+ if (connection !== current || state.closed) throw new Error("OpenViking MCP connection closed during startup");+ state.tools = listed.tools;+ state.connected = true;+ state.error = null;+ return client;+ })(), signal).catch(async (error) => {+ if (connection === current) {+ connection = null;+ state.connected = false;+ state.error = errorMessage(error);+ }+ await client.close();+ throw error;+ });+ return current;+ }++ async function connect(budgetMs = DEFAULT_HANDSHAKE_BUDGET_MS) {+ try {+ await open(readConfig(), budgetMs).ready;+ } catch (error) {+ // MCP failure must not prevent REST recall and session capture.+ if (!state.connected) state.error = errorMessage(error);+ }+ return state;+ }++ async function callTool(name, args, { signal } = {}) {+ signal?.throwIfAborted();+ const cfg = readConfig();+ const timeout = cfg.timeoutMs || DEFAULT_TIMEOUT_MS;+ const deadline = AbortSignal.timeout(timeout);+ const callSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;+ const current = open(cfg, Math.min(timeout, DEFAULT_HANDSHAKE_BUDGET_MS));+ let result;+ try {+ const client = await waitFor(current.ready, callSignal);+ result = await client.callTool({ name, arguments: args }, { signal: callSignal, timeout });+ } catch (error) {+ // Protocol/tool errors and user cancellation do not invalidate a connection.+ // A failed transport is replaced on the next invocation; never replay a call.+ if (!(error instanceof ProtocolError) && !signal?.aborted && connection === current) {+ connection = null;+ state.connected = false;+ state.error = errorMessage(error);+ await current.client.close();+ }+ throw error;+ }+ return toPiResult(name, result);+ }++ async function close() {+ state.closed = true;+ state.connected = false;+ const current = connection;+ connection = null;+ await current?.client.close();+ }++ return { connect, callTool, close, state };+}diff --git a/examples/pi-coding-agent-extension/lib/mcp-result.mjs b/examples/pi-coding-agent-extension/lib/mcp-result.mjsnew file mode 100644index 000000000..6beb99a7d--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/mcp-result.mjs@@ -0,0 +1,87 @@+/** MCP content adapted to pi's text/image tool results. */+export const MAX_RESULT_BYTES = 50 * 1024;+export const MAX_RESULT_LINES = 2000;+const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);++export function joinText(blocks) {+ return (Array.isArray(blocks) ? blocks : [])+ .filter((block) => block && block.type === "text")+ .map((block) => String(block.text ?? ""))+ .join("\n");+}++/**+ * An MCP `tools/call` result as pi content blocks.+ *+ * pi's content union is text or image; everything else becomes one readable+ * text line so the model still learns what came back.+ */+export function mcpContentToPi(result) {+ const blocks = Array.isArray(result?.content) ? result.content : [];+ const out = [];+ for (const block of blocks) {+ if (!isPlainObject(block)) continue;+ if (block.type === "text") {+ out.push({ type: "text", text: String(block.text ?? "") });+ } else if (block.type === "image") {+ out.push({+ type: "image",+ data: String(block.data ?? ""),+ mimeType: String(block.mimeType ?? block.mime_type ?? "image/png"),+ });+ } else if (block.type === "audio") {+ out.push({ type: "text", text: `[audio content omitted (${String(block.mimeType ?? "unknown type")})]` });+ } else if (block.type === "resource") {+ const resource = isPlainObject(block.resource) ? block.resource : {};+ const inline = typeof resource.text === "string" ? `\n${resource.text}` : "";+ const mime = resource.mimeType ? ` (${resource.mimeType})` : "";+ out.push({ type: "text", text: `[resource ${String(resource.uri ?? "?")}${mime}]${inline}` });+ } else if (block.type === "resource_link") {+ const label = block.name ? ` — ${block.name}` : "";+ out.push({ type: "text", text: `[resource link ${String(block.uri ?? "?")}${label}]` });+ } else {+ out.push({ type: "text", text: `[unsupported MCP content block: ${String(block.type ?? "?")}]` });+ }+ }++ // structuredContent is appended only when it says something the upstream text+ // does not. FastMCP echoes a {"result": "<the same text>"} beside the text+ // block for every tool annotated `-> str`, so the comparison must be against+ // the UPSTREAM text — never against the notes synthesised above for+ // image/audio/resource blocks, which would make every such echo look new.+ const structured = result?.structuredContent;+ if (isPlainObject(structured)) {+ const text = joinText(blocks).trim();+ const serialized = JSON.stringify(structured);+ const duplicate =+ (typeof structured.result === "string" && structured.result.trim() === text)+ || serialized.trim() === text;+ if (!duplicate && serialized) out.push({ type: "text", text: serialized });+ }++ if (out.length === 0) out.push({ type: "text", text: "" });+ return out;+}++/** All text blocks share one budget, including the truncation notice. */+export function toPiResult(tool, result) {+ const content = mcpContentToPi(result);+ const text = joinText(content);+ const truncated = Buffer.byteLength(text) > MAX_RESULT_BYTES || text.split("\n").length > MAX_RESULT_LINES;+ if (truncated) {+ const hint = "\n[OpenViking] Output truncated. Request fewer items or use a narrower URI, offset or limit.";+ const lines = text.split("\n").slice(0, MAX_RESULT_LINES - 1).join("\n");+ const buffer = Buffer.from(lines);+ let end = Math.min(buffer.length, MAX_RESULT_BYTES - Buffer.byteLength(hint));+ while (end > 0 && (buffer[end] & 0xc0) === 0x80) end--;+ // Consolidating text keeps the limit independent of MCP block boundaries.+ const shortened = buffer.subarray(0, end).toString("utf8") + hint;+ if (result.isError) throw new Error(shortened);+ return {+ content: [{ type: "text", text: shortened }, ...content.filter((block) => block.type === "image")],+ details: { tool, truncated: true },+ };+ }+ if (result.isError) throw new Error(text.trim() || "OpenViking " + tool + " failed");+ return { content, details: { tool, truncated: false } };+}diff --git a/examples/pi-coding-agent-extension/lib/takeover-core.mjs b/examples/pi-coding-agent-extension/lib/takeover-core.mjsindex 5b73dbd44..accd419fd 100644--- a/examples/pi-coding-agent-extension/lib/takeover-core.mjs+++ b/examples/pi-coding-agent-extension/lib/takeover-core.mjs@@ -145,7 +145,7 @@ export function buildOverviewMessage(overview, firstKeptTs = 0, budget = DEFAULTrole: "user",content:`${OVERVIEW_MARKER} Earlier conversation was archived to OpenViking and summarized below. ` +- `Use viking_search / viking_archive_expand for details.\n\n${body}`,+ `Use openviking_search for details.\n\n${body}`,timestamp,};}diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjsindex 91436b994..ac4f6b1de 100644--- a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs@@ -1,32 +1,63 @@-import { evaluateUriGuard, evaluateUriNotice } from "../shared/uri-guard.mjs";+import { evaluateUriGuard, evaluateUriNotice, normalizeToolName } from "../shared/uri-guard.mjs";+// pi's builtin file tools mapped to the OpenViking MCP tools the bridge+// registers. Every example is a valid call against the server's own schemas:+// `read` takes a `uris` array, `grep` takes a `uri` plus a `pattern` array,+// `glob` takes a pattern plus an optional `uri`, and `write`/`edit` address+// content by `uri`. Tools absent from this table are never guarded, so the+// openviking_* tools themselves need no allowlist.const VIKING_URI_TOOL_HINTS = {read: {- tool: "viking_read",- example: (uri) => `viking_read(uri="${uri}", level="overview")`,+ tool: "openviking_read",+ example: (uri) => `openviking_read(uris=["${uri}"])`,},grep: {- tool: "viking_search",- example: (uri, input = {}) => `viking_search(query="${String(input.pattern ?? "").replaceAll('"', '\\"')}", scope="${uri}")`,+ tool: "openviking_grep",+ example: (uri, input = {}) => `openviking_grep(uri="${uri}", pattern=["${String(input.pattern ?? "").replaceAll('"', '\\"')}"])`,},find: {- tool: "viking_browse",- example: (uri) => `viking_browse(action="list", uri="${uri}")`,+ tool: "openviking_glob",+ example: (uri) => `openviking_glob(uri="${uri}", pattern="**/*")`,},ls: {- tool: "viking_browse",- example: (uri) => `viking_browse(action="list", uri="${uri}")`,+ tool: "openviking_list",+ example: (uri) => `openviking_list(uri="${uri}")`,+ },+ write: {+ tool: "openviking_write",+ example: (uri) => `openviking_write(uri="${uri}", content="...")`,+ },+ edit: {+ tool: "openviking_edit",+ example: (uri) => `openviking_edit(uri="${uri}", old_string="...", new_string="...")`,},bash: {- tool: "viking_read or viking_search",- example: (uri) => `viking_read(uri="${uri}", level="overview")`,+ tool: "openviking_read or openviking_search",+ example: (uri) => `openviking_read(uris=["${uri}"])`,},};+// The only keys the guard may see for a given tool. pi's edit takes+// `{ path, edits: [{ oldText, newText }] }` (plus a legacy top-level+// oldText/newText pair), and those replacement-text keys are not in the shared+// guard's content-key allowlist. Handed the whole input, its generic sweep+// reads them as locations and blocks any edit whose new text merely mentions a+// viking:// URI — which fires the moment somebody edits this repo's own docs.+// Only `path` says where the edit lands, so only `path` gets through.+const GUARD_INPUT_KEYS_BY_TOOL = { edit: ["path"] };++function narrowGuardInput(toolName, input) {+ const keys = GUARD_INPUT_KEYS_BY_TOOL[normalizeToolName(toolName)];+ if (!keys) return input;+ if (!input || typeof input !== "object") return {};+ return Object.fromEntries(keys.filter((key) => input[key] !== undefined).map((key) => [key, input[key]]));+}+function readPiToolEvent(event) {+ const toolName = event?.toolName ?? event?.tool_name ?? event?.name;return {- toolName: event?.toolName ?? event?.tool_name ?? event?.name,- input: event?.input ?? event?.args ?? event?.params ?? {},+ toolName,+ input: narrowGuardInput(toolName, event?.input ?? event?.args ?? event?.params ?? {}),};}diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.jsonnew file mode 100644index 000000000..44220641f--- /dev/null+++ b/examples/pi-coding-agent-extension/package-lock.json@@ -0,0 +1,161 @@+{+ "name": "openviking-pi-extension",+ "version": "0.4.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "openviking-pi-extension",+ "version": "0.4.0",+ "dependencies": {+ "@modelcontextprotocol/client": "2.0.0"+ },+ "engines": {+ "node": ">=22.19.0"+ }+ },+ "node_modules/@modelcontextprotocol/client": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz",+ "integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==",+ "license": "MIT",+ "dependencies": {+ "@modelcontextprotocol/core": "2.0.0",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "jose": "^6.1.3",+ "pkce-challenge": "^5.0.0",+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@modelcontextprotocol/core": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz",+ "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",+ "license": "MIT",+ "dependencies": {+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.12",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",+ "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/zod": {+ "version": "4.6.5",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.jsonindex 476e97b1d..98caf3a20 100644--- a/examples/pi-coding-agent-extension/package.json+++ b/examples/pi-coding-agent-extension/package.json@@ -3,5 +3,11 @@"version": "0.4.0","description": "OpenViking memory and context extension for the pi coding agent","private": true,- "type": "module"+ "type": "module",+ "engines": {+ "node": ">=22.19.0"+ },+ "dependencies": {+ "@modelcontextprotocol/client": "2.0.0"+ }}diff --git a/examples/pi-coding-agent-extension/tests/fixtures/mcp-tools-list.json b/examples/pi-coding-agent-extension/tests/fixtures/mcp-tools-list.jsonnew file mode 100644index 000000000..3e7d0ee62--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/fixtures/mcp-tools-list.json@@ -0,0 +1,649 @@+{+ "_note": "Sample of the OpenViking MCP tools/list response, captured 2026-09-21 from a live openviking-server. It exists so the bridge tests can exercise real schema shapes. It is NOT the authoritative tool catalogue: the extension mirrors whatever the server returns at runtime and never ships a hard-coded list. Refresh it by re-running an MCP initialize + tools/list against a server whenever a test needs newer schemas.",+ "tools": [+ {+ "name": "find",+ "description": "Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score.",+ "inputSchema": {+ "properties": {+ "query": {+ "title": "Query",+ "type": "string"+ },+ "target_uri": {+ "default": "",+ "title": "Target Uri",+ "type": "string"+ },+ "limit": {+ "default": 10,+ "title": "Limit",+ "type": "integer"+ },+ "min_score": {+ "default": 0.35,+ "title": "Min Score",+ "type": "number"+ },+ "level": {+ "items": {+ "type": "integer"+ },+ "type": "array",+ "title": "Level"+ },+ "context_type": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Context Type"+ },+ "read_content": {+ "default": false,+ "title": "Read Content",+ "type": "boolean"+ }+ },+ "required": [+ "query"+ ],+ "title": "findArguments",+ "type": "object"+ }+ },+ {+ "name": "search",+ "description": "Deep semantic retrieval with optional session context and intent analysis.\n\n ``mode=\"list\"`` returns ranked memories, resources, and skills with URI,\n abstract, and score. ``mode=\"context\"`` returns an injection-ready,\n token-budgeted context block and supports category quotas, purpose presets,\n detail tiers, cross-turn deduplication, peer scoping, and optional rewriting.\n ``target_uri`` is only supported in list mode.\n ",+ "inputSchema": {+ "properties": {+ "query": {+ "title": "Query",+ "type": "string"+ },+ "target_uri": {+ "default": "",+ "title": "Target Uri",+ "type": "string"+ },+ "session_id": {+ "type": "string",+ "title": "Session Id"+ },+ "limit": {+ "default": 10,+ "title": "Limit",+ "type": "integer"+ },+ "min_score": {+ "type": "number",+ "title": "Min Score"+ },+ "level": {+ "items": {+ "type": "integer"+ },+ "type": "array",+ "title": "Level"+ },+ "context_type": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Context Type"+ },+ "mode": {+ "default": "list",+ "enum": [+ "list",+ "context"+ ],+ "title": "Mode",+ "type": "string"+ },+ "query_expansion": {+ "default": "auto",+ "enum": [+ "off",+ "auto"+ ],+ "title": "Query Expansion",+ "type": "string"+ },+ "max_tokens": {+ "default": 1600,+ "maximum": 32000,+ "minimum": 64,+ "title": "Max Tokens",+ "type": "integer"+ },+ "quotas": {+ "additionalProperties": {+ "type": "integer"+ },+ "type": "object",+ "title": "Quotas"+ },+ "purpose": {+ "enum": [+ "chat",+ "coding"+ ],+ "type": "string",+ "title": "Purpose"+ },+ "detail": {+ "default": "auto",+ "enum": [+ "auto",+ "abstract",+ "overview",+ "full"+ ],+ "title": "Detail",+ "type": "string"+ },+ "detail_by_category": {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object",+ "title": "Detail By Category"+ },+ "dedup_turns": {+ "default": 0,+ "maximum": 100,+ "minimum": 0,+ "title": "Dedup Turns",+ "type": "integer"+ },+ "exclude_uris": {+ "items": {+ "type": "string"+ },+ "maxItems": 200,+ "type": "array",+ "title": "Exclude Uris"+ },+ "peer_scope": {+ "default": "all",+ "enum": [+ "actor",+ "all"+ ],+ "title": "Peer Scope",+ "type": "string"+ },+ "other_peer_penalty": {+ "type": "number",+ "title": "Other Peer Penalty"+ },+ "other_peer_penalties": {+ "additionalProperties": {+ "type": "number"+ },+ "type": "object",+ "title": "Other Peer Penalties"+ },+ "rewrite": {+ "default": "off",+ "enum": [+ "off",+ "auto"+ ],+ "title": "Rewrite",+ "type": "string"+ },+ "rewrite_max_bullets": {+ "default": 6,+ "maximum": 20,+ "minimum": 1,+ "title": "Rewrite Max Bullets",+ "type": "integer"+ },+ "read_content": {+ "default": false,+ "title": "Read Content",+ "type": "boolean"+ }+ },+ "required": [+ "query"+ ],+ "title": "searchArguments",+ "type": "object"+ }+ },+ {+ "name": "read",+ "description": "Read one or more viking:// file URIs. Text reads accept line-based offset/limit. Raster images and supported audio return native MCP content blocks. For directory listing, use the list tool instead.",+ "inputSchema": {+ "properties": {+ "uris": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Uris"+ },+ "offset": {+ "default": 0,+ "title": "Offset",+ "type": "integer"+ },+ "limit": {+ "default": -1,+ "title": "Limit",+ "type": "integer"+ }+ },+ "required": [+ "uris"+ ],+ "title": "readArguments",+ "type": "object"+ }+ },+ {+ "name": "list",+ "description": "List one sorted page under a viking:// directory URI.\n\n Args:\n uri: Directory URI to list.\n recursive: Whether to recursively list descendants.\n offset: Number of visible entries to skip.\n limit: Optional maximum number of entries.\n sort_by: Optional name or modification-time ordering.\n sort_order: Ascending or descending order.\n\n Returns:\n A line-oriented directory listing.\n ",+ "inputSchema": {+ "properties": {+ "uri": {+ "title": "Uri",+ "type": "string"+ },+ "recursive": {+ "default": false,+ "title": "Recursive",+ "type": "boolean"+ },+ "offset": {+ "default": 0,+ "title": "Offset",+ "type": "integer"+ },+ "limit": {+ "type": "integer",+ "title": "Limit"+ },+ "sort_by": {+ "enum": [+ "name",+ "mtime"+ ],+ "type": "string",+ "title": "Sort By"+ },+ "sort_order": {+ "default": "asc",+ "enum": [+ "asc",+ "desc"+ ],+ "title": "Sort Order",+ "type": "string"+ }+ },+ "required": [+ "uri"+ ],+ "title": "lsArguments",+ "type": "object"+ }+ },+ {+ "name": "tree",+ "description": "Show one visible page from a recursive directory tree.\n\n Args:\n uri: Directory URI to traverse.\n level_limit: Maximum traversal depth.\n node_limit: Existing default result limit.\n include_abstract: Whether to include file summaries.\n offset: Number of visible nodes to skip.\n limit: Optional result limit that overrides node_limit.\n\n Returns:\n An indented directory tree.\n ",+ "inputSchema": {+ "properties": {+ "uri": {+ "default": "viking://",+ "title": "Uri",+ "type": "string"+ },+ "level_limit": {+ "default": 3,+ "title": "Level Limit",+ "type": "integer"+ },+ "node_limit": {+ "default": 1000,+ "title": "Node Limit",+ "type": "integer"+ },+ "include_abstract": {+ "default": false,+ "title": "Include Abstract",+ "type": "boolean"+ },+ "offset": {+ "default": 0,+ "title": "Offset",+ "type": "integer"+ },+ "limit": {+ "type": "integer",+ "title": "Limit"+ }+ },+ "title": "treeArguments",+ "type": "object"+ }+ },+ {+ "name": "remember",+ "description": "Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, or decisions worth persisting.",+ "inputSchema": {+ "properties": {+ "messages": {+ "items": {+ "properties": {+ "role": {+ "description": "Message role",+ "enum": [+ "user",+ "assistant"+ ],+ "title": "Role",+ "type": "string"+ },+ "content": {+ "description": "Message text content",+ "title": "Content",+ "type": "string"+ }+ },+ "required": [+ "role",+ "content"+ ],+ "title": "StoreMessage",+ "type": "object"+ },+ "title": "Messages",+ "type": "array"+ }+ },+ "required": [+ "messages"+ ],+ "title": "rememberArguments",+ "type": "object"+ }+ },+ {+ "name": "write",+ "description": "Write text to a viking:// file. Use this to save files (notes, profiles, knowledge, state) in OpenViking the same way you would use a working directory. To change part of an existing file, prefer the edit tool over a full rewrite.\n\n - mode=\"replace\" (default): overwrite the file; creates it and any missing parent directories if needed.\n - mode=\"create\": fail if the file already exists.\n - Any new file (whether created by \"replace\" or \"create\") must end in one of: .md .txt .json .yaml .yml .toml .py .js .ts\n - mode=\"append\": append to the end of an existing file; fails if the file does not exist.\n\n Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. The viking://~ home alias expands to the caller's user root. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change.",+ "inputSchema": {+ "properties": {+ "uri": {+ "title": "Uri",+ "type": "string"+ },+ "content": {+ "title": "Content",+ "type": "string"+ },+ "mode": {+ "default": "replace",+ "enum": [+ "replace",+ "append",+ "create"+ ],+ "title": "Mode",+ "type": "string"+ },+ "wait": {+ "default": false,+ "title": "Wait",+ "type": "boolean"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout"+ }+ },+ "required": [+ "uri",+ "content"+ ],+ "title": "writeArguments",+ "type": "object"+ }+ },+ {+ "name": "edit",+ "description": "Replace an exact string with new text in an existing viking:// file. Use this for targeted changes instead of rewriting the whole file with the write tool. old_string must match the file's current content exactly, including indentation and newlines; use the read tool first to see it. The edit fails and the file is left unchanged if old_string is not found, or if it matches more than once and replace_all is false (pass more surrounding context to make it unique, or set replace_all=true to replace every occurrence). Pass new_string=\"\" to delete old_string.\n\n Editing a memory file preserves its metadata; after an edit, search indexes refresh in the background (pass wait=true to block until search reflects the change).",+ "inputSchema": {+ "properties": {+ "uri": {+ "title": "Uri",+ "type": "string"+ },+ "old_string": {+ "title": "Old String",+ "type": "string"+ },+ "new_string": {+ "title": "New String",+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "title": "Replace All",+ "type": "boolean"+ },+ "wait": {+ "default": false,+ "title": "Wait",+ "type": "boolean"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout"+ }+ },+ "required": [+ "uri",+ "old_string",+ "new_string"+ ],+ "title": "editArguments",+ "type": "object"+ }+ },+ {+ "name": "add_resource",+ "description": "Add a resource to OpenViking. Asynchronous — processing happens in the background.\n\n Remote URL: pass ``path`` as an http(s)://, git@, ssh://, or git:// URL. A sitemap /\n RSS / Atom URL ingests the WHOLE site as one resource tree; pass ``args={\"site\": true}``\n to force whole-site ingestion from a bare domain.\n\n Local file: pass ``path`` as a filesystem path (e.g. ``/tmp/foo.pdf``). The response is an\n upload instruction — HTTP POST the file to the returned URL and the server ingests it\n automatically; you do NOT need to call this tool again.\n\n Args:\n path: Remote URL or local filesystem path. Required unless ``temp_file_id`` is set.\n temp_file_id: Server-minted upload id from a prior signed local-file upload.\n add_type: Explicit Connector source type (e.g. \"tos\", \"git\"). When set, the\n request routes through the Connector integration (must be enabled\n server-side) and ``path`` is sent verbatim — never treated as a local\n file. Requires an exact ``to`` target and cannot be combined with\n ``temp_file_id`` or ``parent``. Leave empty for the default path-probing\n behavior.\n description: Optional human-readable reason for adding the resource.\n watch_interval: Auto-refresh cadence in minutes. 0 = no watch. Prefer >=1440 (24h)\n unless the source changes faster — every refresh re-embeds the whole resource.\n Only applies to remote-URL invocations.\n processing_mode: \"semantic_and_vectors\" for normal semantic processing, or\n \"vectors_only\" to skip semantic understanding and only build vector indexes.\n to: Exact final URI including the leaf name (e.g.\n \"viking://resources/volcengine/OpenViking\"). Written verbatim; an existing\n target is synced to match the new source, so visible entries it does not\n contain are deleted. Required when ``add_type`` is set.\n parent: Existing directory to store the resource under, for remote or\n local-file imports; the leaf name comes from the source. Never overwrites\n — a collision reserves the next free name (\"name_1\", \"name_2\", ...) and\n returns a warning. Mutually exclusive with ``to``; not supported when\n ``add_type`` is set. Leaving both empty derives the directory and the name\n from the source and handles collisions like ``parent``.\n tags: Optional explicit k=v retrieval tags to apply after ingestion.\n tag_mode: Tag update mode, \"replace\" or \"append\". Defaults to \"replace\".\n args: Parser-specific options, e.g. {\"auth_config\": {\"token\": \"...\"}}\n for native HTTPS Git imports and watches, {\"feishu_access_token\": \"...\"}\n for Feishu imports, {\"site\": true} for whole-site ingestion, or\n {\"parse_mode\": \"no_split\"} to keep each parsed document body in one file.\n ",+ "inputSchema": {+ "properties": {+ "path": {+ "default": "",+ "title": "Path",+ "type": "string"+ },+ "temp_file_id": {+ "default": "",+ "title": "Temp File Id",+ "type": "string"+ },+ "add_type": {+ "default": "",+ "title": "Add Type",+ "type": "string"+ },+ "description": {+ "default": "",+ "title": "Description",+ "type": "string"+ },+ "watch_interval": {+ "default": 0,+ "title": "Watch Interval",+ "type": "number"+ },+ "processing_mode": {+ "default": "semantic_and_vectors",+ "enum": [+ "semantic_and_vectors",+ "vectors_only"+ ],+ "title": "Processing Mode",+ "type": "string"+ },+ "to": {+ "default": "",+ "title": "To",+ "type": "string"+ },+ "parent": {+ "default": "",+ "title": "Parent",+ "type": "string"+ },+ "tags": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Tags"+ },+ "tag_mode": {+ "default": "replace",+ "title": "Tag Mode",+ "type": "string"+ },+ "args": {+ "additionalProperties": true,+ "type": "object",+ "title": "Args"+ }+ },+ "title": "add_resourceArguments",+ "type": "object"+ }+ },+ {+ "name": "list_watches",+ "description": "List watch tasks (auto-refresh subscriptions) visible to the current user.",+ "inputSchema": {+ "properties": {},+ "title": "list_watchesArguments",+ "type": "object"+ }+ },+ {+ "name": "cancel_watch",+ "description": "Cancel a watch task by its target URI (e.g. \"viking://resources/volcengine/OpenViking\").",+ "inputSchema": {+ "properties": {+ "to_uri": {+ "title": "To Uri",+ "type": "string"+ }+ },+ "required": [+ "to_uri"+ ],+ "title": "cancel_watchArguments",+ "type": "object"+ }+ },+ {+ "name": "grep",+ "description": "Search content in viking:// files using regex patterns (like grep). Supports multiple patterns searched concurrently. Use this for exact text matching; use the search tool for semantic retrieval.",+ "inputSchema": {+ "properties": {+ "uri": {+ "title": "Uri",+ "type": "string"+ },+ "pattern": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Pattern"+ },+ "case_insensitive": {+ "default": false,+ "title": "Case Insensitive",+ "type": "boolean"+ },+ "node_limit": {+ "default": 10,+ "title": "Node Limit",+ "type": "integer"+ }+ },+ "required": [+ "uri",+ "pattern"+ ],+ "title": "grepArguments",+ "type": "object"+ }+ },+ {+ "name": "glob",+ "description": "Find viking:// files matching a glob pattern (e.g. **/*.md, *.py). Use this for filename matching; use the search tool for content-based retrieval.",+ "inputSchema": {+ "properties": {+ "pattern": {+ "title": "Pattern",+ "type": "string"+ },+ "uri": {+ "default": "viking://",+ "title": "Uri",+ "type": "string"+ },+ "node_limit": {+ "default": 100,+ "title": "Node Limit",+ "type": "integer"+ }+ },+ "required": [+ "pattern"+ ],+ "title": "globArguments",+ "type": "object"+ }+ },+ {+ "name": "forget",+ "description": "Permanently delete a viking:// URI from OpenViking. Irreversible — confirm with user before calling.",+ "inputSchema": {+ "properties": {+ "uri": {+ "title": "Uri",+ "type": "string"+ },+ "recursive": {+ "default": false,+ "title": "Recursive",+ "type": "boolean"+ }+ },+ "required": [+ "uri"+ ],+ "title": "forgetArguments",+ "type": "object"+ }+ },+ {+ "name": "health",+ "description": "Check whether the OpenViking server is healthy.",+ "inputSchema": {+ "properties": {},+ "title": "healthArguments",+ "type": "object"+ }+ }+ ]+}diff --git a/examples/pi-coding-agent-extension/tests/handshake-once.test.mjs b/examples/pi-coding-agent-extension/tests/handshake-once.test.mjsnew file mode 100644index 000000000..60a6fd6ea--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/handshake-once.test.mjs@@ -0,0 +1,262 @@+/** Exercise the extension lifecycle with REST available and MCP refused. */++import test from "node:test";+import assert from "node:assert/strict";+import { registerHooks } from "node:module";+import { createServer } from "node:http";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const EXTENSION_DIR = dirname(dirname(fileURLToPath(import.meta.url)));+const EXTENSION_URL = pathToFileURL(EXTENSION_DIR + "/").href;++// Only the extension's own relative `.js` specifiers are touched, and only+// after the real resolution has already failed, so nothing else in the process+// can change meaning because this file ran.+registerHooks({+ resolve(specifier, context, nextResolve) {+ const inExtension = typeof context?.parentURL === "string"+ && context.parentURL.startsWith(EXTENSION_URL);+ if (!inExtension || !specifier.startsWith(".") || !specifier.endsWith(".js")) {+ return nextResolve(specifier, context);+ }+ try {+ return nextResolve(specifier, context);+ } catch {+ return nextResolve(specifier.slice(0, -3) + ".ts", context);+ }+ },+});++const MANAGED_ENV = [+ "OPENVIKING_CREDENTIAL_SOURCE",+ "OPENVIKING_CLI_CONFIG_FILE",+ "OPENVIKING_CONFIG_FILE",+ "OPENVIKING_URL",+ "OPENVIKING_BASE_URL",+ "OPENVIKING_MCP_URL",+ "OPENVIKING_API_KEY",+ "OPENVIKING_BEARER_TOKEN",+ "OPENVIKING_ACCOUNT",+ "OPENVIKING_USER",+ "OPENVIKING_AUTH_MODE",+ "OPENVIKING_PEER_ID",+ "OPENVIKING_DEBUG",+ "OPENVIKING_DEBUG_LOG",+ "OV_DEBUG_LOG",+ "OPENVIKING_PENDING_DIR",+];++async function startServer() {+ const initializes = [];+ const gate = { health: null };+ const server = createServer((req, res) => {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", async () => {+ const path = (req.url || "").split("?")[0];+ if (path === "/mcp") {+ let method = null;+ try {+ method = JSON.parse(Buffer.concat(chunks).toString("utf8"))?.method ?? null;+ } catch {+ // A malformed body is still a post worth ignoring, not a crash.+ }+ if (method === "initialize") initializes.push(Date.now());+ res.writeHead(403, { "content-type": "application/json" });+ res.end(JSON.stringify({ detail: "root key cannot reach /mcp" }));+ return;+ }+ if (path === "/health") await gate.health;+ // Everything the REST half touches during startup: /health, the profile+ // fetch, recall. An empty result keeps each of them a no-op.+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ status: "ok", result: {} }));+ });+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const { port } = server.address();+ return {+ url: `http://127.0.0.1:${port}`,+ initializes,+ gate,+ close: () => new Promise((resolve) => server.close(resolve)),+ };+}++/** The slice of pi's API `index.ts` reaches for. */+function fakePi() {+ const handlers = new Map();+ const tools = [];+ return {+ pi: {+ on(event, handler) { handlers.set(event, handler); },+ registerTool(tool) { tools.push(tool?.name); },+ registerCommand() {},+ appendEntry() {},+ getAllTools() { return []; },+ sendMessage() {},+ },+ handlers,+ tools,+ };+}++function fakeCtx(notified = [], statuses = []) {+ return {+ sessionManager: {+ getSessionId: () => "pi-session-handshake",+ getBranch: () => [],+ getLeafId: () => "entry-1",+ },+ ui: {+ notify: (...args) => notified.push(args),+ setStatus: (...args) => statuses.push(args),+ },+ getContextUsage: () => ({ tokens: 0, contextWindow: 262144, percent: 0 }),+ };+}++/** Boot one extension instance against a throwaway config and a fake server. */+async function withExtension(t, fn) {+ const server = await startServer();+ const dir = await mkdtemp(join(tmpdir(), "ov-pi-handshake-"));+ const saved = Object.fromEntries(MANAGED_ENV.map((name) => [name, process.env[name]]));+ for (const name of MANAGED_ENV) delete process.env[name];+ process.env.OPENVIKING_CREDENTIAL_SOURCE = "env";+ process.env.OPENVIKING_URL = server.url;+ process.env.OPENVIKING_API_KEY = "pi-handshake-key";+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf");+ process.env.OPENVIKING_CONFIG_FILE = join(dir, "ov.conf");+ process.env.OPENVIKING_PENDING_DIR = join(dir, "pending");+ await writeFile(join(dir, "ovcli.conf"), JSON.stringify({ plugin: { pi: {} } }), "utf8");++ t.after(async () => {+ for (const [name, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ await server.close();+ await rm(dir, { recursive: true, force: true });+ });++ // Dynamic, so the resolve hook above is already installed. The module is+ // evaluated once per process; each call to its default export builds a fresh+ // extension instance with its own bridge and its own session state.+ const mod = await import(join(EXTENSION_DIR, "index.ts"));+ assert.equal(typeof mod.default, "function");++ const { pi, handlers, tools } = fakePi();+ await mod.default(pi);+ const notified = [];+ const statuses = [];+ return fn({+ server,+ handlers,+ tools,+ notified,+ statuses,+ ctx: fakeCtx(notified, statuses),+ configPath: join(dir, "ovcli.conf"),+ turn: (prompt) => handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt, systemPrompt: "BASE" },+ fakeCtx(notified, statuses),+ ),+ shutdown: () => handlers.get("session_shutdown")(+ { type: "session_shutdown", reason: "reload" },+ fakeCtx(notified, statuses),+ ),+ });+}++test("the first turn attempts the handshake once, and the retry waits for the next one", async (t) => {+ await withExtension(t, async ({ server, turn, shutdown, notified }) => {+ await turn("hello");+ assert.equal(+ server.initializes.length,+ 1,+ "turn one must not re-attempt the handshake start() already joined",+ );++ await turn("again");+ assert.equal(+ server.initializes.length,+ 2,+ "turn two is the retry branch doing its job on a toolless session",+ );++ await turn("and again");+ assert.equal(server.initializes.length, 3, "and it keeps retrying while there are no tools");++ // The failure is announced once, not once per attempt.+ const warnings = notified.filter(([message]) => /no tools this session/.test(message));+ assert.equal(warnings.length, 1, JSON.stringify(notified));+ assert.match(warnings[0][0], /403/);++ await shutdown();+ });+});++test("a refused handshake still leaves the session working", async (t) => {+ await withExtension(t, async ({ turn, tools, statuses, shutdown }) => {+ const result = await turn("hello");+ // No tools registered, but the session is live: the system prompt still+ // comes back (or at worst undefined), and the status line flags the gap.+ assert.deepEqual(tools, []);+ if (result) assert.ok(!/OpenViking tools/.test(result.systemPrompt));+ assert.ok(+ statuses.some(([, status]) => /OV ✓/.test(status) && /tools ✗/.test(status)),+ JSON.stringify(statuses),+ );+ await shutdown();+ });+});++test("reload clears only the owning extension's coexistence marker", async (t) => {+ await withExtension(t, async ({ turn, shutdown }) => {+ await turn("hello");+ assert.ok(globalThis.__OPENVIKING_PI_EXTENSION__);+ await shutdown();+ assert.equal(globalThis.__OPENVIKING_PI_EXTENSION__, undefined);+ });+ await withExtension(t, async ({ turn, shutdown }) => {+ await turn("hello");+ const replacement = { dir: "another-instance" };+ globalThis.__OPENVIKING_PI_EXTENSION__ = replacement;+ await shutdown();+ assert.equal(globalThis.__OPENVIKING_PI_EXTENSION__, replacement);+ delete globalThis.__OPENVIKING_PI_EXTENSION__;+ });+});++test("shutdown during health check cannot restore the marker or register tools", async (t) => {+ await withExtension(t, async ({ server, turn, shutdown, tools }) => {+ let release;+ server.gate.health = new Promise((resolve) => { release = resolve; });+ const starting = turn("hello");+ await shutdown();+ release();+ await starting;+ assert.equal(globalThis.__OPENVIKING_PI_EXTENSION__, undefined);+ assert.deepEqual(tools, []);+ assert.equal(server.initializes.length, 0);+ });+});++for (const plugin of [{ mcpEnabled: false }, { bypassSession: true }]) {+ test("MCP stays off for " + JSON.stringify(plugin), async (t) => {+ await withExtension(t, async ({ server, turn, shutdown, configPath }) => {+ // The instance loads configuration at construction, so reload it first.+ await shutdown();+ await writeFile(configPath, JSON.stringify({ plugin: { pi: plugin } }));+ const { default: extension } = await import(join(EXTENSION_DIR, "index.ts"));+ const { pi, handlers } = fakePi();+ await extension(pi);+ await handlers.get("before_agent_start")({ prompt: "hello", systemPrompt: "BASE" }, fakeCtx());+ assert.equal(server.initializes.length, 0);+ await handlers.get("session_shutdown")({}, fakeCtx());+ });+ });+}diff --git a/examples/pi-coding-agent-extension/tests/mcp-bridge-config.test.mjs b/examples/pi-coding-agent-extension/tests/mcp-bridge-config.test.mjsnew file mode 100644index 000000000..be46b4d44--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/mcp-bridge-config.test.mjs@@ -0,0 +1,207 @@+/** MCP and REST share the resolved server, credentials and actor peer. */++import test from "node:test";+import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";++import { loadConfig, buildBridgeProxyConfig } from "../config.ts";+import { OVClient } from "../client.ts";+import { toMcpProxyConfig } from "../shared/mcp-proxy-config.mjs";++const MANAGED_ENV = [+ "OPENVIKING_CREDENTIAL_SOURCE",+ "OPENVIKING_CLI_CONFIG_FILE",+ "OPENVIKING_CONFIG_FILE",+ "OPENVIKING_URL",+ "OPENVIKING_BASE_URL",+ "OPENVIKING_MCP_URL",+ "OPENVIKING_API_KEY",+ "OPENVIKING_BEARER_TOKEN",+ "OPENVIKING_ACCOUNT",+ "OPENVIKING_USER",+ "OPENVIKING_AUTH_MODE",+ "OPENVIKING_PEER_ID",+ "OPENVIKING_WORKSPACE_PEER",+ "OPENVIKING_RECALL_PEER_SCOPE",+ "OPENVIKING_DEBUG",+ "OPENVIKING_DEBUG_LOG",+ "OV_DEBUG_LOG",+ "OPENVIKING_TIMEOUT_MS",+ "OPENVIKING_EXTRA_HEADERS",+];++/**+ * Run `fn` with one freshly loaded configuration.+ *+ * `env` overrides the baseline (an env-pinned credential chain against a local+ * server); `plugin` becomes the `plugin.pi` section of a throwaway ovcli.conf.+ */+async function withConfig({ env = {}, plugin = {} } = {}, fn) {+ const dir = await mkdtemp(join(tmpdir(), "ov-pi-bridge-config-"));+ const saved = Object.fromEntries(MANAGED_ENV.map((name) => [name, process.env[name]]));+ for (const name of MANAGED_ENV) delete process.env[name];+ process.env.OPENVIKING_CREDENTIAL_SOURCE = "env";+ process.env.OPENVIKING_URL = "http://127.0.0.1:1933";+ process.env.OPENVIKING_API_KEY = "pi-parity-key";+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf");+ process.env.OPENVIKING_CONFIG_FILE = join(dir, "ov.conf");+ for (const [name, value] of Object.entries(env)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }++ try {+ await writeFile(join(dir, "ovcli.conf"), JSON.stringify({ plugin: { pi: plugin } }), "utf8");+ return await fn(loadConfig());+ } finally {+ for (const [name, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ await rm(dir, { recursive: true, force: true });+ }+}++/**+ * What `OVClient` sends for one request, as the server would see it.+ *+ * `health()` is the first call `start()` makes and the one every session makes,+ * so it is the honest sample of the REST side of the connection.+ */+async function restRequest(cfg) {+ const originalFetch = globalThis.fetch;+ const seen = [];+ globalThis.fetch = async (url, init = {}) => {+ seen.push({ url: String(url), headers: { ...(init.headers || {}) } });+ return new Response(JSON.stringify({ status: "ok", result: {} }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ };+ try {+ assert.equal(await new OVClient(cfg).health(), true);+ } finally {+ globalThis.fetch = originalFetch;+ }+ assert.equal(seen.length, 1);+ return { ...seen[0], baseUrl: seen[0].url.replace(/\/health$/, "") };+}++// ---------------------------------------------------------------------------+// Server+// ---------------------------------------------------------------------------++test("the bridge's MCP URL is the REST client's base URL plus /mcp", async () => {+ // The trailing slash is the interesting part: the REST client trims it and+ // `buildMcpProxyConfig` trims it again, so neither side can end up with a+ // doubled separator that a strict reverse proxy would 404.+ await withConfig({ env: { OPENVIKING_URL: "http://127.0.0.1:1933/" } }, async (cfg) => {+ const rest = await restRequest(cfg);+ const bridge = buildBridgeProxyConfig(cfg);++ assert.equal(rest.url, "http://127.0.0.1:1933/health");+ assert.equal(bridge.mcpUrl, `${rest.baseUrl}/mcp`);+ assert.equal(bridge.mcpUrl, "http://127.0.0.1:1933/mcp");+ });+});++test("an explicitly pinned MCP URL is the one the bridge uses", async () => {+ // `OPENVIKING_MCP_URL` exists for deployments whose MCP endpoint does not sit+ // under the REST base (a gateway path, a separate host). The bridge has to+ // honour the URL the shared chain resolved rather than deriving its own, or+ // that pin would work for every other harness and silently not for pi.+ await withConfig({+ env: { OPENVIKING_MCP_URL: "http://127.0.0.1:1933/gateway/mcp" },+ }, async (cfg) => {+ const rest = await restRequest(cfg);+ const bridge = buildBridgeProxyConfig(cfg);++ assert.equal(cfg.mcpUrl, "http://127.0.0.1:1933/gateway/mcp");+ assert.equal(bridge.mcpUrl, cfg.mcpUrl);+ assert.equal(rest.baseUrl, "http://127.0.0.1:1933", "the REST base URL is untouched by the pin");+ });+});++// ---------------------------------------------------------------------------+// Credentials and identity+// ---------------------------------------------------------------------------++test("the bridge carries the same key, account and user as the REST client", async () => {+ await withConfig({+ env: {+ OPENVIKING_API_KEY: "pi-parity-key",+ OPENVIKING_ACCOUNT: "acct-parity",+ OPENVIKING_USER: "user-parity",+ },+ }, async (cfg) => {+ const rest = await restRequest(cfg);+ const bridge = buildBridgeProxyConfig(cfg);++ assert.equal(bridge.apiKey, "pi-parity-key");+ assert.equal(rest.headers.Authorization, `Bearer ${bridge.apiKey}`);++ // An account and a user with no auth mode named means a trusted server, so+ // both surfaces name the operator.+ assert.equal(cfg.sendIdentityHeaders, true);+ assert.equal(bridge.sendIdentityHeaders, cfg.sendIdentityHeaders);+ assert.equal(bridge.account, "acct-parity");+ assert.equal(bridge.user, "user-parity");+ assert.equal(rest.headers["X-OpenViking-Account"], bridge.account);+ assert.equal(rest.headers["X-OpenViking-User"], bridge.user);+ });+});++test("an api_key server keeps the operator's identity off both wires", async () => {+ // The key already carries the identity there, and the headers are ignored;+ // sending them anyway would name the operator to every proxy on the path. The+ // bridge has to inherit that decision instead of re-deciding it.+ await withConfig({+ env: {+ OPENVIKING_ACCOUNT: "acct-parity",+ OPENVIKING_USER: "user-parity",+ OPENVIKING_AUTH_MODE: "api_key",+ },+ }, async (cfg) => {+ const rest = await restRequest(cfg);+ const bridge = buildBridgeProxyConfig(cfg);++ assert.equal(cfg.sendIdentityHeaders, false);+ assert.equal(bridge.sendIdentityHeaders, false);+ // Shared header construction omits identity on api_key deployments.+ assert.equal(bridge.account, "acct-parity");+ assert.equal(bridge.user, "user-parity");+ const sent = Object.values(rest.headers);+ assert.ok(!sent.includes("acct-parity"), "the account stays off the REST request");+ assert.ok(!sent.includes("user-parity"), "so does the user");+ });+});++// ---------------------------------------------------------------------------+// Peer+// ---------------------------------------------------------------------------++test("the peer the REST client resolves is the MCP actor peer", async () => {+ await withConfig({+ env: { OPENVIKING_RECALL_PEER_SCOPE: "all" },+ plugin: { peerId: "pi-parity-peer" },+ }, async (cfg) => {+ const rest = await restRequest(cfg);+ const bridge = buildBridgeProxyConfig(cfg);++ assert.equal(cfg.peerId, "pi-parity-peer");+ assert.equal(bridge.peerId, cfg.peerId);+ assert.ok(+ Object.values(rest.headers).includes(cfg.peerId),+ "the REST client already sends this peer on every request",+ );++ // Why `buildBridgeProxyConfig` passes the peer explicitly: the shared+ // default is written for a long-lived stdio proxy, which cannot trust its+ // launch directory and therefore sends a peer only under `actor` recall+ // scope. Taking that default here would widen the tools' default search to+ // every peer under the user while recall stays narrowed to this one.+ assert.equal(toMcpProxyConfig(cfg).peerId, "", "the stdio default drops it");+ });+});diff --git a/examples/pi-coding-agent-extension/tests/mcp-bridge.test.mjs b/examples/pi-coding-agent-extension/tests/mcp-bridge.test.mjsnew file mode 100644index 000000000..8fd0882f6--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/mcp-bridge.test.mjs@@ -0,0 +1,204 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { setTimeout as delay } from "node:timers/promises";+import { createMcpBridge, MCP_PROTOCOL_VERSION } from "../lib/mcp-bridge.mjs";+import { toPiResult, MAX_RESULT_BYTES, MAX_RESULT_LINES } from "../lib/mcp-result.mjs";++// Real SDK over HTTP: only the server response is controlled by each scenario.+async function fixture(t, handle = () => {}) {+ const requests = [];+ const server = createServer(async (req, res) => {+ if (req.method !== "POST") { res.writeHead(405).end(); return; }+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ const message = JSON.parse(Buffer.concat(chunks));+ requests.push({ ...message, headers: req.headers });+ if (await handle(message, res)) return;+ if (message.id === undefined) { res.writeHead(202).end(); return; }+ const result = message.method === "initialize"+ ? { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } }+ : message.method === "tools/list"+ ? { tools: [{ name: "echo", description: "Echo", inputSchema: { type: "object" } }] }+ : { content: [{ type: "text", text: JSON.stringify(message.params.arguments) }] };+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const cfg = { mcpUrl: "http://127.0.0.1:" + server.address().port + "/mcp", timeoutMs: 1000,+ apiKey: "key", sendIdentityHeaders: true, account: "acct", user: "user", peerId: "peer" };+ const bridge = createMcpBridge({ readConfig: () => cfg });+ t.after(async () => {+ await bridge.close();+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ });+ return { bridge, cfg, requests, count: (method) => requests.filter((r) => r.method === method).length };+}++test("shares initialization, sends resolved headers, and pairs concurrent calls", async (t) => {+ const { bridge, requests, count } = await fixture(t);+ const states = await Promise.all(Array.from({ length: 10 }, () => bridge.connect()));+ assert.ok(states.every((s) => s.connected));+ assert.equal(count("initialize"), 1);+ assert.equal(count("tools/list"), 1);+ const results = await Promise.all(Array.from({ length: 20 }, (_, i) => bridge.callTool("echo", { i })));+ assert.deepEqual(results.map((r) => JSON.parse(r.content[0].text).i), Array.from({ length: 20 }, (_, i) => i));+ for (const req of requests) {+ assert.equal(req.headers.authorization, "Bearer key");+ assert.equal(req.headers["x-openviking-account"], "acct");+ assert.equal(req.headers["x-openviking-user"], "user");+ assert.equal(req.headers["x-openviking-actor-peer"], "peer");+ }+ assert.equal(requests[0].params.protocolVersion, MCP_PROTOCOL_VERSION);+});++for (const status of [401, 403, 404, 500]) {+ test("HTTP " + status + " fails once; the next call reconnects", async (t) => {+ let fail = true;+ const { bridge, count } = await fixture(t, (message, res) => {+ if (message.method === "tools/call" && fail) { fail = false; res.writeHead(status).end("rejected"); return true; }+ });+ await bridge.connect();+ await assert.rejects(bridge.callTool("echo", {}), /rejected/);+ assert.equal(count("tools/call"), 1);+ assert.equal(bridge.state.connected, false);+ await bridge.callTool("echo", {});+ assert.equal(count("initialize"), 2);+ assert.equal(count("tools/call"), 2);+ });+}++test("credential, identity and URL changes are picked up before the next call", async (t) => {+ const { bridge, cfg, requests, count } = await fixture(t);+ await bridge.connect();+ Object.assign(cfg, { apiKey: "rotated", sendIdentityHeaders: false, peerId: "next", mcpUrl: cfg.mcpUrl + "?updated=1" });+ await bridge.callTool("echo", {});+ assert.equal(count("initialize"), 2);+ const headers = requests.at(-1).headers;+ assert.equal(headers.authorization, "Bearer rotated");+ assert.equal(headers["x-openviking-account"], undefined);+ assert.equal(headers["x-openviking-user"], undefined);+ assert.equal(headers["x-openviking-actor-peer"], "next");+});++for (const stage of ["initialize", "notifications/initialized", "tools/list"]) {+ test("one handshake budget covers " + stage + " and a fresh instance can recover", async (t) => {+ let hang = true;+ const { bridge, count } = await fixture(t, (message) => hang && message.method === stage);+ const start = performance.now();+ assert.equal((await bridge.connect(70)).connected, false);+ assert.ok(performance.now() - start < 500);+ hang = false;+ assert.equal((await bridge.connect()).connected, true);+ assert.equal(count("initialize"), 2);+ });+}++test("tool budget includes connection time and never replays a timed out write", async (t) => {+ const { bridge, cfg, count } = await fixture(t, async (message) => {+ if (message.method === "initialize") await delay(80);+ if (message.method === "tools/call") await delay(300);+ });+ cfg.timeoutMs = 180;+ const start = performance.now();+ await assert.rejects(bridge.callTool("echo", { value: 1 }));+ assert.ok(performance.now() - start < 330);+ assert.equal(count("tools/call"), 1);+});++test("cancelling one tool leaves another concurrent call usable", async (t) => {+ const { bridge, count } = await fixture(t, (message) => message.method === "tools/call" && message.params.arguments.hang);+ await bridge.connect();+ const controller = new AbortController();+ const pending = bridge.callTool("echo", { hang: true }, { signal: controller.signal });+ const rejected = assert.rejects(pending);+ await delay(20);+ controller.abort();+ await rejected;+ assert.equal((await bridge.callTool("echo", { ok: true })).content[0].text, '{"ok":true}');+ assert.equal(count("initialize"), 1);+});++test("business errors do not reconnect", async (t) => {+ const { bridge, count } = await fixture(t, (message, res) => {+ if (message.method !== "tools/call") return;+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { isError: true, content: [{ type: "text", text: "invalid URI" }] } }));+ return true;+ });+ await assert.rejects(bridge.callTool("echo", {}), /invalid URI/);+ await assert.rejects(bridge.callTool("echo", {}), /invalid URI/);+ assert.equal(count("initialize"), 1);+});++test("closing during startup never publishes a connection", async (t) => {+ const { bridge } = await fixture(t, async (message) => { if (message.method === "initialize") await delay(60); });+ const pending = bridge.connect();+ await delay(10);+ await bridge.close();+ await pending;+ assert.equal(bridge.state.connected, false);+ assert.equal(bridge.state.closed, true);+ await assert.rejects(bridge.callTool("echo", {}), /closed/);+});++test("result conversion preserves images, avoids structured echoes, and bounds all text together", () => {+ const image = { type: "image", data: "aGVsbG8=", mimeType: "image/png" };+ assert.deepEqual(toPiResult("read", { content: [{ type: "text", text: "hello" }, image], structuredContent: { result: "hello" } }).content,+ [{ type: "text", text: "hello" }, image]);+ for (const text of ["字".repeat(12000), "line\n".repeat(1100), " ".repeat(30000)]) {+ const result = toPiResult("read", { content: [{ type: "text", text }, image, { type: "text", text }] });+ const output = result.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");+ assert.equal(result.details.truncated, true);+ assert.ok(Buffer.byteLength(output) <= MAX_RESULT_BYTES);+ assert.ok(output.split("\n").length <= MAX_RESULT_LINES);+ assert.ok(!output.includes("\ufffd"));+ assert.match(output, /Output truncated/);+ assert.ok(result.content.includes(image) || result.content.some((b) => b.type === "image"));+ }+});++test("large tool errors are bounded and non-text content remains readable", () => {+ assert.throws(() => toPiResult("read", { isError: true, content: [{ type: "text", text: "error".repeat(20000) }] }),+ (error) => Buffer.byteLength(error.message) <= MAX_RESULT_BYTES && error.message.includes("Output truncated"));+ const result = toPiResult("read", { content: [+ { type: "audio", data: "AAAA", mimeType: "audio/wav" },+ { type: "resource", resource: { uri: "resource-uri", text: "inline body" } },+ { type: "resource_link", uri: "linked-uri", name: "attachment" },+ ], structuredContent: { count: 3 } });+ const text = result.content.map((block) => block.text).join("\n");+ assert.match(text, /audio content omitted/);+ assert.match(text, /inline body/);+ assert.match(text, /linked-uri/);+ assert.match(text, /"count":3/);+});++test("an old in-flight call cannot invalidate the replacement connection", async (t) => {+ let received;+ const waiting = new Promise((resolve) => { received = resolve; });+ const { bridge, cfg, count } = await fixture(t, (message) => {+ if (message.method === "tools/call" && message.params.arguments.old) { received(); return true; }+ });+ await bridge.connect();+ const old = assert.rejects(bridge.callTool("echo", { old: true }));+ await waiting;+ cfg.apiKey = "replacement";+ await bridge.callTool("echo", { next: true });+ await old;+ await bridge.callTool("echo", { last: true });+ assert.equal(bridge.state.connected, true);+ assert.equal(count("initialize"), 2);+});++test("JSON-RPC argument errors fail the tool without reconnecting", async (t) => {+ const { bridge, count } = await fixture(t, (message, res) => {+ if (message.method !== "tools/call") return;+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32602, message: "bad argument" } }));+ return true;+ });+ await assert.rejects(bridge.callTool("echo", {}), /bad argument/);+ await assert.rejects(bridge.callTool("echo", {}), /bad argument/);+ assert.equal(count("initialize"), 1);+});diff --git a/examples/pi-coding-agent-extension/tests/mcp-tools.test.mjs b/examples/pi-coding-agent-extension/tests/mcp-tools.test.mjsnew file mode 100644index 000000000..67c5fc2d5--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/mcp-tools.test.mjs@@ -0,0 +1,69 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { registerMcpTools } from "../tools.ts";++const { tools } = JSON.parse(readFileSync(new URL("fixtures/mcp-tools-list.json", import.meta.url)));+function register(descriptors = tools) {+ const definitions = new Map();+ const calls = [];+ const names = registerMcpTools({ registerTool: (tool) => definitions.set(tool.name, tool) }, {+ state: { tools: descriptors },+ callTool: async (...args) => { calls.push(args); return { content: [] }; },+ });+ return { definitions, names, calls };+}++test("registers the server catalogue with its schemas and descriptions", () => {+ const { definitions, names } = register();+ assert.deepEqual(names, tools.map((tool) => "openviking_" + tool.name));+ for (const tool of tools) {+ const definition = definitions.get("openviking_" + tool.name);+ assert.deepEqual(definition.parameters, tool.inputSchema);+ assert.equal(definition.description, tool.description.trim());+ assert.equal(definition.promptSnippet, undefined);+ assert.equal(definition.promptGuidelines, undefined);+ }+ const added = register([{ name: "future_tool", inputSchema: { type: "object" } }]);+ assert.deepEqual(added.names, ["openviking_future_tool"]);+});++test("validates original arguments before pi can coerce them", () => {+ const { definitions } = register();+ for (const [tool, args] of [+ ["write", { uri: "viking://user/u/memories/a.md", content: "hello", mode: null }],+ ["remember", { messages: { role: "user", content: "hello" } }],+ ["remember", { messages: '[{"role":"user","content":"hello"}]' }],+ ["find", { query: "hello", level: "1" }],+ ["read", { uris: "viking://user/u/memories/a.md" }],+ ]) {+ const before = structuredClone(args);+ assert.throws(() => definitions.get("openviking_" + tool).prepareArguments(args), /Invalid arguments/);+ assert.deepEqual(args, before);+ }+});++test("preserves valid arguments and forwards the bare tool name and cancellation", async () => {+ const { definitions, calls } = register();+ const tool = definitions.get("openviking_read");+ const args = { uris: ["viking://user/u/memories/a.md"], offset: 0, limit: 20 };+ const before = structuredClone(args);+ assert.equal(tool.prepareArguments(args), args);+ assert.deepEqual(args, before);+ const { signal } = new AbortController();+ await tool.execute("call-1", args, signal);+ assert.deepEqual(calls, [["read", args, { signal }]]);+});++test("enforces additionalProperties and required fields without adding defaults", () => {+ const { definitions } = register([{ name: "example", inputSchema: {+ type: "object", required: ["value"], additionalProperties: false,+ properties: { value: { type: "integer" }, mode: { type: "string", default: "replace" } },+ } }]);+ const tool = definitions.get("openviking_example");+ assert.throws(() => tool.prepareArguments({}), /Invalid arguments/);+ assert.throws(() => tool.prepareArguments({ value: 1, extra: 2 }), /Invalid arguments/);+ const args = { value: 1 };+ tool.prepareArguments(args);+ assert.deepEqual(args, { value: 1 });+});diff --git a/examples/pi-coding-agent-extension/tests/takeover-core.test.mjs b/examples/pi-coding-agent-extension/tests/takeover-core.test.mjsindex a09630ed3..9eadeebd7 100644--- a/examples/pi-coding-agent-extension/tests/takeover-core.test.mjs+++ b/examples/pi-coding-agent-extension/tests/takeover-core.test.mjs@@ -134,6 +134,12 @@ test("buildOverviewMessage is byte-stable for the same inputs", () => {assert.match(a.content, /\[OpenViking Session Context\]/);});+test("buildOverviewMessage points the model at the openviking_search tool", () => {+ const message = buildOverviewMessage("summary", 1, 1000);+ assert.match(message.content, /Use openviking_search for details\./);+ assert.doesNotMatch(message.content, /viking_archive_expand/);+});+test("countUndeliveredForSession only counts addMessage for the same session", () => {const pending = [{ entry: { type: "addMessage", sessionId: "a" } },diff --git a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjsindex e45c82573..450a3371e 100644--- a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs+++ b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs@@ -11,7 +11,8 @@ test("pi URI guard blocks builtin file tools on viking URIs", () => {assert.equal(decision?.block, true)assert.match(decision?.reason ?? "", /viking:\/\/ URIs are OpenViking virtual paths/)- assert.match(decision?.reason ?? "", /Use viking_read instead/)+ assert.match(decision?.reason ?? "", /Use openviking_read instead/)+ assert.match(decision?.reason ?? "", /openviking_read\(uris=\["viking:\/\/resources\/project\/file\.md"\]\)/)})test("pi URI guard lets bash commands containing viking URI run", () => {@@ -26,10 +27,62 @@ test("pi URI guard lets bash commands containing viking URI run", () => {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: "openviking_read", input: { uris: ["viking://resources/file.md"] } }), null)assert.equal(guardVikingUriToolCall({ toolName: "grep", input: { pattern: "viking://", path: "/repo" } }), null)})+test("pi URI guard blocks an edit on a viking path but not one that merely mentions a URI", () => {+ const decision = guardVikingUriToolCall({+ type: "tool_call",+ toolName: "edit",+ input: {+ path: "viking://memories/project/notes.md",+ edits: [{ oldText: "old", newText: "new" }],+ },+ })++ assert.equal(decision?.block, true)+ assert.match(decision?.reason ?? "", /Use openviking_edit instead/)+ assert.match(+ decision?.reason ?? "",+ /openviking_edit\(uri="viking:\/\/memories\/project\/notes\.md", old_string="\.\.\.", new_string="\.\.\."\)/,+ )++ // Editing a local file whose replacement text carries a viking:// URI — what+ // happens whenever somebody edits this repo's own docs. pi's edits[] keys are+ // not in the shared guard's content-key allowlist, so the adapter narrows the+ // input to { path } before the guard sees it.+ assert.equal(+ guardVikingUriToolCall({+ toolName: "edit",+ input: {+ path: "/repo/docs/agent-integrations/11-pi.md",+ edits: [{ oldText: "see the docs", newText: "read viking://memories/project/notes.md instead" }],+ },+ }),+ null,+ )+ // Same edit in pi's legacy top-level spelling.+ assert.equal(+ guardVikingUriToolCall({+ toolName: "edit",+ input: { path: "/repo/docs/README.md", oldText: "see the docs", newText: "viking://memories/project/notes.md" },+ }),+ null,+ )+})++test("pi URI guard blocks a write to a viking path but not a local write that mentions one", () => {+ assert.equal(+ guardVikingUriToolCall({ toolName: "write", input: { path: "viking://memories/a.md", content: "x" } })?.block,+ true,+ )+ assert.equal(+ guardVikingUriToolCall({ toolName: "write", input: { path: "/tmp/a.md", content: "viking://memories/a.md" } }),+ 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({@@ -45,8 +98,8 @@ test("pi URI guard appends a notice to bash results whose command carried a vikiassert.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, /use openviking_read or openviking_search instead/)+ assert.match(result.content[1].text, /openviking_read\(uris=\["viking:\/\/resources\/project\/file\.md"\]\)/)assert.match(result.content[1].text, /ignore this notice\.$/)assert.equal(original.length, 1)})@@ -55,5 +108,5 @@ 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)+ assert.equal(noticeVikingUriToolResult({ toolName: "openviking_read", input: { uris: ["viking://resources/file.md"] }, content }), null)})diff --git a/examples/pi-coding-agent-extension/tools.ts b/examples/pi-coding-agent-extension/tools.tsindex b806269ac..fe94f80c4 100644--- a/examples/pi-coding-agent-extension/tools.ts+++ b/examples/pi-coding-agent-extension/tools.ts@@ -1,252 +1,29 @@-import { Type } from "typebox";-import { StringEnum } from "@earendil-works/pi-ai";-import type { OVClient } from "./client.js";-import type { SyncManager } from "./sync.js";--export function registerTools(pi: any, client: OVClient, sync?: SyncManager): void {-- // --- viking_search ---- pi.registerTool({- name: "viking_search",- label: "Viking Search",- description: "Semantic search over the OpenViking knowledge base. Returns ranked results with viking:// URIs and abstracts. Use to recall past decisions, user preferences, or project-specific knowledge not in current context.",- promptSnippet: "Search OpenViking for past decisions, preferences, and project knowledge",- promptGuidelines: [- "Use viking_search when you need information from previous sessions not in MEMORY.md.",- "Use viking_search before making decisions that might conflict with past decisions.",- ],- parameters: Type.Object({- query: Type.String({ description: "Search query" }),- scope: Type.Optional(Type.String({ description: "Viking URI prefix to scope search (e.g., 'viking://~/memories/')" })),- limit: Type.Optional(Type.Number({ description: "Max results (default: 10)" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- const results = await client.find(params.query, {- targetUri: params.scope,- topK: params.limit ?? 10,- });- if (results.length === 0) {- return { content: [{ type: "text", text: "No results found." }] };- }- const maxChars = client.cfg.recallMaxContentChars;- const lines = results.map(r => {- const abs = r.abstract.length > maxChars- ? r.abstract.slice(0, maxChars) + "..."- : r.abstract;- return `[${r.score.toFixed(2)}] ${r.uri}\n ${abs}`; }- );- return {- content: [{ type: "text", text: lines.join("\n\n") }],- details: { results },- };- },- });-- // --- viking_read ---- pi.registerTool({- name: "viking_read",- label: "Viking Read",- description: "Read content at a viking:// URI. Three detail levels: 'abstract' (~100 tokens), 'overview' (~2k tokens), 'full' (complete). Start with abstract, escalate when needed.",- promptSnippet: "Read OpenViking content at a viking:// URI with tiered detail levels",- parameters: Type.Object({- uri: Type.String({ description: "viking:// URI to read" }),- level: StringEnum(["abstract", "overview", "full"] as const),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- let content: string | null = null;- switch (params.level) {- case "abstract": content = await client.abstract(params.uri); break;- case "overview": content = await client.overview(params.uri); break;- case "full": content = await client.readContent(params.uri); break;- }- if (!content) {- return { content: [{ type: "text", text: `No content at ${params.uri}` }] };- }- return { content: [{ type: "text", text: content }] };- },- });-- // --- viking_browse ---- pi.registerTool({- name: "viking_browse",- label: "Viking Browse",- description: "Browse the OpenViking knowledge store like a filesystem. List directory contents or get metadata.",- promptSnippet: "Browse the viking:// directory tree in OpenViking",- parameters: Type.Object({- action: StringEnum(["list", "stat"] as const),- uri: Type.Optional(Type.String({ description: "viking:// URI (default: 'viking://')" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- const uri = params.uri ?? "viking://";- if (params.action === "stat") {- const info = await client.stat(uri);- if (!info) return { content: [{ type: "text", text: `Not found: ${uri}` }] };- return { content: [{ type: "text", text: JSON.stringify(info, null, 2) }] };- }- // list- const entries = await client.ls(uri);- if (entries.length === 0) {- return { content: [{ type: "text", text: `Empty directory: ${uri}` }] };- }- const lines = entries.map(e => `${e.isDir ? "📁" : "📄"} ${e.name}`);- return { content: [{ type: "text", text: lines.join("\n") }] };- },- });-- // --- viking_remember ---- pi.registerTool({- name: "viking_remember",- label: "Viking Remember",- description: "Store a fact or memory in OpenViking. Stored as a session message and extracted into long-term memory on commit. Use for important information the agent should remember: preferences, decisions, gotchas, lessons learned.",- promptSnippet: "Store a fact in OpenViking for cross-session persistence",- promptGuidelines: [- "Use viking_remember for facts that should survive across sessions but don't belong in MEMORY.md.",- "Good for: user preferences, architectural decisions, gotchas, environment details.",- ],- parameters: Type.Object({- content: Type.String({ description: "The fact or observation to store" }),- category: Type.Optional(Type.String({ description: "Category hint: 'preference', 'entity', 'event', 'case', 'pattern'" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- // Store as a tagged message directly in OV — the extractor picks up [Remember — ...] prefix- const category = params.category ?? "general";- const tagged = `[Remember — ${category}] ${params.content}`;-- // Directly add to OV session if available- let stored = false;- if (sync?.sessionId) {- stored = await client.addMessage(sync.sessionId, "user", tagged);- }-- return {- content: [{ type: "text", text: stored ? `Remembered in OpenViking: "${params.content}" (${category})` : `Queued for OpenViking: "${params.content}" (${category})` }],- details: { stored, category, tagged },- };- },- });-- // --- viking_forget ---- pi.registerTool({- name: "viking_forget",- label: "Viking Forget",- description: "Delete a memory by URI, or search for a specific memory and remove it. Use to correct outdated or wrong information.",- promptSnippet: "Delete a memory from OpenViking by URI or query",- parameters: Type.Object({- uri: Type.Optional(Type.String({ description: "Exact viking:// URI to delete" })),- query: Type.Optional(Type.String({ description: "Search query — deletes the strongest match if score > 0.8" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- if (params.uri) {- const ok = await client.delete(params.uri);- return {- content: [{ type: "text", text: ok ? `Deleted: ${params.uri}` : `Failed to delete: ${params.uri}` }],- };- }- if (params.query) {- const results = await client.find(params.query, { topK: 1 });- if (results.length > 0 && results[0].score > 0.8) {- const ok = await client.delete(results[0].uri);- return {- content: [{ type: "text", text: ok ? `Deleted: ${results[0].uri}` : `Failed: ${results[0].uri}` }],- };- }- return { content: [{ type: "text", text: "No strong match found (score > 0.8 required)." }] };- }- return { content: [{ type: "text", text: "Provide either 'uri' or 'query'." }] };- },- });-- // --- viking_add_resource ---- pi.registerTool({- name: "viking_add_resource",- label: "Viking Add Resource",- description: "Ingest a URL into OpenViking. The page is auto-processed into L0/L1/L2 tiers and indexed for semantic search. HTTP only — local file paths are not supported by the OV server.",- promptSnippet: "Ingest a URL into OpenViking for indexed retrieval",- parameters: Type.Object({- url: Type.String({ description: "URL to ingest (HTTP only, no file paths)" }),- reason: Type.Optional(Type.String({ description: "Why this resource is relevant (improves indexing)" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- const result = await client.addResource(params.url);- if (!result) {- return { content: [{ type: "text", text: `Failed to ingest: ${params.url}` }] };- }- return {- content: [{ type: "text", text: `Ingested: ${result.root_uri}` }],- details: result,- };- },- });-- // --- viking_archive_expand ---- pi.registerTool({- name: "viking_archive_expand",- label: "Viking Archive Expand",- description: "Expand an archived session back into raw messages. Use when the archive summary is too coarse and you need detailed conversation history.",- promptSnippet: "Expand an archived session to see raw conversation messages",- parameters: Type.Object({- archive_id: Type.Optional(Type.String({ description: "Archive ID to expand" })),- session_id: Type.Optional(Type.String({ description: "OV session ID to expand" })),- }),- async execute(- _id: string, params: any, _signal: AbortSignal,- _onUpdate: any, _ctx: any,- ) {- if (!client.connected) {- return { content: [{ type: "text", text: "OpenViking server is not reachable." }] };- }- const sid = params.session_id ?? params.archive_id;- if (!sid) {- return { content: [{ type: "text", text: "Provide session_id or archive_id." }] };- }- // Read the session's overview — sessions are at viking://session/{sid}- const uri = `viking://session/${sid}`;- const content = await client.overview(uri);- if (!content) {- // Try reading the history subdirectory- const history = await client.overview(`${uri}/history`);- if (!history) {- return { content: [{ type: "text", text: `Archive not found: ${sid}` }] };- }- return { content: [{ type: "text", text: history }] };- }- return { content: [{ type: "text", text: content }] };- },+/** Register the server's tool catalogue once per pi session. */+import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";+import type { McpBridge } from "./lib/mcp-bridge.mjs";++export const TOOL_NAME_PREFIX = "openviking_";++export function registerMcpTools(pi: any, bridge: McpBridge): string[] {+ const validator = new AjvJsonSchemaValidator();+ return bridge.state.tools.map((tool) => {+ const name = TOOL_NAME_PREFIX + tool.name;+ const validate = validator.getValidator(tool.inputSchema);+ pi.registerTool({+ name,+ label: "OpenViking " + tool.name,+ description: tool.description?.trim() || tool.title || "OpenViking " + tool.name,+ parameters: tool.inputSchema,+ // Validate before pi coerces values or drops optional null properties.+ prepareArguments(args: unknown) {+ const result = validate(args);+ if (!result.valid) throw new Error("Invalid arguments for " + name + ": " + result.errorMessage);+ return args;+ },+ async execute(_toolCallId: string, params: Record<string, unknown>, signal?: AbortSignal) {+ return bridge.callTool(tool.name, params, { signal });+ },+ });+ return name;});}diff --git a/examples/pi-experimental-context-management/index.ts b/examples/pi-experimental-context-management/index.tsindex 47b7e931d..e28c17630 100644--- a/examples/pi-experimental-context-management/index.ts+++ b/examples/pi-experimental-context-management/index.ts@@ -11,10 +11,16 @@* newest user message.** Do not load this together with the openviking extension — they would both- * register `viking_*` tools and both sync the same OV session. As a backstop- * this one stands down as soon as it sees a `viking_search` registered from- * another extension's directory, which is re-checked on every event boundary- * because that extension registers its tools only after a network round trip.+ * register overlapping tools and both sync the same OV session. As a backstop+ * this one stands down as soon as it sees the peer, by either of two signals:+ * a search tool registered from another extension's directory (`viking_search`+ * before 0.4, `openviking_search` from 0.4 on), or the+ * `globalThis.__OPENVIKING_PI_EXTENSION__` marker the peer sets once it is+ * connected and not bypassed. The marker is what covers the dangerous case:+ * when `/mcp` answers 401/403 or the handshake times out the peer registers no+ * tool at all and still writes the OV session, so no tool name is there to see.+ * Both signals are re-checked on every event boundary because the peer arrives+ * only after a network round trip.*/import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import { dirname } from "node:path";@@ -36,8 +42,18 @@ import {STATUS_CUSTOM_TYPE,} from "./lib/context-window-core.mjs";-/** The tool whose presence means the non-experimental extension is loaded. */-const COEXISTENCE_PROBE_TOOL = "viking_search";+/**+ * Tools whose presence may mean the non-experimental extension is loaded.+ * It registers `openviking_search` from 0.4 on and `viking_search` before that,+ * and a pre-0.4 build may still be installed, so both names count.+ */+const COEXISTENCE_PROBE_TOOLS = new Set(["viking_search", "openviking_search"]);++/** The probe name this extension registers itself (see `tools.ts`). */+const OWN_PROBE_TOOL = "viking_search";++/** Set by the non-experimental extension once it is connected and not bypassed. */+const PEER_GLOBAL_MARKER = "__OPENVIKING_PI_EXTENSION__";/*** Static system-prompt guidance (plan §5). Identical for the whole session, so@@ -146,25 +162,39 @@ export default async function (pi: ExtensionAPI) {const ownDir = dirname(fileURLToPath(import.meta.url));/**- * True when a *different* extension owns `viking_search`.+ * True when the non-experimental extension is present.*- * A one-shot probe at startup cannot work: the other extension registers its- * tools only after an awaited health check, so at the moment our own start()- * begins the tool is provably not there yet. So the probe compares the- * registering extension's `sourceInfo.path` with ours and is re-run on every- * event boundary — pi's tool registry is keyed by name, so once the peer- * registers, `viking_search` carries its path and not ours.+ * A one-shot probe at startup cannot work: the other extension arrives only+ * after an awaited health check, so at the moment our own start() begins+ * there is provably nothing to see. Hence this is re-run on every event+ * boundary, and it looks at two independent signals.+ *+ * The global marker comes first because it is the only one that survives a+ * failed handshake: with `/mcp` answering 401/403 the peer registers no tool+ * and still syncs the OV session, which is precisely when double-writing+ * hurts. This extension never sets the marker, so seeing it means the peer.+ *+ * Otherwise compare the registering extension's `sourceInfo.path` with ours.+ * pi's tool registry is keyed by name, so once the peer registers, its search+ * tool carries its path and not ours.*/const peerOwnsToolSurface = (): boolean => {try {+ if ((globalThis as any)[PEER_GLOBAL_MARKER]) return true;const tools = (pi as any).getAllTools?.();if (!Array.isArray(tools)) return false;for (const tool of tools) {- if (tool?.name !== COEXISTENCE_PROBE_TOOL) continue;+ const name = String(tool?.name ?? "");+ if (!COEXISTENCE_PROBE_TOOLS.has(name)) continue;const path = String(tool?.sourceInfo?.path ?? tool?.sourceInfo?.baseDir ?? "");- // No sourceInfo (an older pi, or a synthetic tool): fall back to "any- // viking_search we did not register ourselves is a peer's".- if (!path) return !toolsRegistered;+ if (!path) {+ // No sourceInfo (an older pi, or a synthetic tool). A name this+ // extension never registers can only be the peer's; for our own name+ // fall back to "one we did not register ourselves is a peer's".+ if (name !== OWN_PROBE_TOOL || !toolsRegistered) return true;+ // Ours, so keep scanning — a peer's tool may come later in the list.+ continue;+ }if (path !== ownDir && !path.startsWith(ownDir + "/")) return true;}return false;diff --git a/examples/pi-experimental-context-management/tests/coexistence-contract.test.mjs b/examples/pi-experimental-context-management/tests/coexistence-contract.test.mjsnew file mode 100644index 000000000..0f67134d3--- /dev/null+++ b/examples/pi-experimental-context-management/tests/coexistence-contract.test.mjs@@ -0,0 +1,230 @@+/**+ * The coexistence contract between this fork and the non-experimental+ * extension, pinned at the text level.+ *+ * The two pi extensions must never drive the same OpenViking session: both+ * would capture every message and both would race on the same commit. This+ * fork therefore stands down as soon as it detects the peer, on two signals —+ * a search tool registered from another extension's directory, and the+ * `globalThis.__OPENVIKING_PI_EXTENSION__` marker the peer sets once its+ * health check passes. The marker is the signal that matters: on a `/mcp`+ * 401/403 the peer registers zero tools and still writes the session, so no+ * tool name is there to see.+ *+ * The behaviour of both signals is covered by the runtime tests in+ * `index-load.test.mjs`, but those load `index.ts` through the jiti pi bundles+ * and skip themselves when they cannot find it — which is exactly what happens+ * on CI, where pi is not installed (that file then reports every coexistence+ * case as SKIPPED and exits green). So on CI nothing today notices if one side+ * renames the marker or the probe set loses a tool name.+ *+ * This file closes that hole by reading the two `index.ts` files and the peer's+ * `tools.ts` as TEXT and asserting the literals they must agree on. Reading+ * source rather than running it is deliberate: the contract is a constant+ * shared across two extensions that are never loaded in the same process here,+ * and a text assertion is the only form of it that runs without jiti. It is a+ * stand-in for the runtime tests, not a replacement — keep both.+ */++import test from "node:test";+import assert from "node:assert/strict";+import { existsSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const EXTENSION_DIR = dirname(dirname(fileURLToPath(import.meta.url)));+const FORK_INDEX = join(EXTENSION_DIR, "index.ts");++/**+ * The non-experimental extension, as a sibling of this one in the repository.+ *+ * An installed copy of this fork ships alone, so the peer's sources are simply+ * absent there; the assertions that need them skip instead of failing. In the+ * repository — and therefore on CI, which is where this file has to bite —+ * both directories are always present.+ */+const PEER_DIR = join(dirname(EXTENSION_DIR), "pi-coding-agent-extension");+const PEER_INDEX = join(PEER_DIR, "index.ts");+const PEER_TOOLS = join(PEER_DIR, "tools.ts");+const NO_PEER_SOURCES =+ existsSync(PEER_INDEX) && existsSync(PEER_TOOLS)+ ? false+ : `the peer extension is not beside this one (${PEER_DIR}); an installed copy ships alone`;++function source(file) {+ return readFileSync(file, "utf-8");+}++/** The names in `COEXISTENCE_PROBE_TOOLS`, in source order. */+function probeToolNames(text) {+ const match = /COEXISTENCE_PROBE_TOOLS\s*=\s*new Set\(\s*\[([\s\S]*?)\]\s*\)/.exec(text);+ assert.ok(+ match,+ "index.ts no longer declares COEXISTENCE_PROBE_TOOLS as a set literal. It is the list of " ++ "tool names that mean the non-experimental extension is loaded; if it moved, move this " ++ "assertion with it rather than deleting it.",+ );+ return [...match[1].matchAll(/["'`]([^"'`]+)["'`]/g)].map((entry) => entry[1]);+}++/** The string `PEER_GLOBAL_MARKER` is bound to. */+function peerMarkerName(text) {+ const match = /PEER_GLOBAL_MARKER\s*=\s*["'`]([^"'`]+)["'`]/.exec(text);+ assert.ok(+ match,+ "index.ts no longer declares PEER_GLOBAL_MARKER as a string literal. That constant is the " ++ "globalThis key the peer sets; it has to stay readable from here so this test can check " ++ "that the peer still writes the same key.",+ );+ return match[1];+}++/**+ * The body of `peerOwnsToolSurface()`.+ *+ * Bounded on purpose: an assertion about what the probe reads must not be+ * satisfied by an unrelated mention elsewhere in a 650-line file.+ */+function peerProbeBody(text) {+ const start = text.indexOf("const peerOwnsToolSurface");+ assert.notEqual(+ start,+ -1,+ "index.ts no longer defines peerOwnsToolSurface(). That function is how this fork notices " ++ "the other OpenViking extension and stands down; without it both extensions sync the same " ++ "OpenViking session.",+ );+ const end = text.indexOf("\n };", start);+ return end === -1 ? text.slice(start, start + 4000) : text.slice(start, end);+}++// ---------------------------------------------------------------------------+// Signal 1: the peer's search tool, under both the old and the new name+// ---------------------------------------------------------------------------++test("the probe set names the peer's search tool under both its old and its current name", () => {+ const fork = source(FORK_INDEX);+ const names = probeToolNames(fork);++ assert.ok(+ names.includes("viking_search"),+ "COEXISTENCE_PROBE_TOOLS dropped `viking_search`. The peer registered that name before 0.4 " ++ "and such a build may still be installed; without it in the probe set this fork does not " ++ "see an old peer and both extensions capture every message into the same OpenViking " ++ "session.",+ );+ assert.ok(+ names.includes("openviking_search"),+ "COEXISTENCE_PROBE_TOOLS dropped `openviking_search`. That is what the peer registers from " ++ "0.4 on (tools.ts prefixes the server's MCP tool names with `openviking_`); without it in " ++ "the probe set the current peer is invisible to the tool-name signal and two writers race " ++ "on one session commit.",+ );++ assert.match(+ peerProbeBody(fork),+ /COEXISTENCE_PROBE_TOOLS/,+ "peerOwnsToolSurface() no longer consults COEXISTENCE_PROBE_TOOLS, so the probe set has no " ++ "effect: a peer that only announces itself through its tools would go unnoticed.",+ );+});++// ---------------------------------------------------------------------------+// Signal 2: the globalThis marker — the one that survives a 403+// ---------------------------------------------------------------------------++test("the fork reads the peer's globalThis marker, not only its tool names", () => {+ const fork = source(FORK_INDEX);++ assert.equal(+ peerMarkerName(fork),+ "__OPENVIKING_PI_EXTENSION__",+ "PEER_GLOBAL_MARKER no longer matches the key the peer writes " ++ "(`globalThis.__OPENVIKING_PI_EXTENSION__` in pi-coding-agent-extension/index.ts). Both " ++ "sides have to spell it identically; a rename on either side silently disables the only " ++ "coexistence signal that works when the peer has no tools.",+ );++ const body = peerProbeBody(fork);+ assert.match(+ body,+ /PEER_GLOBAL_MARKER|__OPENVIKING_PI_EXTENSION__/,+ "peerOwnsToolSurface() no longer looks at the peer's globalThis marker. Tool names alone are " ++ "not enough: when `/mcp` answers 401/403 the peer registers ZERO tools and still writes the " ++ "OpenViking session, and the marker is the only thing left to see it by.",+ );+});++test("the peer still writes the globalThis marker this fork probes for", {+ skip: NO_PEER_SOURCES,+}, () => {+ const marker = peerMarkerName(source(FORK_INDEX));+ const peer = source(PEER_INDEX);++ assert.ok(+ peer.includes(marker),+ `pi-coding-agent-extension/index.ts no longer mentions \`${marker}\`, the marker this fork ` ++ "reads to decide whether the peer is active. If the peer stops announcing itself, this " ++ "fork keeps running beside it and both sync the same OpenViking session.",+ );++ const assignment = new RegExp(`${marker}(?:["'\`]?\\s*\\])?\\s*=\\s*[^=]`);+ assert.match(+ peer,+ assignment,+ `pi-coding-agent-extension/index.ts mentions \`${marker}\` but never assigns it. The marker ` ++ "is only useful as a write: the peer has to set it once its health check passes, before " ++ "any tool is registered, because a failed MCP handshake leaves it with no tools at all.",+ );++ const markerLine = peer.split("\n").find((line) => line.includes(marker) && line.includes("="));+ assert.match(+ markerLine ?? "",+ /globalThis/,+ `pi-coding-agent-extension/index.ts sets \`${marker}\` somewhere other than globalThis. This ` ++ "fork reads it off globalThis — the two extensions share a process but not a module graph, " ++ "so a module-scoped marker never reaches the reader.",+ );+});++// ---------------------------------------------------------------------------+// The peer's tool surface is really `openviking_`-prefixed+// ---------------------------------------------------------------------------++test("the peer's registered tool names carry the prefix the probe set expects", {+ skip: NO_PEER_SOURCES,+}, () => {+ const tools = source(PEER_TOOLS);+ const match = /TOOL_NAME_PREFIX\s*=\s*["'`]([^"'`]*)["'`]/.exec(tools);+ assert.ok(+ match,+ "pi-coding-agent-extension/tools.ts no longer declares TOOL_NAME_PREFIX as a string literal. " ++ "That prefix is what turns the server's MCP tool names into pi tool names, and this fork's " ++ "probe set is written against it.",+ );+ const prefix = match[1];++ assert.equal(+ prefix,+ "openviking_",+ "The peer changed its tool-name prefix. Every name in this fork's COEXISTENCE_PROBE_TOOLS is " ++ "built from it, so a prefix change makes the tool-name signal miss the peer entirely.",+ );++ assert.match(+ tools,+ /TOOL_NAME_PREFIX\s*\+/,+ "pi-coding-agent-extension/tools.ts declares TOOL_NAME_PREFIX but no longer builds the " ++ "registered names from it, so the names pi actually sees are no longer the ones this " ++ "fork's probe set was written against.",+ );++ const names = probeToolNames(source(FORK_INDEX));+ assert.ok(+ names.includes(`${prefix}search`),+ `COEXISTENCE_PROBE_TOOLS does not contain \`${prefix}search\`, the name the peer registers ` ++ "for the server's `search` tool. `search` is the one tool the peer has always exposed, so " ++ "it is the probe this fork relies on; without it a connected peer is only detectable " ++ "through the globalThis marker.",+ );+});diff --git a/examples/pi-experimental-context-management/tests/index-load.test.mjs b/examples/pi-experimental-context-management/tests/index-load.test.mjsindex a4822c5ba..e26109f37 100644--- a/examples/pi-experimental-context-management/tests/index-load.test.mjs+++ b/examples/pi-experimental-context-management/tests/index-load.test.mjs@@ -679,9 +679,25 @@ test("the fork ships no takeover module", () => {// not fire off a stale usage reading.// ----------------------------------------------------------------------------/** A `viking_search` some other extension registered. */+/** A `viking_search` some other extension registered — the peer before 0.4. */const PEER_TOOL = { name: "viking_search", sourceInfo: { path: "/somewhere/else/openviking" } };+/** The same peer from 0.4 on, where the tools are named `openviking_*`. */+const PEER_TOOL_RENAMED = {+ name: "openviking_search",+ sourceInfo: { path: "/somewhere/else/openviking" },+};++/** The marker the peer sets on `globalThis` once it is connected. */+const PEER_MARKER = "__OPENVIKING_PI_EXTENSION__";++/** Drop the peer marker again, whatever the test did with it. */+function withoutPeerMarker(t) {+ t.after(() => {+ delete globalThis[PEER_MARKER];+ });+}+test("a peer that registers viking_search later still makes this extension stand down", { skip: !JITI_PATH }, async (t) => {withDeadServer(t);// The other extension registers only after its own awaited health check, so@@ -712,6 +728,65 @@ test("a peer that registers viking_search later still makes this extension standassert.equal(await calls.handlers.get("context")({ type: "context", messages }, fakeCtx()), undefined);});+test("a peer that registers the renamed openviking_search stands this extension down too", { skip: !JITI_PATH }, async (t) => {+ withDeadServer(t);+ // From 0.4 on the peer's search tool is `openviking_search`, so probing for+ // the old name alone would leave both extensions writing one OV session.+ let peerLoaded = false;+ const calls = await loadExtension({ getAllTools: () => (peerLoaded ? [PEER_TOOL_RENAMED] : []) });++ const notified = [];+ await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "hello", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.ok(calls.tools.includes("viking_search"), "the early probe found nothing, so we registered");++ peerLoaded = true;+ const result = await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "again", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.equal(result, undefined, "the second writer stands down instead of syncing the same session");+ assert.ok(+ notified.some(([message]) => /another OpenViking extension is already active/.test(message)),+ JSON.stringify(notified),+ );++ const messages = [{ role: "user", content: "hi", timestamp: 1 }];+ assert.equal(await calls.handlers.get("context")({ type: "context", messages }, fakeCtx()), undefined);+});++test("the peer marker alone stands this extension down, with no tool registered", { skip: !JITI_PATH }, async (t) => {+ withDeadServer(t);+ withoutPeerMarker(t);+ // When `/mcp` answers 401/403 or the handshake times out, the peer registers+ // no tool at all and still writes the OV session. The marker is the only+ // signal left, and this extension never sets it itself.+ const calls = await loadExtension({ getAllTools: () => [] });++ const notified = [];+ await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "hello", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.ok(calls.tools.includes("viking_search"), "no peer signal yet, so we registered");++ globalThis[PEER_MARKER] = { version: "0.4.0" };+ const result = await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "again", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.equal(result, undefined, "a tool-less peer is still a second writer");+ assert.ok(+ notified.some(([message]) => /another OpenViking extension is already active/.test(message)),+ JSON.stringify(notified),+ );++ const messages = [{ role: "user", content: "hi", timestamp: 1 }];+ assert.equal(await calls.handlers.get("context")({ type: "context", messages }, fakeCtx()), undefined);+});+test("our own viking_search is not mistaken for a peer's", { skip: !JITI_PATH }, async (t) => {withDeadServer(t);const calls = await loadExtension({@@ -725,6 +800,60 @@ test("our own viking_search is not mistaken for a peer's", { skip: !JITI_PATH },assert.ok(calls.tools.includes("new_context"));});+test("an openviking_search from our own directory is not mistaken for a peer's", { skip: !JITI_PATH }, async (t) => {+ withDeadServer(t);+ // `sourceInfo.path` has the final say over the name: a probe name carrying+ // our own directory is ours, whichever generation of the naming it belongs to.+ const calls = await loadExtension({+ getAllTools: () => [{ name: "openviking_search", sourceInfo: { path: EXTENSION_DIR } }],+ });+ const result = await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "hello", systemPrompt: "BASE" },+ fakeCtx(),+ );+ assert.ok(result?.systemPrompt, "the extension keeps working");+ assert.ok(calls.tools.includes("new_context"));+});++test("without sourceInfo, only a name we never register counts as a peer's", { skip: !JITI_PATH }, async (t) => {+ withDeadServer(t);+ // An older pi reports no `sourceInfo`. Our own `viking_search` then has to be+ // recognised by the fact that we registered it, while `openviking_search` is+ // a name this extension never registers and so can only be the peer's.+ let stage = "empty";+ const registries = {+ empty: [],+ ours: [{ name: "viking_search" }],+ peer: [{ name: "viking_search" }, { name: "openviking_search" }],+ };+ const calls = await loadExtension({ getAllTools: () => registries[stage] });++ const notified = [];+ await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "hello", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.ok(calls.tools.includes("viking_search"), "nothing registered yet, so we registered");++ stage = "ours";+ const kept = await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "still us", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.ok(kept?.systemPrompt, "our own sourceInfo-less viking_search is not a peer");++ stage = "peer";+ const result = await calls.handlers.get("before_agent_start")(+ { type: "before_agent_start", prompt: "again", systemPrompt: "BASE" },+ fakeCtx({ notified }),+ );+ assert.equal(result, undefined, "the peer's openviking_search wins over our own entry in the list");+ assert.ok(+ notified.some(([message]) => /another OpenViking extension is already active/.test(message)),+ JSON.stringify(notified),+ );+});+test("a turn that ended in a provider error does not re-arm the reminders", { skip: !JITI_PATH }, async (t) => {const { port } = await startFakeOv(t);withFakeServer(t, port);