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(plugins): retrofit OpenCode and pi memory integrations (hybrid MCP, shared lib, 4-harness installer) (#3079)
t0sakib511d91ee58e
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex 8e30b9601..aee08e73b 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -38,8 +38,15 @@ jobs:examples/codex-memory-plugin/scripts/auto-recall.test.mjs \examples/claude-code-memory-plugin/scripts/marketplace.test.mjs \examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs \+ examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs \examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs \- examples/memory-plugin-shared/sync.test.mjs+ examples/memory-plugin-shared/install-opencode-jsonc.test.mjs \+ examples/memory-plugin-shared/sync.test.mjs \+ examples/memory-plugin-shared/recall-core.test.mjs \+ examples/memory-plugin-shared/uri-guard.test.mjs \+ examples/opencode-plugin/tests/*.test.mjs \+ examples/opencode-plugin/servers/mcp-proxy.test.mjs \+ examples/pi-coding-agent-extension/tests/*.test.mjs- name: Check installer scripts parserun: |diff --git a/.github/workflows/release-tos.yml b/.github/workflows/release-tos.ymlindex 6fe5418be..dc2b9058e 100644--- a/.github/workflows/release-tos.yml+++ b/.github/workflows/release-tos.yml@@ -85,6 +85,7 @@ jobs:mkdir -p "${STAGE}"cp -R examples/.claude-plugin examples/.agents \examples/claude-code-memory-plugin examples/codex-memory-plugin \+ examples/opencode-plugin examples/pi-coding-agent-extension \examples/memory-plugin-shared "${STAGE}/"(cd /tmp && zip -rq "memory-plugin-marketplace-${RELEASE_TAG}.zip" memory-plugin-marketplace)diff --git a/.gitignore b/.gitignoreindex bef692e50..a327a779f 100644--- a/.gitignore+++ b/.gitignore@@ -15,6 +15,10 @@ eggs/lib/# Shared memory-plugin JS source — not a Python build artifact.!examples/memory-plugin-shared/lib/+!examples/opencode-plugin/lib/+!examples/opencode-plugin/lib/**+!examples/pi-coding-agent-extension/lib/+!examples/pi-coding-agent-extension/lib/**lib64/parts/sdist/@@ -219,3 +223,6 @@ tests/integration/.tmp_*/# LoopX local control-plane state.loopx/++# all node_modules folders+node_modules/diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.mdindex 214eaab6a..affd483c1 100644--- a/docs/en/agent-integrations/01-overview.md+++ b/docs/en/agent-integrations/01-overview.md@@ -10,16 +10,18 @@ OpenViking can act as the long-term memory and context backend for many agent ru| **OpenClaw** | [OpenClaw Plugin](./03-openclaw.md) — context-engine with full lifecycle integration || **Codex** | [Codex Memory Plugin](./04-codex.md) — lifecycle hooks for auto-recall and incremental capture || **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 || **LangChain / LangGraph** | [LangChain and LangGraph](./07-langchain-langgraph.md) — retriever, tools, context backend, store, and middleware || **Cursor / Trae / Manus / Claude Desktop / ChatGPT / …** | [MCP Clients](./06-mcp-clients.md) — point any MCP-compatible client at the built-in `/mcp` endpoint |-| **AstrBot / OpenCode / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |+| **AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |## Integration depthsSome integrations go beyond what a generic MCP client can do:- **Generic MCP clients** call OpenViking on demand through tools the model decides to invoke. Setup is one config snippet.-- **Hooks-based / native plugins** (Claude Code, Codex, OpenClaw, Hermes Agent, AstrBot) drive recall and capture from runtime lifecycle events — every prompt, every turn, session start/end, compact, subagent spawn. The model doesn't need to "remember to recall."+- **Hooks-based / native plugins** (Claude Code, Codex, OpenClaw, Hermes Agent, OpenCode, pi, AstrBot) drive recall and capture from runtime lifecycle events — every prompt, every turn, session start/end, compact, subagent spawn. The model doesn't need to "remember to recall."- **SDK integrations** (LangChain/LangGraph) wire OpenViking into framework-native abstractions such as retrievers, tools, chat history, stores, and middleware.For agents whose runtime exposes hooks, middleware, or a context-engine slot, the native integration path is usually the better default.diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.mdindex 55fff7fc7..7df73c638 100644--- a/docs/en/agent-integrations/02-claude-code.md+++ b/docs/en/agent-integrations/02-claude-code.md@@ -15,7 +15,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/eIn regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror (or pick "TOS mirror" at the download-source prompt):```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```> **TOS caveat for Claude Code**: the TOS channel registers a local directory marketplace, which cannot auto-update — re-run the installer to update. (Codex on TOS installs from a TOS-hosted git repo and keeps remote updates.)diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.mdindex 5fe03a878..a5d9117fc 100644--- a/docs/en/agent-integrations/04-codex.md+++ b/docs/en/agent-integrations/04-codex.md@@ -15,7 +15,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/eIn regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror (or pick "TOS mirror" at the download-source prompt). Codex installs from a TOS-hosted git repo and keeps remote update support:```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```No shell wrapper is needed anymore — the plugin ships a stdio MCP proxy that reads `~/.openviking/ovcli.conf` (or `OPENVIKING_*` env vars) at runtime, same as the hooks. After installing:diff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.mdindex 4cfbc8a18..8005d0cc5 100644--- a/docs/en/agent-integrations/08-community-plugins.md+++ b/docs/en/agent-integrations/08-community-plugins.md@@ -19,139 +19,15 @@ Provides auto-capture of group/DM conversations, semantic recall before each LLM- Four auto-commit triggers: message count, token threshold, idle timeout, and process-exit flush- Backfills platform message history on first venue encounter-## OpenCode plugin+## Open WebUI tool server-OpenViking provides one unified OpenCode plugin for repository context and long-term memory workflows.+[Open WebUI](https://github.com/open-webui/open-webui) is a self-hosted AI chat interface.-Source: [examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)+Source: [examples/openwebui-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/openwebui-plugin)-The plugin combines indexed repository context, OpenViking memory tools, session synchronization, lifecycle commit, and automatic recall through OpenCode plugin hooks. Use this plugin for both the former explicit-tool and context-injection use cases.+A standalone FastAPI server that exposes a curated subset of OpenViking endpoints as OpenAPI tools, so Open WebUI can call them as native tools. Setup and endpoint details are in the README.-### Prerequisites+## More examples-- [OpenCode](https://opencode.ai/)-- Node.js and npm-- An OpenViking HTTP server-- An OpenViking API key when your server requires authentication+The [examples/](https://github.com/volcengine/OpenViking/tree/main/examples) directory also contains deployment and integration samples beyond agent plugins — Grafana dashboards, Kubernetes Helm charts, multi-tenant setups, snapshot workflows, and SDK snippets.-Start your OpenViking server first:--```bash-openviking-server --config ~/.openviking/ov.conf-```--In another terminal, check the service:--```bash-curl http://localhost:1933/health-```--### Install--The published npm package is `@openviking/opencode-plugin`. For a first-time OpenCode config:--```bash-mkdir -p ~/.config/opencode-cat > ~/.config/opencode/opencode.json <<'JSON'-{- "$schema": "https://opencode.ai/config.json",- "plugin": ["@openviking/opencode-plugin"]-}-JSON-opencode-```--If `~/.config/opencode/opencode.json` already exists, do not overwrite it; only merge `"@openviking/opencode-plugin"` into the existing `plugin` array. OpenCode downloads the npm package at startup.--If package installation is not available in your environment, use the source install path below.--```bash-git clone https://github.com/volcengine/OpenViking.git-cd OpenViking-mkdir -p ~/.config/opencode/plugins/openviking-cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js-cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/-cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install-```--This source install creates the layout OpenCode can discover:--```text-~/.config/opencode/plugins/-├── openviking.js-└── openviking/- ├── index.mjs- ├── package.json- ├── lib/- └── node_modules/-```--The top-level `openviking.js` is only a wrapper that forwards OpenCode's first-level plugin entry to the installed package directory.-Use the `.js` wrapper for source installs; OpenCode's local plugin scanner discovers JavaScript/TypeScript plugin files.--### Configure--Create `~/.config/opencode/openviking-config.json`:--```json-{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "",- "enabled": true,- "timeoutMs": 30000,- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },- "autoRecall": {- "enabled": true,- "limit": 6,- "scoreThreshold": 0.15,- "maxContentChars": 500,- "preferAbstract": true,- "tokenBudget": 2000- }-}-```--Prefer environment variables for secrets:--```bash-export OPENVIKING_API_KEY="your-api-key-here"-export OPENVIKING_ACCOUNT="default" # optional, trusted-mode deployments only-export OPENVIKING_USER="opencode" # optional, trusted-mode deployments only-export OPENVIKING_PEER_ID="opencode" # optional, peer-scoped memory routing-```--Environment variables override `openviking-config.json`. `apiKey` is sent as `X-API-Key`; `account` and `user` are trusted-mode headers; `peerId` is sent as request-level `peer_id` for recall, search, and captured session messages.--### Verify--Restart OpenCode after installation. In an OpenCode session, the plugin should expose these tools:--- `memsearch`, `memread`, `membrowse`-- `memgrep`, `memglob`-- `memadd`, `memwrite`, `memremove`, `memqueue`-- `memcommit`-- `codesearch`, `codeoutline`, `codeexpand`--Ask OpenCode to search or browse OpenViking memory, or request a manual session commit. Runtime state and errors are written to:--```bash-~/.config/opencode/openviking/openviking-memory.log-~/.config/opencode/openviking/openviking-session-map.json-```--### Troubleshooting--| Issue | What to check |-|-------|---------------|-| Plugin does not load | Confirm `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or that `~/.config/opencode/plugins/openviking.js` exists for source installs |-| Tools call the wrong server | Check `endpoint` in `~/.config/opencode/openviking-config.json`, or set `OPENVIKING_PLUGIN_CONFIG` to the intended config path |-| 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |-| Recall is empty | Confirm the OpenViking server has indexed memories/resources and that `autoRecall.enabled` is `true` |-| Local `memadd` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |--For all available tools, configuration fields, and runtime file details, see the [plugin README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin).diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.mdnew file mode 100644index 000000000..b1171abcd--- /dev/null+++ b/docs/en/agent-integrations/10-opencode.md@@ -0,0 +1,158 @@+# OpenCode Plugin++Give [OpenCode](https://opencode.ai/) cross-project and cross-session long-term memory plus indexed repository context. Once installed, every conversation automatically recalls relevant memories and captures new content through OpenCode plugin hooks, while model-callable tools come from the same OpenViking stdio MCP proxy used by the Claude Code and Codex memory plugins.++Source: [examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)++## Prerequisites++- [OpenCode](https://opencode.ai/)+- Node.js 18++- An OpenViking HTTP server+- An OpenViking API key when your server requires authentication++Start your OpenViking server first:++```bash+openviking-server --config ~/.openviking/ov.conf+```++In another terminal, check the service:++```bash+curl http://localhost:1933/health+```++## Install++### One-line installer (recommended)++OpenCode shares the unified installer with Claude Code and Codex. It asks for your language (English/中文), which harnesses to install, the download source, and your OpenViking credentials; every step is idempotent—re-running it is entirely safe.++```bash+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness opencode+```++In regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror (or pick "TOS mirror" at the download-source prompt):++```bash+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)+```++The installer registers the npm plugin (or a local file plugin on the TOS channel), writes the `openviking` MCP server entry into `~/.config/opencode/opencode.json`, and configures `~/.openviking/ovcli.conf`.++### Manual npm install++The published npm package is `@openviking/opencode-plugin`. For a first-time OpenCode config:++```bash+mkdir -p ~/.config/opencode+cat > ~/.config/opencode/opencode.json <<'JSON'+{+ "$schema": "https://opencode.ai/config.json",+ "plugin": ["@openviking/opencode-plugin"]+}+JSON+opencode+```++If `~/.config/opencode/opencode.json` already exists, do not overwrite it; only merge `"@openviking/opencode-plugin"` into the existing `plugin` array. OpenCode downloads the npm package at startup, and the plugin registers its MCP server automatically.++### Source install++If package installation is not available in your environment:++```bash+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking+mkdir -p ~/.config/opencode/plugins/openviking+cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js+cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/+cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/+cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/+```++This source install creates the layout OpenCode can discover:++```text+~/.config/opencode/plugins/+├── openviking.js+└── openviking/+ ├── index.mjs+ ├── package.json+ ├── lib/+ └── servers/+```++The top-level `openviking.js` is only a wrapper that forwards OpenCode's first-level plugin entry to the installed package directory.+Use the `.js` wrapper for source installs; OpenCode's local plugin scanner discovers JavaScript/TypeScript plugin files.++## Configure++Credentials are shared with the Claude Code and Codex memory plugins. Run the setup wizard once, or set `OPENVIKING_*` environment variables:++```bash+node examples/opencode-plugin/scripts/setup.mjs+```++`~/.config/opencode/openviking-config.json` is now for behavior knobs only:++```json+{+ "enabled": true,+ "timeoutMs": 30000,+ "repoContext": { "enabled": true, "cacheTtlMs": 60000 },+ "autoRecall": {+ "enabled": true,+ "limit": 6,+ "scoreThreshold": 0.35,+ "maxContentChars": 500,+ "preferAbstract": true,+ "tokenBudget": 2000,+ "minQueryLength": 3+ },+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000+}+```++Environment variables override `ovcli.conf`:++```bash+export OPENVIKING_API_KEY="your-api-key-here"+export OPENVIKING_ACCOUNT="default" # optional, trusted-mode deployments only+export OPENVIKING_USER="opencode" # optional, trusted-mode deployments only+export OPENVIKING_PEER_ID="opencode" # optional, peer-scoped memory routing+```++API keys are sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode headers; `peerId` is sent as `X-OpenViking-Actor-Peer` and as `peer_id` on captured session messages. Existing `openviking-config.json` credential fields are still read as a migration fallback, but new installs should use `ovcli.conf` or env vars.++## Verify++Restart OpenCode after installation. In an OpenCode session, the plugin should expose the `openviking` MCP server. OpenCode namespaces MCP tools as `openviking_*`, for example:++- `openviking_recall`, `openviking_search`, `openviking_find`+- `openviking_read`, `openviking_list`, `openviking_grep`, `openviking_glob`+- `openviking_remember`, `openviking_add_resource`, `openviking_forget`, `openviking_health`+- `openviking_code_search`, `openviking_code_outline`, `openviking_code_expand`++Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are written to:++```bash+~/.config/opencode/openviking/openviking-memory.log+~/.config/opencode/openviking/openviking-session-state.json+```++## Troubleshooting++| Issue | What to check |+|-------|---------------|+| Plugin does not load | Confirm `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or that `~/.config/opencode/plugins/openviking.js` exists for source installs |+| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_PLUGIN_CONFIG` to the intended config path |+| 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |+| Recall is empty | Confirm the OpenViking server has indexed memories/resources and that `autoRecall.enabled` is `true` |+| Local `openviking_add_resource` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |++For all available tools, configuration fields, and runtime file details, see the [plugin README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin).diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdnew file mode 100644index 000000000..c0fab80ea--- /dev/null+++ b/docs/en/agent-integrations/11-pi.md@@ -0,0 +1,84 @@+# pi Coding Agent Extension++Give [pi](https://github.com/earendil-works/pi) cross-session long-term memory. 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 sessions are committed for persistent memory extraction.++Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)++## How it works++- **Session start** injects your OpenViking profile block, plus the archive overview when resuming a previously committed session.+- **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; the session commits automatically once pending content crosses the token threshold, before compaction, and at shutdown.+- **Native tools** `viking_search`, `viking_read`, `viking_browse`, `viking_remember`, `viking_forget`, `viking_add_resource`, `viking_archive_expand` let the model query and update memory on demand.+- A footer status segment (`OV ✓ …`) shows connection and capture state; the `/viking` command prints status, and `/viking commit` forces a commit.+- Accidental `read`/`bash` calls on `viking://` URIs are blocked with a hint pointing back to `viking_read` / `viking_search`.++## Prerequisites++- pi coding agent (`npm i -g @earendil-works/pi-coding-agent`)+- An OpenViking HTTP server — verify with `curl http://localhost:1933/health`++## Install++pi shares the unified installer with the other memory plugins. It asks for your language, harnesses, download source, and OpenViking credentials; every step is idempotent.++```bash+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness pi+```++In regions where GitHub is hard to reach, run the same installer from the Volcengine TOS mirror:++```bash+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)+```++The installer copies the extension into `~/.pi/agent/extensions/openviking` (preserving an existing `config.json`), registers it with `pi install`, and configures `~/.openviking/ovcli.conf`.++Manual copy from a repo checkout also works:++```bash+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking+mkdir -p ~/.pi/agent/extensions+cp -r examples/pi-coding-agent-extension ~/.pi/agent/extensions/openviking+```++## Configure++Credentials resolve from `OPENVIKING_*` environment variables, then `~/.openviking/ovcli.conf`, then `~/.openviking/ov.conf` — shared with the Claude Code, Codex, and OpenCode plugins. Run the wizard once if you have not configured them yet:++```bash+node ~/.pi/agent/extensions/openviking/scripts/setup.mjs+```++`~/.pi/agent/extensions/openviking/config.json` holds behavior knobs only, and reinstalls preserve your edits:++```json+{+ "recallLimit": 6,+ "scoreThreshold": 0.35,+ "recallTokenBudget": 2000,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000,+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "captureAssistantTurns": true,+ "bypassPatterns": []+}+```++## 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.++## Troubleshooting++| Issue | What to check |+|-------|---------------|+| `OV ✗` in the footer or "server not reachable" | `curl http://localhost:1933/health`; check the endpoint in `~/.openviking/ovcli.conf` |+| Extension does not load | `pi list` should show `extensions/openviking`; re-run the installer or `pi install ~/.pi/agent/extensions/openviking` |+| 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` |+| 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/images/agents/en/opencode.md b/docs/images/agents/en/opencode.mdindex 2e554ca21..e38826459 100644--- a/docs/images/agents/en/opencode.md+++ b/docs/images/agents/en/opencode.md@@ -1,122 +1,52 @@-OpenViking provides one unified OpenCode plugin for repository context and long-term memory workflows.--## `opencode-plugin`+Add persistent, cross-session memory and indexed repository context to [OpenCode](https://opencode.ai/). Install it once, and the plugin will automatically recall memories on every prompt, capture turns into OpenViking sessions, and commit before compaction. Model-callable tools come from the same OpenViking MCP proxy used by the Claude Code and Codex plugins.Source: [examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)-The plugin combines indexed repository context, OpenViking memory tools, session synchronization, lifecycle commit, and automatic recall through OpenCode plugin hooks.--## Step 1: Prepare OpenViking--Install OpenCode, Node.js/npm, and an OpenViking HTTP server. Start the server before launching OpenCode:--```bash-openviking-server --config ~/.openviking/ov.conf-```--In another terminal, check the service:--```bash-curl http://localhost:1933/health-```--For remote or multi-tenant deployments, prepare an OpenViking API key.--## Step 2: Install the plugin--The published npm package is `@openviking/opencode-plugin`. For a first-time OpenCode config:+## Step 1: Install```bash-mkdir -p ~/.config/opencode-cat > ~/.config/opencode/opencode.json <<'JSON'-{- "$schema": "https://opencode.ai/config.json",- "plugin": ["@openviking/opencode-plugin"]-}-JSON-opencode+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```-If `~/.config/opencode/opencode.json` already exists, do not overwrite it; only merge `"@openviking/opencode-plugin"` into the existing `plugin` array. OpenCode downloads the npm package at startup.+OpenCode shares this one installer with Claude Code and Codex. It asks which tools to install, which source to use (GitHub or the TOS mirror), your language (English/中文), and OpenViking credentials; each step is idempotent, so it is safe to rerun. On the TOS channel the plugin is installed as local files — rerun the installer to update.-If package installation is not available in your environment, use the source install path below.--```bash-git clone https://github.com/volcengine/OpenViking.git-cd OpenViking-mkdir -p ~/.config/opencode/plugins/openviking-cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js-cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/-cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install-```+<details>+<summary><b>Manual installation</b></summary>-The source install creates:+Prerequisites: OpenCode, Node.js 18+, and a reachable OpenViking server (`curl http://localhost:1933/health`).-```text-~/.config/opencode/plugins/-├── openviking.js-└── openviking/- ├── index.mjs- ├── package.json- ├── lib/- └── node_modules/-```+1. **Configure the connection** - write `~/.openviking/ovcli.conf` (`url`, `api_key`, optional `account`/`user`), or run the bundled wizard `node <plugin-dir>/scripts/setup.mjs` after installing.-## Step 3: Configure the OpenViking connection--Create `~/.config/opencode/openviking-config.json`:--```json-{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "",- "enabled": true,- "timeoutMs": 30000,- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },- "autoRecall": {- "enabled": true,- "limit": 6,- "scoreThreshold": 0.15,- "maxContentChars": 500,- "preferAbstract": true,- "tokenBudget": 2000- }-}-```+2. **Register the npm plugin** (needs npm registry access) — merge `"@openviking/opencode-plugin"` into the `plugin` array of `~/.config/opencode/opencode.json`:-Prefer environment variables for secrets:+ ```json+ {+ "$schema": "https://opencode.ai/config.json",+ "plugin": ["@openviking/opencode-plugin"]+ }+ ```-```bash-export OPENVIKING_API_KEY="your-api-key-here"-export OPENVIKING_ACCOUNT="default" # optional, trusted-mode deployments only-export OPENVIKING_USER="opencode" # optional, trusted-mode deployments only-export OPENVIKING_PEER_ID="opencode" # optional, peer-scoped memory routing-```+ OpenCode downloads the package at startup, and the plugin registers its `openviking` MCP server automatically.-Environment variables override the config file.+</details>-## Step 4: Verify+## Step 2: Verify-Restart OpenCode. The plugin should expose memory tools `memsearch`, `memread`, `membrowse`, `memgrep`, `memglob`, `memadd`, `memwrite`, `memremove`, `memqueue`, `memcommit`, and code tools `codesearch`, `codeoutline`, `codeexpand`.+Restart OpenCode. The plugin exposes MCP tools with the `openviking_` prefix, for example `openviking_search`, `openviking_read`, `openviking_remember`, `openviking_health`. Ask OpenCode to search or browse OpenViking memory.-Ask OpenCode to browse OpenViking or commit the current session. Check runtime logs if anything looks wrong:+Behavior knobs (recall limits, commit thresholds) live in `~/.config/opencode/openviking-config.json`; credentials come from `~/.openviking/ovcli.conf` or `OPENVIKING_*` environment variables. Runtime logs:```bash~/.config/opencode/openviking/openviking-memory.log-~/.config/opencode/openviking/openviking-session-map.json+~/.config/opencode/openviking/openviking-session-state.json```## Troubleshooting| Symptom | Fix ||---------|-----|-| Plugin is not loaded | Check `~/.config/opencode/opencode.json` for package installs, or `~/.config/opencode/plugins/openviking.js` for source installs |-| Tools call the wrong server | Check `endpoint`, or set `OPENVIKING_PLUGIN_CONFIG` to the intended config path |+| Plugin is not loaded | Check `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or `~/.config/opencode/plugins/openviking.js` for file installs |+| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_PLUGIN_CONFIG` || 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; trusted-mode deployments also need `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` || Recall is empty | Confirm OpenViking has memories/resources and `autoRecall.enabled` is `true` |diff --git a/docs/images/agents/zh/opencode.md b/docs/images/agents/zh/opencode.mdindex 72108c902..a4e4ba52d 100644--- a/docs/images/agents/zh/opencode.md+++ b/docs/images/agents/zh/opencode.md@@ -1,123 +1,52 @@--OpenViking 现在只保留一个面向 OpenCode 的统一插件,同时覆盖仓库上下文与长期记忆场景。--## `opencode-plugin`+为 [OpenCode](https://opencode.ai/) 提供跨会话长期记忆和已索引仓库上下文。安装一次后,插件会在每次 prompt 前自动召回记忆、把对话逐轮捕获进 OpenViking session,并在 compact 前自动 commit。模型可调用工具来自 Claude Code / Codex 插件同款的 OpenViking MCP proxy。源码:[examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)-这个插件通过 OpenCode plugin hooks 组合已索引仓库上下文、OpenViking 记忆工具、session 同步、生命周期 commit 与自动 recall。--## 步骤 1:准备 OpenViking--先安装 OpenCode、Node.js/npm,并准备一个 OpenViking HTTP server。启动 OpenCode 前先启动服务:+## 步骤 1:安装```bash-openviking-server --config ~/.openviking/ov.conf+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```-在另一个终端检查服务:+OpenCode 与 Claude Code、Codex 共用这一个安装器。它会询问要安装的工具、下载源(GitHub 或 TOS 镜像)、语言(English/中文)和 OpenViking 凭据;每一步都是幂等的,重复运行完全安全。TOS 渠道以本地文件方式安装插件——更新时重跑安装器即可。-```bash-curl http://localhost:1933/health-```+<details>+<summary><b>手动安装</b></summary>-远程或多租户部署需要提前准备 OpenViking API key。+前置条件:OpenCode、Node.js 18+,以及可达的 OpenViking server(`curl http://localhost:1933/health`)。-## 步骤 2:安装插件+1. **配置连接**——写入 `~/.openviking/ovcli.conf`(`url`、`api_key`,可选 `account`/`user`),或安装后运行内置向导 `node <plugin-dir>/scripts/setup.mjs`。-已发布的 npm 包是 `@openviking/opencode-plugin`。首次配置 OpenCode 时:+2. **注册 npm 插件**(需要 npm registry 可达)——把 `"@openviking/opencode-plugin"` 合并进 `~/.config/opencode/opencode.json` 的 `plugin` 数组:-```bash-mkdir -p ~/.config/opencode-cat > ~/.config/opencode/opencode.json <<'JSON'-{- "$schema": "https://opencode.ai/config.json",- "plugin": ["@openviking/opencode-plugin"]-}-JSON-opencode-```--已有 `~/.config/opencode/opencode.json` 时,不要覆盖原文件;只把 `"@openviking/opencode-plugin"` 合并到已有的 `plugin` 数组。OpenCode 启动时会自动下载这个 npm 包。+ ```json+ {+ "$schema": "https://opencode.ai/config.json",+ "plugin": ["@openviking/opencode-plugin"]+ }+ ```-如果当前环境不能通过 package 安装,请使用下面的源码安装路径。--```bash-git clone https://github.com/volcengine/OpenViking.git-cd OpenViking-mkdir -p ~/.config/opencode/plugins/openviking-cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js-cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/-cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install-```--源码安装会形成如下结构:--```text-~/.config/opencode/plugins/-├── openviking.js-└── openviking/- ├── index.mjs- ├── package.json- ├── lib/- └── node_modules/-```--## 步骤 3:配置 OpenViking 连接--创建 `~/.config/opencode/openviking-config.json`:--```json-{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "",- "enabled": true,- "timeoutMs": 30000,- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },- "autoRecall": {- "enabled": true,- "limit": 6,- "scoreThreshold": 0.15,- "maxContentChars": 500,- "preferAbstract": true,- "tokenBudget": 2000- }-}-```--敏感信息建议用环境变量提供:--```bash-export OPENVIKING_API_KEY="your-api-key-here"-export OPENVIKING_ACCOUNT="default" # 可选,仅 trusted-mode 部署需要-export OPENVIKING_USER="opencode" # 可选,仅 trusted-mode 部署需要-export OPENVIKING_PEER_ID="opencode" # 可选,peer 维度记忆路由需要-```+ OpenCode 启动时会自动下载该包,插件会自动注册它的 `openviking` MCP server。-环境变量优先级高于配置文件。+</details>-## 步骤 4:验证+## 步骤 2:验证-重启 OpenCode。插件应暴露 memory tools:`memsearch`、`memread`、`membrowse`、`memgrep`、`memglob`、`memadd`、`memwrite`、`memremove`、`memqueue`、`memcommit`,以及 code tools:`codesearch`、`codeoutline`、`codeexpand`。+重启 OpenCode。插件会暴露带 `openviking_` 前缀的 MCP 工具,例如 `openviking_search`、`openviking_read`、`openviking_remember`、`openviking_health`。可以让 OpenCode 搜索或浏览 OpenViking memory。-可以让 OpenCode 浏览 OpenViking 或 commit 当前 session。异常时查看运行时日志:+行为旋钮(召回上限、commit 阈值等)在 `~/.config/opencode/openviking-config.json`;凭据来自 `~/.openviking/ovcli.conf` 或 `OPENVIKING_*` 环境变量。运行时日志:```bash~/.config/opencode/openviking/openviking-memory.log-~/.config/opencode/openviking/openviking-session-map.json+~/.config/opencode/openviking/openviking-session-state.json```## 故障排查| 现象 | 修复 ||------|------|-| 插件没有加载 | package 安装检查 `~/.config/opencode/opencode.json`;源码安装检查 `~/.config/opencode/plugins/openviking.js` |-| Tools 连到了错误的 server | 检查 `endpoint`,或用 `OPENVIKING_PLUGIN_CONFIG` 指向正确配置文件 |+| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 引用了 `@openviking/opencode-plugin`;文件安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 |+| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或设置 `OPENVIKING_*` 环境变量 / `OPENVIKING_PLUGIN_CONFIG` || OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还需要 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` || recall 为空 | 确认 OpenViking 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.mdindex db4613bc0..57df584e3 100644--- a/docs/zh/agent-integrations/01-overview.md+++ b/docs/zh/agent-integrations/01-overview.md@@ -10,16 +10,18 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端| **OpenClaw** | [OpenClaw 插件](./03-openclaw.md) — 全生命周期一体化集成 || **Codex** | [Codex 记忆插件](./04-codex.md) — 生命周期 hooks 自动召回与增量捕获 || **Hermes Agent** | [Hermes Agent](./05-hermes.md) — 内置 OpenViking 记忆提供方,无需安装插件 |+| **OpenCode** | [OpenCode 插件](./10-opencode.md) — MCP 工具 + 生命周期 hooks,覆盖仓库上下文、自动召回与捕获 |+| **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获与阈值 commit || **LangChain / LangGraph** | [LangChain 和 LangGraph](./07-langchain-langgraph.md) — retriever、tools、context backend、store 和 middleware || **Cursor / Trae / Manus / Claude Desktop / ChatGPT / …** | [MCP 客户端](./06-mcp-clients.md) — 任何兼容 MCP 的客户端直接对接内置 `/mcp` 端点 |-| **AstrBot / OpenCode / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |+| **AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |## 集成深度部分集成能力超过通用 MCP 客户端:- **通用 MCP 客户端**:模型主动调用工具时按需访问 OpenViking。配置只需一份连接片段。-- **基于 hooks / 原生插件**(Claude Code、Codex、OpenClaw、Hermes Agent、AstrBot):在运行时生命周期事件(每次 prompt、每轮结束、session 起止、compact、subagent 派生等)中驱动召回与捕获。模型不需要"记得调用"。+- **基于 hooks / 原生插件**(Claude Code、Codex、OpenClaw、Hermes Agent、OpenCode、pi、AstrBot):在运行时生命周期事件(每次 prompt、每轮结束、session 起止、compact、subagent 派生等)中驱动召回与捕获。模型不需要"记得调用"。- **SDK 集成**(LangChain/LangGraph):把 OpenViking 接入框架原生抽象,例如 retriever、tools、chat history、store 和 middleware。如果你的 Agent 运行时暴露 hooks、middleware 或 context-engine 槽位,原生集成通常是更好的默认选择。diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.mdindex c7de094fd..06dde4ff2 100644--- a/docs/zh/agent-integrations/02-claude-code.md+++ b/docs/zh/agent-integrations/02-claude-code.md@@ -15,7 +15,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/eGitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个安装脚本(或在下载源提问时选择「TOS 镜像」):```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```> **Claude Code 走 TOS 的注意事项**:TOS 渠道注册的是本地目录 marketplace,**无法自动更新**——更新请重跑安装脚本。(Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力。)diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.mdindex 237dab0c3..c558ecdec 100644--- a/docs/zh/agent-integrations/04-codex.md+++ b/docs/zh/agent-integrations/04-codex.md@@ -15,7 +15,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/eGitHub 访问受限的地区,从火山引擎 TOS 镜像运行同一个安装脚本(或在下载源提问时选择「TOS 镜像」)。Codex 走 TOS 时安装自 TOS 托管的 git 仓库,保留远程更新能力:```bash-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)```现在不再需要任何 shell wrapper——插件自带的 stdio MCP 代理会在运行时读取 `~/.openviking/ovcli.conf`(或 `OPENVIKING_*` 环境变量),与 hooks 使用同一套配置链。安装完成后:diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.mdindex 7692dc383..8e2bceaa2 100644--- a/docs/zh/agent-integrations/08-community-plugins.md+++ b/docs/zh/agent-integrations/08-community-plugins.md@@ -19,139 +19,15 @@- 四触发器自动 commit:消息计数、token 阈值、空闲超时、进程退出 flush- 首次接入群聊时自动拉取平台历史消息入库-## OpenCode 插件+## Open WebUI tool server-OpenViking 现在只保留一个面向 OpenCode 的统一插件,同时覆盖仓库上下文与长期记忆场景。+[Open WebUI](https://github.com/open-webui/open-webui) 是一个自托管的 AI 聊天界面。-源码:[examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)+源码:[examples/openwebui-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/openwebui-plugin)-这个插件通过 OpenCode plugin hooks 组合已索引仓库上下文、OpenViking 记忆工具、session 同步、生命周期 commit 与自动 recall。原来的显式工具和上下文注入两类用法都应使用这个统一插件。+一个独立的 FastAPI server,把 OpenViking 的一组精选端点以 OpenAPI tools 形式暴露,让 Open WebUI 作为原生工具调用。部署与端点说明见 README。-### 前置条件+## 更多示例-- [OpenCode](https://opencode.ai/)-- Node.js 和 npm-- OpenViking HTTP server-- 如果服务端启用了鉴权,需要一个可用的 OpenViking API key+[examples/](https://github.com/volcengine/OpenViking/tree/main/examples) 目录下还有 Agent 插件之外的部署与集成示例——Grafana 面板、Kubernetes Helm chart、多租户配置、快照流程和 SDK 片段等。-先启动 OpenViking server:--```bash-openviking-server --config ~/.openviking/ov.conf-```--在另一个终端检查服务:--```bash-curl http://localhost:1933/health-```--### 安装--已发布的 npm 包是 `@openviking/opencode-plugin`。首次配置 OpenCode 时:--```bash-mkdir -p ~/.config/opencode-cat > ~/.config/opencode/opencode.json <<'JSON'-{- "$schema": "https://opencode.ai/config.json",- "plugin": ["@openviking/opencode-plugin"]-}-JSON-opencode-```--已有 `~/.config/opencode/opencode.json` 时,不要覆盖原文件;只把 `"@openviking/opencode-plugin"` 合并到已有的 `plugin` 数组。OpenCode 启动时会自动下载这个 npm 包。--如果当前环境不能通过 package 安装,请使用下面的源码安装路径。--```bash-git clone https://github.com/volcengine/OpenViking.git-cd OpenViking-mkdir -p ~/.config/opencode/plugins/openviking-cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js-cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/-cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install-```--源码安装后,OpenCode 能发现的目录结构应类似:--```text-~/.config/opencode/plugins/-├── openviking.js-└── openviking/- ├── index.mjs- ├── package.json- ├── lib/- └── node_modules/-```--顶层 `openviking.js` 只是一个 wrapper,用来把 OpenCode 可发现的一级插件入口转发到实际安装目录。-源码安装请使用 `.js` wrapper;OpenCode 的本地插件扫描器会发现 JavaScript/TypeScript 插件文件。--### 配置--创建 `~/.config/opencode/openviking-config.json`:--```json-{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "",- "enabled": true,- "timeoutMs": 30000,- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },- "autoRecall": {- "enabled": true,- "limit": 6,- "scoreThreshold": 0.15,- "maxContentChars": 500,- "preferAbstract": true,- "tokenBudget": 2000- }-}-```--敏感信息建议用环境变量提供:--```bash-export OPENVIKING_API_KEY="your-api-key-here"-export OPENVIKING_ACCOUNT="default" # 可选,仅 trusted-mode 部署需要-export OPENVIKING_USER="opencode" # 可选,仅 trusted-mode 部署需要-export OPENVIKING_PEER_ID="opencode" # 可选,peer 维度记忆路由需要-```--环境变量优先级高于 `openviking-config.json`。`apiKey` 会作为 `X-API-Key` 发送;`account` 和 `user` 是 trusted-mode headers;`peerId` 会作为请求级 `peer_id` 用于 recall、search 和 session message 写入。--### 验证--安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露这些 tools:--- `memsearch`、`memread`、`membrowse`-- `memgrep`、`memglob`-- `memadd`、`memwrite`、`memremove`、`memqueue`-- `memcommit`-- `codesearch`、`codeoutline`、`codeexpand`--可以让 OpenCode 搜索或浏览 OpenViking memory,也可以要求它手动 commit 当前 session。运行时状态和错误日志会写入:--```bash-~/.config/opencode/openviking/openviking-memory.log-~/.config/opencode/openviking/openviking-session-map.json-```--### 故障排查--| 问题 | 排查方向 |-|------|----------|-| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 引用了 `@openviking/opencode-plugin`;源码安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 |-| Tools 连到了错误的 server | 检查 `~/.config/opencode/openviking-config.json` 里的 `endpoint`,或用 `OPENVIKING_PLUGIN_CONFIG` 指向正确配置文件 |-| OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |-| recall 为空 | 确认 OpenViking server 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |-| 本地 `memadd` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |--完整 tools、配置字段和运行时文件说明见 [插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)。diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.mdnew file mode 100644index 000000000..46f39a1d6--- /dev/null+++ b/docs/zh/agent-integrations/10-opencode.md@@ -0,0 +1,158 @@+# OpenCode 插件++为 [OpenCode](https://opencode.ai/) 提供跨项目、跨会话的长期记忆和已索引仓库上下文。安装后,每次对话都会通过 OpenCode plugin hooks 自动召回相关记忆并捕获新内容;模型可调用工具来自 Claude Code / Codex 记忆插件同款的 OpenViking stdio MCP proxy。++源码:[examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)++## 前置条件++- [OpenCode](https://opencode.ai/)+- Node.js 18++- OpenViking HTTP server+- 如果服务端启用了鉴权,需要一个可用的 OpenViking API key++先启动 OpenViking server:++```bash+openviking-server --config ~/.openviking/ov.conf+```++在另一个终端检查服务:++```bash+curl http://localhost:1933/health+```++## 安装++### 一键安装(推荐)++OpenCode 与 Claude Code、Codex 共用同一个安装器。它会询问语言(English/中文)、要安装的 harness、下载源和 OpenViking 凭据;每一步都是幂等的,重复运行完全安全。++```bash+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness opencode+```++在 GitHub 访问困难的地区,可从火山引擎 TOS 镜像运行同一个安装器(或在下载源选择步骤选"TOS mirror"):++```bash+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)+```++安装器会注册 npm 插件(TOS 渠道则安装本地文件插件),把 `openviking` MCP server 条目写进 `~/.config/opencode/opencode.json`,并配置 `~/.openviking/ovcli.conf`。++### 手动 npm 安装++已发布的 npm 包是 `@openviking/opencode-plugin`。首次配置 OpenCode 时:++```bash+mkdir -p ~/.config/opencode+cat > ~/.config/opencode/opencode.json <<'JSON'+{+ "$schema": "https://opencode.ai/config.json",+ "plugin": ["@openviking/opencode-plugin"]+}+JSON+opencode+```++已有 `~/.config/opencode/opencode.json` 时,不要覆盖原文件;只把 `"@openviking/opencode-plugin"` 合并到已有的 `plugin` 数组。OpenCode 启动时会自动下载这个 npm 包,插件会自动注册它的 MCP server。++### 源码安装++如果当前环境不能通过 package 安装:++```bash+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking+mkdir -p ~/.config/opencode/plugins/openviking+cp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.js+cp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/+cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/+cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/+```++源码安装后,OpenCode 能发现的目录结构应类似:++```text+~/.config/opencode/plugins/+├── openviking.js+└── openviking/+ ├── index.mjs+ ├── package.json+ ├── lib/+ └── servers/+```++顶层 `openviking.js` 只是一个 wrapper,用来把 OpenCode 可发现的一级插件入口转发到实际安装目录。+源码安装请使用 `.js` wrapper;OpenCode 的本地插件扫描器会发现 JavaScript/TypeScript 插件文件。++## 配置++凭据与 Claude Code / Codex 记忆插件共用。可以先运行 setup 向导,或使用 `OPENVIKING_*` 环境变量:++```bash+node examples/opencode-plugin/scripts/setup.mjs+```++`~/.config/opencode/openviking-config.json` 现在只放行为旋钮:++```json+{+ "enabled": true,+ "timeoutMs": 30000,+ "repoContext": { "enabled": true, "cacheTtlMs": 60000 },+ "autoRecall": {+ "enabled": true,+ "limit": 6,+ "scoreThreshold": 0.35,+ "maxContentChars": 500,+ "preferAbstract": true,+ "tokenBudget": 2000,+ "minQueryLength": 3+ },+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000+}+```++环境变量优先级高于 `ovcli.conf`:++```bash+export OPENVIKING_API_KEY="your-api-key-here"+export OPENVIKING_ACCOUNT="default" # 可选,仅 trusted-mode 部署需要+export OPENVIKING_USER="opencode" # 可选,仅 trusted-mode 部署需要+export OPENVIKING_PEER_ID="opencode" # 可选,peer 维度记忆路由需要+```++API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`account` 和 `user` 是 trusted-mode headers;`peerId` 会作为 `X-OpenViking-Actor-Peer` 和捕获 session message 的 `peer_id` 使用。旧版 `openviking-config.json` 里的凭据字段仍会作为迁移 fallback 读取,但新安装建议使用 `ovcli.conf` 或环境变量。++## 验证++安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server。OpenCode 会给 MCP 工具加 `openviking_` 前缀,例如:++- `openviking_recall`、`openviking_search`、`openviking_find`+- `openviking_read`、`openviking_list`、`openviking_grep`、`openviking_glob`+- `openviking_remember`、`openviking_add_resource`、`openviking_forget`、`openviking_health`+- `openviking_code_search`、`openviking_code_outline`、`openviking_code_expand`++可以让 OpenCode 搜索或浏览 OpenViking memory。运行时状态和错误日志会写入:++```bash+~/.config/opencode/openviking/openviking-memory.log+~/.config/opencode/openviking/openviking-session-state.json+```++## 故障排查++| 问题 | 排查方向 |+|------|----------|+| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 引用了 `@openviking/opencode-plugin`;源码安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 |+| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量 / `OPENVIKING_PLUGIN_CONFIG` 指向正确配置 |+| OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |+| recall 为空 | 确认 OpenViking server 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |+| 本地 `openviking_add_resource` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |++完整 tools、配置字段和运行时文件说明见 [插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)。diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdnew file mode 100644index 000000000..f3581939b--- /dev/null+++ b/docs/zh/agent-integrations/11-pi.md@@ -0,0 +1,84 @@+# pi Coding Agent 扩展++为 [pi](https://github.com/earendil-works/pi) 提供跨会话长期记忆。扩展基于 pi 原生扩展 API 构建(pi 不支持 MCP):每个 prompt 前自动召回、每个 turn 后自动捕获,session 会被 commit 以进行持久记忆提取。++源码:[examples/pi-coding-agent-extension](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)++## 工作方式++- **Session 开始**时注入 OpenViking profile 块;恢复曾 commit 过的 session 时追加 archive 概览。+- **每个 prompt** 向 OpenViking server 做语义召回,把命中的记忆作为隐藏上下文注入。+- **每个 turn** 把用户与助手消息(含结构化工具调用)捕获进 OpenViking session;待处理内容超过 token 阈值、compact 前、退出时都会自动 commit。+- **原生工具** `viking_search`、`viking_read`、`viking_browse`、`viking_remember`、`viking_forget`、`viking_add_resource`、`viking_archive_expand` 供模型按需查询和写入记忆。+- 底部状态栏显示 `OV ✓ …` 连接与捕获状态;`/viking` 命令查看状态,`/viking commit` 强制 commit。+- 模型误用本地 `read`/`bash` 读取 `viking://` URI 时会被拦截,并提示改用 `viking_read` / `viking_search`。++## 前置条件++- pi coding agent(`npm i -g @earendil-works/pi-coding-agent`)+- OpenViking HTTP server——用 `curl http://localhost:1933/health` 确认可达++## 安装++pi 与其他记忆插件共用同一个安装器。它会询问语言、要安装的 harness、下载源和 OpenViking 凭据;每一步都是幂等的。++```bash+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness pi+```++在 GitHub 访问困难的地区,可从火山引擎 TOS 镜像运行同一个安装器:++```bash+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)+```++安装器会把扩展复制到 `~/.pi/agent/extensions/openviking`(保留已有的 `config.json`),用 `pi install` 完成注册,并配置 `~/.openviking/ovcli.conf`。++也可以从仓库 checkout 手动复制:++```bash+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking+mkdir -p ~/.pi/agent/extensions+cp -r examples/pi-coding-agent-extension ~/.pi/agent/extensions/openviking+```++## 配置++凭据解析顺序是 `OPENVIKING_*` 环境变量、`~/.openviking/ovcli.conf`、`~/.openviking/ov.conf`——与 Claude Code、Codex、OpenCode 插件共用。尚未配置时可运行一次向导:++```bash+node ~/.pi/agent/extensions/openviking/scripts/setup.mjs+```++`~/.pi/agent/extensions/openviking/config.json` 只保留行为旋钮,重装时会保留你的修改:++```json+{+ "recallLimit": 6,+ "scoreThreshold": 0.35,+ "recallTokenBudget": 2000,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000,+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "captureAssistantTurns": true,+ "bypassPatterns": []+}+```++## 验证++启动 `pi`。连接成功后底部状态栏出现 `OV ✓` 段,`/viking` 会打印当前 session 映射。问 pi 一个你在早前会话里提到过的事情,确认召回生效。++## 故障排查++| 问题 | 排查方向 |+|------|----------|+| 状态栏显示 `OV ✗` 或提示 "server not reachable" | `curl http://localhost:1933/health`;检查 `~/.openviking/ovcli.conf` 中的 endpoint |+| 扩展没有加载 | `pi list` 应能看到 `extensions/openviking`;重跑安装器或执行 `pi install ~/.pi/agent/extensions/openviking` |+| 报错提到 `@mariozechner/*` | pi 迁移到 `@earendil-works/*` 之前的旧副本——重跑安装器 |+| OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |+| recall 为空 | 确认 server 中已有记忆,且 prompt 长度超过 `minQueryLength` |++完整工具、配置与设计说明见 [扩展 README](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)。diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonindex 45ba3bad9..c5f9698b4 100644--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openviking-memory",- "version": "0.3.0",+ "version": "0.4.0","description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.","author": {"name": "OpenViking",diff --git a/examples/claude-code-memory-plugin/hooks/hooks.json b/examples/claude-code-memory-plugin/hooks/hooks.jsonindex 5d6d5ad7a..d2d4df28a 100644--- a/examples/claude-code-memory-plugin/hooks/hooks.json+++ b/examples/claude-code-memory-plugin/hooks/hooks.json@@ -35,6 +35,18 @@]}],+ "PreToolUse": [+ {+ "matcher": "Read|Glob|Grep",+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/uri-guard.mjs",+ "timeout": 5+ }+ ]+ }+ ],"Stop": [{"matcher": "",diff --git a/examples/claude-code-memory-plugin/package-lock.json b/examples/claude-code-memory-plugin/package-lock.jsonindex 1b07ebfd4..c875c2e34 100644--- a/examples/claude-code-memory-plugin/package-lock.json+++ b/examples/claude-code-memory-plugin/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-code-openviking-memory",- "version": "0.3.0",+ "version": "0.4.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-code-openviking-memory",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@modelcontextprotocol/sdk": "^1.12.1","zod": "^4.3.6"diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.jsonindex 0035de0af..1440bcb3c 100644--- a/examples/claude-code-memory-plugin/package.json+++ b/examples/claude-code-memory-plugin/package.json@@ -1,6 +1,6 @@{"name": "claude-code-openviking-memory",- "version": "0.3.0",+ "version": "0.4.0","description": "OpenViking memory plugin for Claude Code — semantic long-term memory","type": "module","scripts": {diff --git a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjsindex 1b4bec26a..7b43209d2 100644--- a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs@@ -1,293 +1 @@-/**- * Session-start profile injection helper.- *- * Builds a <user-profile> + <available-memories> block from- * viking://user/<space>/memories/profile.md- * viking://user/<space>/memories/preferences/ (ls with abstracts)- * viking://user/<space>/memories/entities/ (ls with abstracts)- *- * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=- * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so- * callers (e.g. session-start.mjs) can log token counts that match what- * the budget logic actually sees.- *- * Returned block is the *inner* content only (no outer <openviking-context>);- * session-start.mjs composes the outer wrapper so the archive block can sit- * alongside in a single context envelope.- */--const USER_RESERVED_DIRS = new Set(["memories"]);-let _userSpaceCache = null;--/**- * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).- * Duplicated rather than imported to avoid coupling session-start to- * auto-recall's module-level fetchJSON closure.- */-async function resolveUserSpace(fetchJSON, actorPeerId = "") {- if (_userSpaceCache) return _userSpaceCache;-- let fallbackSpace = "default";- const status = await fetchJSON("/api/v1/system/status");- if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {- fallbackSpace = status.result.user.trim();- }-- const lsRes = await fetchJSON(- `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,- {},- { actorPeerId },- );- if (lsRes.ok && Array.isArray(lsRes.result)) {- const spaces = lsRes.result- .filter((e) => e?.isDir)- .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))- .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));- if (spaces.length > 0) {- if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }- if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }- if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }- }- }- _userSpaceCache = fallbackSpace;- return fallbackSpace;-}--/**- * Token estimate that splits CJK from the rest. The rest of the plugin uses a- * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and- * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.- *- * Rule:- * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK- * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical- * average for cl100k_base on Chinese; Claude's tokenizer is in the same- * ballpark).- * - everything else → chars/4 (the standard English-ish heuristic).- *- * Single linear pass, no dependencies. Errs on the side of overcounting CJK- * by ~10-20% in the worst case (some common Chinese phrases compress better- * than 1.5 tokens/char), which is the safe direction for budget enforcement.- */-export function estimateTokens(text) {- if (!text) return 0;- let cjk = 0;- for (let i = 0; i < text.length; i++) {- if (text.charCodeAt(i) >= 0x3000) cjk++;- }- const other = text.length - cjk;- return Math.ceil(cjk * 1.5 + other / 4);-}--/**- * Convert a token budget to a max-chars budget that respects this content's- * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap- * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).- *- * For an empty/missing string, returns 0.- */-function tokensToCharsBudget(content, maxTokens) {- if (!content) return 0;- let cjk = 0;- for (let i = 0; i < content.length; i++) {- if (content.charCodeAt(i) >= 0x3000) cjk++;- }- const ratio = cjk / content.length;- const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;- return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));-}--async function readProfile(fetchJSON, profileUri, actorPeerId = "") {- const res = await fetchJSON(- `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,- {},- { actorPeerId },- );- if (!res.ok || typeof res.result !== "string") return null;- const trimmed = res.result.trim();- return trimmed || null;-}--/**- * Recursive ls of a memory directory, flattening to .md leaves.- *- * Memory layout under preferences/ and entities/ is two-level:- * <dir>/<owner_name>/<topic>.md- * so we use the server's recursive=true flag and filter to leaf .md files.- * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name- * to keep owner-namespacing visible and unambiguous when multiple owners exist.- */-async function lsDir(fetchJSON, dirUri, actorPeerId = "") {- const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;- const res = await fetchJSON(url, {}, { actorPeerId });- if (!res.ok || !Array.isArray(res.result)) return [];- return res.result- .filter((e) => !e.isDir)- .map((e) => {- const rel = typeof e.rel_path === "string" && e.rel_path- ? e.rel_path- : (typeof e.name === "string" ? e.name : "");- return {- name: rel,- abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",- };- })- .filter((e) => e.name && e.name.endsWith(".md"))- .sort((a, b) => a.name.localeCompare(b.name));-}--/**- * When profile exceeds its sub-cap, keep the head (identity block + first- * timeline events) and the tail (most-recent events), drop the middle. This- * preserves both stable identity facts (top of file) and most-recent activity- * (bottom of file) — only the noisy middle timeline is sacrificed.- *- * Layout:- * <first HEAD_LINES lines>- * ... [profile middle elided] ...- * <as many trailing lines as fit in remaining budget>- *- * Falls back to head-only truncate when the file is too short to elide- * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit- * both head and a useful tail.- */-function elideProfile(content, maxTokens) {- // Compute char budget from token budget using *this* content's CJK density,- // not chars/4 — otherwise the truncated string can still blow the token cap- // for CJK-heavy profiles (Copilot review point).- const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));- if (estimateTokens(content) <= maxTokens) return content;-- const HEAD_LINES = 8;- const ELLIPSIS = "\n... [profile middle elided] ...\n";- const lines = content.split("\n");-- const fallbackHeadTruncate = () =>- content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";-- if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();-- const head = lines.slice(0, HEAD_LINES).join("\n");- const reserveForTail = maxChars - head.length - ELLIPSIS.length;- if (reserveForTail < 200) return fallbackHeadTruncate();-- let tailChars = 0;- let tailStart = lines.length;- for (let i = lines.length - 1; i > HEAD_LINES; i--) {- const lineLen = lines[i].length + 1;- if (tailChars + lineLen > reserveForTail) break;- tailChars += lineLen;- tailStart = i;- }- if (tailStart >= lines.length - 1) return fallbackHeadTruncate();-- return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;-}--function formatListing(headerUri, entries, budgetTokens) {- if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };- // Header is the full directory URI; child lines are relative paths so the- // agent can reconstruct each leaf's full URI by concatenation while the- // listing itself stays compact.- const header = ` ${headerUri}/`;- const headerTokens = estimateTokens(header);- // If the header alone busts the budget, emit just a one-line stub instead- // of silently violating the cap (Copilot review point).- if (headerTokens > budgetTokens) {- const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;- return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };- }- const lines = [header];- let used = headerTokens;- for (let i = 0; i < entries.length; i++) {- const e = entries[i];- const desc = e.abstract- ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`- : "";- const line = ` - ${e.name}${desc}`;- const tokens = estimateTokens(line);- if (used + tokens > budgetTokens) {- const remaining = entries.length - i;- const tail = ` ... +${remaining} more, use \`memory_recall\``;- const tailTokens = estimateTokens(tail);- // Only emit the tail if it fits; otherwise the listing closes silently- // rather than violating the cap to advertise its own truncation.- if (used + tailTokens <= budgetTokens) {- lines.push(tail);- return { lines, used: used + tailTokens, dropped: remaining };- }- return { lines, used, dropped: remaining };- }- lines.push(line);- used += tokens;- }- return { lines, used, dropped: 0 };-}--/**- * Build the profile injection block.- *- * Returns null when neither profile.md nor either listing has any content.- * The returned `block` is just the inner <user-profile>/<available-memories>- * payload — the caller wraps it in <openviking-context source="...">.- *- * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure- * @param {number} totalBudgetTokens chars/4 budget, total for the whole block- * @returns {Promise<null | {- * block: string, chars: number, tokens: number, profileUri: string,- * profileChars: number, prefCount: number, entCount: number,- * droppedPref: number, droppedEnt: number,- * }>}- */-export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {- const space = await resolveUserSpace(fetchJSON, actorPeerId);- const profileUri = `viking://user/${space}/memories/profile.md`;- const prefUri = `viking://user/${space}/memories/preferences`;- const entUri = `viking://user/${space}/memories/entities`;-- const [profile, prefs, ents] = await Promise.all([- readProfile(fetchJSON, profileUri, actorPeerId),- lsDir(fetchJSON, prefUri, actorPeerId),- lsDir(fetchJSON, entUri, actorPeerId),- ]);-- if (!profile && prefs.length === 0 && ents.length === 0) return null;-- // Profile gets up to half the total budget; listings split the rest.- // Sub-cap protects against a runaway profile blowing the listing budget.- const profileBudget = Math.floor(totalBudgetTokens / 2);- const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;- const profileTokens = estimateTokens(profileTrunc || "");-- const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);- const halfListing = Math.floor(listingBudget / 2);- const prefBlock = formatListing(prefUri, prefs, halfListing);- const entBudget = Math.max(0, listingBudget - prefBlock.used);- const entBlock = formatListing(entUri, ents, entBudget);-- const lines = [];- if (profileTrunc) {- lines.push(`<user-profile uri="${profileUri}">`);- lines.push(profileTrunc);- lines.push(`</user-profile>`);- }- if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {- lines.push(`<available-memories>`);- lines.push(...prefBlock.lines);- lines.push(...entBlock.lines);- lines.push(`</available-memories>`);- }-- const block = lines.join("\n");- return {- block,- chars: block.length,- tokens: estimateTokens(block),- profileUri,- profileChars: profile?.length ?? 0,- prefCount: prefs.length,- entCount: ents.length,- droppedPref: prefBlock.dropped,- droppedEnt: entBlock.dropped,- };-}+export * from "../shared/profile-inject.mjs";diff --git a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjsindex f1f78c1ae..acbae51e5 100644--- a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs@@ -67,3 +67,16 @@ test("Claude hooks include optional skill experience PostToolUse Read hook", ());execFileSync("node", ["--check", join(pluginDir, "scripts", "skill-experience.mjs")], { stdio: "pipe" });});++test("Claude hooks include PreToolUse URI guard for filesystem tools", () => {+ const hooks = readJson(join(pluginDir, "hooks", "hooks.json"));+ const preToolUse = hooks.hooks?.PreToolUse;+ assert.ok(Array.isArray(preToolUse), "hooks.json must define PreToolUse hooks");+ const guardHook = preToolUse.find((entry) => entry?.matcher === "Read|Glob|Grep");+ assert.ok(guardHook, "PreToolUse must guard Read|Glob|Grep");+ assert.equal(+ guardHook.hooks?.[0]?.command,+ "node ${CLAUDE_PLUGIN_ROOT}/scripts/uri-guard.mjs",+ );+ execFileSync("node", ["--check", join(pluginDir, "scripts", "uri-guard.mjs")], { stdio: "pipe" });+});diff --git a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjsindex 4ad0314bf..3a1fb1fec 100644--- a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs@@ -72,6 +72,17 @@ function stringifyCompact(value, maxChars) {}}+function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}+function blockText(block) {if (!block || typeof block !== "object") return "";if (typeof block.text === "string") return block.text;@@ -115,6 +126,51 @@ function toolPayload(block, kind) {"";}+function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}+function formatToolBlock(block, kind, maxChars) {const name = toolName(block);const payload = toolPayload(block, kind);@@ -193,6 +249,121 @@ export function extractTextFromPayload(payload, options = {}) {return chunks.join("\n\n");}+function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}+export function normalizeCaptureRole(role) {const value = normalizeType(role);if (value === "user") return "user";diff --git a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjsindex 4513d57a9..76b30fb8e 100644--- a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs@@ -95,13 +95,24 @@ function sourceMode(env) {return "auto";}-function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+function hasEnvCredentialFields(env) {+ return Boolean(+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||+ str(env.OPENVIKING_MCP_URL, "") ||+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(env.OPENVIKING_USER, "") ||+ str(env.OPENVIKING_PEER_ID, ""),+ );+}++function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));const cliUrl = str(cliFile.url, "");+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");- if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");- if (!useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");const server = ovFile.server || {};const ovUrl = str(server.url, "");@@ -115,11 +126,13 @@ function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {export function resolveOpenVikingCredentials(env = process.env) {const files = loadCredentialFiles(env);const mode = sourceMode(env);- const useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const envHasCredentials = hasEnvCredentialFields(env);+ const useCli = mode === "cli" ||+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));const cx = files.ovFile.codex || {};const server = files.ovFile.server || {};- const baseUrl = deriveBaseUrl({ env, ...files, useCli });+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });const apiKey = useCli? str(files.cliFile.api_key, "")@@ -156,11 +169,11 @@ export function resolveOpenVikingCredentials(env = process.env) {);const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");- const mcpUrl = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;return {...files,- credentialSource: useCli ? "ovcli" : (mode === "env" ? "env" : "auto"),+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),baseUrl,mcpUrl,apiKey,diff --git a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjsindex 754771d22..cbf6d445f 100644--- a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs@@ -397,7 +397,7 @@ export async function replayPending(fetchJSON, log) {} else if (entry.type === "commitSession") {res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {method: "POST",- body: JSON.stringify({}),+ body: JSON.stringify(entry.payload || {}),});} else {await dequeue(claimedFilename);diff --git a/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjsnew file mode 100644index 000000000..3f601844a--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs@@ -0,0 +1,294 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url, {}, { actorPeerId });+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjsnew file mode 100644index 000000000..445f00b1a--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs@@ -0,0 +1,282 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },+];++let userSpaceCache = "";++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);+ return {+ query: "",+ quotas: {+ events: limit,+ entities: limit,+ preferences: Math.max(1, Math.min(limit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (userSpaceCache) return userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ if (items.length === 0) return null;++ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),+ });++ return lines.join("\n");+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}++export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return null;++ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);+ if (endpointBlock !== null) return endpointBlock || null;++ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return null;++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return null;+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}diff --git a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjsnew file mode 100644index 000000000..9505ddb5e--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs@@ -0,0 +1,56 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+ "pattern",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args);+}++export function findVikingUriInValue(value) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}diff --git a/examples/claude-code-memory-plugin/scripts/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/uri-guard.mjsnew file mode 100644index 000000000..c5c89ebc2--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/uri-guard.mjs@@ -0,0 +1,59 @@+#!/usr/bin/env node++import { readFileSync } from "node:fs";+import { buildGuardMessage, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs";++const TOOL_HINTS = {+ read: {+ tool: "OpenViking MCP read",+ example: (uri) => `read(uris="${uri}")`,+ },+ glob: {+ tool: "OpenViking MCP glob or list",+ example: (uri, input = {}) => `glob(pattern="${String(input.pattern ?? "**/*").replaceAll('"', '\\"')}", uri="${uri}")`,+ },+ grep: {+ tool: "OpenViking MCP grep or search",+ example: (uri, input = {}) => `grep(uri="${uri}", pattern="${String(input.pattern ?? "").replaceAll('"', '\\"')}")`,+ },+};++export function evaluatePreToolUse(input = {}) {+ const toolName = normalizeToolName(input.tool_name ?? input.toolName ?? input.name ?? input.tool);+ const hint = TOOL_HINTS[toolName];+ if (!hint) return {};++ const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};+ const uri = findVikingUri(toolInput);+ if (!uri) return {};++ return {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: buildGuardMessage(uri, {+ tool: hint.tool,+ example: hint.example(uri, toolInput),+ }),+ },+ };+}++function main() {+ let payload = {};+ try {+ const raw = readFileSync(0, "utf8").trim();+ if (raw) payload = JSON.parse(raw);+ } catch {+ payload = {};+ }++ const out = evaluatePreToolUse(payload);+ if (Object.keys(out).length > 0) {+ process.stdout.write(`${JSON.stringify(out)}\n`);+ }+}++if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {+ main();+}diff --git a/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs b/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjsnew file mode 100644index 000000000..4b130a3be--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs@@ -0,0 +1,19 @@+import test from "node:test";+import assert from "node:assert/strict";+import { evaluatePreToolUse } from "./uri-guard.mjs";++test("Claude URI guard denies filesystem Read on viking URI", () => {+ const out = evaluatePreToolUse({+ tool_name: "Read",+ tool_input: { file_path: "viking://resources/project/file.md" },+ });++ assert.equal(out.hookSpecificOutput?.hookEventName, "PreToolUse");+ assert.equal(out.hookSpecificOutput?.permissionDecision, "deny");+ assert.match(out.hookSpecificOutput?.permissionDecisionReason ?? "", /OpenViking MCP read/);+});++test("Claude URI guard allows local paths and unrelated tools", () => {+ assert.deepEqual(evaluatePreToolUse({ tool_name: "Read", tool_input: { file_path: "/tmp/a.md" } }), {});+ assert.deepEqual(evaluatePreToolUse({ tool_name: "Bash", tool_input: { command: "cat viking://resources/a.md" } }), {});+});diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.jsonindex 729409603..4d72e9ed3 100644--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openviking-memory",- "version": "0.6.0",+ "version": "0.7.0","description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on PreCompact, and active-window heuristic + idle-TTL sweep on SessionStart (source=startup|clear). Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.","author": {"name": "OpenViking",diff --git a/examples/codex-memory-plugin/scripts/capture-utils.mjs b/examples/codex-memory-plugin/scripts/capture-utils.mjsindex 0eae451ed..0d3b81e5d 100644--- a/examples/codex-memory-plugin/scripts/capture-utils.mjs+++ b/examples/codex-memory-plugin/scripts/capture-utils.mjs@@ -1,499 +1 @@-const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);-const TOOL_CALL_TYPES = new Set([- "tool_call",- "toolcall",- "tool_use",- "tooluse",- "function_call",- "functioncall",-]);-const TOOL_RESULT_TYPES = new Set([- "tool_result",- "toolresult",- "tool_output",- "tooloutput",- "function_call_output",- "functioncalloutput",-]);--const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;-const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;-const METADATA_KEYS = [- "session_id",- "sessionid",- "sessionkey",- "conversation_id",- "conversationid",- "channel",- "sender",- "user_id",- "userid",- "agent_id",- "agentid",- "timestamp",- "timezone",- "cwd",- "model",- "permission_mode",-];--function normalizeType(value) {- return String(value || "").toLowerCase().replace(/[-\s]/g, "_");-}--function isToolCallBlock(block) {- const type = normalizeType(block?.type || block?.kind || block?.role);- return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);-}--function isToolResultBlock(block) {- const type = normalizeType(block?.type || block?.kind || block?.role);- return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";-}--function oneLine(text) {- return String(text || "").replace(/\s+/g, " ").trim();-}--export function truncateCaptureText(text, maxChars = 2000) {- const value = String(text || "").trim();- if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;- return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;-}--function stringifyCompact(value, maxChars) {- if (value == null) return "";- if (typeof value === "string") return truncateCaptureText(value, maxChars);- try {- return truncateCaptureText(JSON.stringify(value), maxChars);- } catch {- return truncateCaptureText(String(value), maxChars);- }-}--function parseMaybeJson(value) {- if (value == null || typeof value !== "string") return value;- const trimmed = value.trim();- if (!trimmed) return value;- try {- return JSON.parse(trimmed);- } catch {- return value;- }-}--function blockText(block) {- if (!block || typeof block !== "object") return "";- if (typeof block.text === "string") return block.text;- if (typeof block.output_text === "string") return block.output_text;- if (typeof block.input_text === "string") return block.input_text;- if (typeof block.content === "string") return block.content;- return "";-}--function toolName(block) {- return oneLine(- block?.name ||- block?.tool_name ||- block?.toolName ||- block?.function?.name ||- block?.call?.name ||- block?.id ||- "",- );-}--function toolPayload(block, kind) {- if (!block || typeof block !== "object") return "";- if (kind === "call") {- return block.input ??- block.arguments ??- block.args ??- block.params ??- block.function?.arguments ??- block.command ??- block.call?.input ??- block.call?.arguments ??- "";- }- return block.output ??- block.result ??- block.error ??- block.data ??- block.content ??- block.text ??- "";-}--function toolId(block) {- return oneLine(- block?.id ||- block?.call_id ||- block?.callId ||- block?.tool_call_id ||- block?.toolCallId ||- block?.tool_use_id ||- block?.toolUseId ||- block?.function_call_id ||- block?.functionCallId ||- "",- );-}--function toolStatus(block, kind) {- if (kind === "call") return "running";- if (block?.is_error || block?.error) return "error";- const status = oneLine(block?.status || "");- return status || "completed";-}--function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {- const id = toolId(block);- const name = toolName(block) || (id ? toolNameById[id] : "");- const payload = toolPayload(block, kind);- const part = {- type: "tool",- tool_id: id || undefined,- tool_name: name || undefined,- tool_status: toolStatus(block, kind),- };- if (kind === "call") {- const input = parseMaybeJson(payload);- if (input !== "" && input != null) {- part.tool_input = typeof input === "object" && !Array.isArray(input)- ? input- : { value: input };- }- } else {- part.tool_output = stringifyCompact(payload, toolMaxChars);- }- return part;-}--function formatToolBlock(block, kind, maxChars) {- const name = toolName(block);- const payload = toolPayload(block, kind);- const body = oneLine(stringifyCompact(payload, maxChars));- const label = kind === "call" ? "tool-call" : "tool-result";- return body- ? `[${label}${name ? ` ${name}` : ""}] ${body}`- : `[${label}${name ? ` ${name}` : ""}]`;-}--function blockToText(block, options) {- if (!block) return "";- if (typeof block === "string") return block;- if (Array.isArray(block)) return extractTextFromContent(block, options);- if (typeof block !== "object") return "";-- if (block.item && typeof block.item === "object") {- const itemText = blockToText(block.item, options);- if (itemText) return itemText;- }-- const type = normalizeType(block.type || block.kind || block.role);- if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);- if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);- if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);- if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);- if (!type) return blockText(block);- return "";-}--export function extractTextFromContent(content, options = {}) {- const opts = { toolMaxChars: 2000, ...options };- if (!content) return "";- if (typeof content === "string") return content;- if (Array.isArray(content)) {- return content- .map((block) => blockToText(block, opts))- .filter(Boolean)- .join("\n\n");- }- if (typeof content === "object") {- return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);- }- return "";-}--export function extractTextFromPayload(payload, options = {}) {- if (!payload || typeof payload !== "object") return "";- const chunks = [];- const directType = normalizeType(payload.type || payload.kind || payload.role);- if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });- if (direct) return direct;- }-- if (payload.message && typeof payload.message === "object") {- const messageText = extractTextFromPayload(payload.message, options);- if (messageText) chunks.push(messageText);- } else if (payload.content !== undefined) {- const contentText = extractTextFromContent(payload.content, options);- if (contentText) chunks.push(contentText);- }-- for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {- const value = payload[key];- if (!value) continue;- const toolText = extractTextFromContent(value, options);- if (toolText) chunks.push(toolText);- }-- if (chunks.length === 0) {- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });- if (direct) chunks.push(direct);- }-- return chunks.join("\n\n");-}--function collectToolNamesByIdFromEntries(entries) {- const map = {};- for (const entry of entries || []) {- const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;- collectToolNamesByIdFromPayload(payload, map);- }- return map;-}--function collectToolNamesByIdFromPayload(payload, out) {- if (!payload || typeof payload !== "object") return;- if (payload.message && typeof payload.message === "object") {- collectToolNamesByIdFromPayload(payload.message, out);- }- const candidates = [];- if (Array.isArray(payload.content)) candidates.push(...payload.content);- for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {- const value = payload[key];- if (!value) continue;- if (Array.isArray(value)) candidates.push(...value);- else candidates.push(value);- }- if (isToolCallBlock(payload)) candidates.push(payload);- for (const block of candidates) {- if (!block || typeof block !== "object") continue;- if (!isToolCallBlock(block)) continue;- const id = toolId(block);- const name = toolName(block);- if (id && name) out[id] = name;- }-}--function extractPartsFromContent(content, options = {}) {- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };- const parts = [];- if (!content) return parts;- if (typeof content === "string") {- if (content.trim()) parts.push({ type: "text", text: content });- return parts;- }- if (!Array.isArray(content)) {- const text = blockToText(content, opts);- if (text.trim()) parts.push({ type: "text", text });- return parts;- }- for (const block of content) {- if (!block || typeof block !== "object") continue;- if (isToolCallBlock(block)) {- parts.push(buildToolPart(block, "call", opts));- } else if (isToolResultBlock(block)) {- parts.push(buildToolPart(block, "result", opts));- } else {- const text = blockToText(block, opts);- if (text.trim()) parts.push({ type: "text", text });- }- }- return parts;-}--export function extractPartsFromPayload(payload, options = {}) {- if (!payload || typeof payload !== "object") return [];- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };- if (payload.message && typeof payload.message === "object") {- return extractPartsFromPayload(payload.message, opts);- }-- const directType = normalizeType(payload.type || payload.kind || payload.role);- if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {- return [buildToolPart(payload, "call", opts)];- }- if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {- return [buildToolPart(payload, "result", opts)];- }-- const parts = [];- if (payload.content !== undefined) {- parts.push(...extractPartsFromContent(payload.content, opts));- }- for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {- const value = payload[key];- if (!value) continue;- if (Array.isArray(value)) {- for (const block of value) parts.push(...extractPartsFromPayload(block, opts));- } else {- parts.push(...extractPartsFromPayload(value, opts));- }- }- return parts;-}--export function extractCaptureTurns(rolloutEntries, cfg = {}) {- const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);- const turns = [];- for (const entry of rolloutEntries || []) {- if (!entry || typeof entry !== "object") continue;- const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;- const message = payload.message && typeof payload.message === "object" ? payload.message : null;- const rawRole = message?.role || payload.role || payload.type || payload.kind;- const role = normalizeCaptureRole(rawRole);- if (!role) continue;- if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;-- const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });- const parts = extractPartsFromPayload(payload, {- toolMaxChars: cfg.captureToolMaxChars,- toolNameById,- });- const decision = shouldCaptureText(rawText, role, cfg);- if (!decision.shouldCapture && parts.length === 0) continue;- const text = decision.shouldCapture ? decision.text : "";- turns.push({ role, text, parts });- }- return turns;-}--export function normalizeCaptureRole(role) {- const value = normalizeType(role);- if (value === "user") return "user";- if (value === "assistant") return "assistant";- if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {- return "user";- }- if (value === "tool_call" || value === "function_call") return "assistant";- return null;-}--export function isAssistantSideCaptureRole(role) {- const value = normalizeType(role);- return value === "assistant" ||- value === "tool" ||- value === "tool_result" ||- value === "tool_call" ||- value === "function" ||- value === "function_call" ||- value === "function_call_output";-}--function stripMetadataFences(text) {- return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {- const lower = body.toLowerCase();- let hits = 0;- for (const key of METADATA_KEYS) {- const re = new RegExp(`["']?${key}["']?\\s*:`, "i");- if (re.test(lower)) hits += 1;- }- return hits >= 3 ? "" : match;- });-}--function stripInjectedDigestBlocks(text) {- const lines = String(text || "").split(/\r?\n/);- const out = [];- let skipping = false;- let skipUntilMcpHint = false;-- for (const line of lines) {- const trimmed = line.trim();- if (/^OpenViking session archive digest:/i.test(trimmed)) {- skipping = true;- skipUntilMcpHint = true;- continue;- }- if (/^OpenViking memory digest:/i.test(trimmed)) {- skipping = true;- skipUntilMcpHint = false;- continue;- }- if (skipping) {- if (skipUntilMcpHint) {- if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {- skipping = false;- skipUntilMcpHint = false;- }- continue;- }- if (!trimmed) {- skipping = false;- continue;- }- if (- /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||- /^\s{2,}\S/.test(line)- ) {- continue;- }- skipping = false;- }- out.push(line);- }-- return out.join("\n");-}--export function sanitizeCapturedText(text) {- let value = String(text || "");- value = value- .replace(/\u0000/g, "")- .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")- .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")- .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")- .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")- .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")- .replace(/^\s*\d{10,13}\s+/gm, "");- value = stripMetadataFences(value);- value = stripInjectedDigestBlocks(value);- value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");- return value- .replace(/[ \t]+\n/g, "\n")- .replace(/\n{3,}/g, "\n\n")- .trim();-}--function hasEnoughSignal(text) {- const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;- const alnum = text.match(/[a-z0-9]/gi)?.length || 0;- return cjk >= 4 || alnum >= 6 || text.length >= 12;-}--function isPunctuationOnly(text) {- return !/[a-z0-9\u3400-\u9fff]/i.test(text);-}--export function shouldCaptureText(text, role, cfg = {}) {- const maxLength = cfg.captureMaxLength || 24000;- const sanitized = sanitizeCapturedText(text);- if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };-- const capped = truncateCaptureText(sanitized, maxLength);- const compact = oneLine(capped);- const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);-- if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {- return { shouldCapture: false, reason: "slash_command", text: "" };- }- if (!isToolSummary && ACK_RE.test(compact)) {- return { shouldCapture: false, reason: "ack", text: "" };- }- if (!isToolSummary && isPunctuationOnly(compact)) {- return { shouldCapture: false, reason: "punctuation", text: "" };- }- if (!isToolSummary && !hasEnoughSignal(compact)) {- return { shouldCapture: false, reason: "too_short", text: "" };- }- if (/^\[openviking-memory\]/i.test(compact)) {- return { shouldCapture: false, reason: "plugin_status", text: "" };- }-- return { shouldCapture: true, reason: "ok", text: capped };-}+export * from "./shared/capture-utils.mjs";diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjsindex f38c04131..ef64effec 100644--- a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs+++ b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs@@ -12,7 +12,7 @@ async function tempJson(prefix, value) {return { dir, path };}-test("active ovcli config wins over stale credential env by default", async () => {+test("credential env wins over ovcli config by default", async () => {const { dir, path } = await tempJson("ov-creds-cli-", {url: "https://ov.example.com",api_key: "cli-key",@@ -31,13 +31,13 @@ test("active ovcli config wins over stale credential env by default", async () =OPENVIKING_PEER_ID: "stale-peer",});- assert.equal(creds.credentialSource, "ovcli");- assert.equal(creds.baseUrl, "https://ov.example.com");- assert.equal(creds.mcpUrl, "https://ov.example.com/mcp");- assert.equal(creds.apiKey, "cli-key");- assert.equal(creds.account, "default");- assert.equal(creds.user, "zeus");- assert.equal(creds.peerId, "peer-a");+ assert.equal(creds.credentialSource, "env");+ assert.equal(creds.baseUrl, "https://stale.example.com");+ assert.equal(creds.mcpUrl, "https://stale.example.com/mcp");+ assert.equal(creds.apiKey, "stale-key");+ assert.equal(creds.account, "stale-account");+ assert.equal(creds.user, "stale-user");+ assert.equal(creds.peerId, "stale-peer");} finally {await rm(dir, { recursive: true, force: true });}@@ -73,13 +73,14 @@ test("env source can be forced explicitly", async () => {}});-test("ovcli config without api_key does not inherit stale env key", async () => {+test("ovcli source can be forced explicitly without inheriting env key", async () => {const { dir, path } = await tempJson("ov-creds-noauth-", {url: "http://127.0.0.1:1933",});try {const creds = resolveOpenVikingCredentials({OPENVIKING_CLI_CONFIG_FILE: path,+ OPENVIKING_CREDENTIAL_SOURCE: "ovcli",OPENVIKING_API_KEY: "stale-key",});diff --git a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjsindex 4ad0314bf..3a1fb1fec 100644--- a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs+++ b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs@@ -72,6 +72,17 @@ function stringifyCompact(value, maxChars) {}}+function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}+function blockText(block) {if (!block || typeof block !== "object") return "";if (typeof block.text === "string") return block.text;@@ -115,6 +126,51 @@ function toolPayload(block, kind) {"";}+function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}+function formatToolBlock(block, kind, maxChars) {const name = toolName(block);const payload = toolPayload(block, kind);@@ -193,6 +249,121 @@ export function extractTextFromPayload(payload, options = {}) {return chunks.join("\n\n");}+function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}+export function normalizeCaptureRole(role) {const value = normalizeType(role);if (value === "user") return "user";diff --git a/examples/codex-memory-plugin/scripts/shared/credentials.mjs b/examples/codex-memory-plugin/scripts/shared/credentials.mjsindex 4513d57a9..76b30fb8e 100644--- a/examples/codex-memory-plugin/scripts/shared/credentials.mjs+++ b/examples/codex-memory-plugin/scripts/shared/credentials.mjs@@ -95,13 +95,24 @@ function sourceMode(env) {return "auto";}-function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+function hasEnvCredentialFields(env) {+ return Boolean(+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||+ str(env.OPENVIKING_MCP_URL, "") ||+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(env.OPENVIKING_USER, "") ||+ str(env.OPENVIKING_PEER_ID, ""),+ );+}++function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));const cliUrl = str(cliFile.url, "");+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");- if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");- if (!useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");const server = ovFile.server || {};const ovUrl = str(server.url, "");@@ -115,11 +126,13 @@ function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {export function resolveOpenVikingCredentials(env = process.env) {const files = loadCredentialFiles(env);const mode = sourceMode(env);- const useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const envHasCredentials = hasEnvCredentialFields(env);+ const useCli = mode === "cli" ||+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));const cx = files.ovFile.codex || {};const server = files.ovFile.server || {};- const baseUrl = deriveBaseUrl({ env, ...files, useCli });+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });const apiKey = useCli? str(files.cliFile.api_key, "")@@ -156,11 +169,11 @@ export function resolveOpenVikingCredentials(env = process.env) {);const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");- const mcpUrl = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;return {...files,- credentialSource: useCli ? "ovcli" : (mode === "env" ? "env" : "auto"),+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),baseUrl,mcpUrl,apiKey,diff --git a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjsindex 754771d22..cbf6d445f 100644--- a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs+++ b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs@@ -397,7 +397,7 @@ export async function replayPending(fetchJSON, log) {} else if (entry.type === "commitSession") {res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {method: "POST",- body: JSON.stringify({}),+ body: JSON.stringify(entry.payload || {}),});} else {await dequeue(claimedFilename);diff --git a/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjsnew file mode 100644index 000000000..3f601844a--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs@@ -0,0 +1,294 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url, {}, { actorPeerId });+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs b/examples/codex-memory-plugin/scripts/shared/recall-core.mjsnew file mode 100644index 000000000..445f00b1a--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs@@ -0,0 +1,282 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },+];++let userSpaceCache = "";++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);+ return {+ query: "",+ quotas: {+ events: limit,+ entities: limit,+ preferences: Math.max(1, Math.min(limit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (userSpaceCache) return userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ if (items.length === 0) return null;++ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),+ });++ return lines.join("\n");+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}++export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return null;++ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);+ if (endpointBlock !== null) return endpointBlock || null;++ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return null;++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return null;+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}diff --git a/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs b/examples/codex-memory-plugin/scripts/shared/uri-guard.mjsnew file mode 100644index 000000000..9505ddb5e--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs@@ -0,0 +1,56 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+ "pattern",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args);+}++export function findVikingUriInValue(value) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}diff --git a/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjsnew file mode 100644index 000000000..8f4881826--- /dev/null+++ b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs@@ -0,0 +1,88 @@+import test from "node:test"+import assert from "node:assert/strict"+import { execFile } from "node:child_process"+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"+import { tmpdir } from "node:os"+import { dirname, join, resolve } from "node:path"+import { fileURLToPath } from "node:url"++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..")+const installer = join(repoRoot, "examples", "memory-plugin-shared", "install.sh")++async function withTempDir(prefix, fn) {+ const dir = await mkdtemp(join(tmpdir(), prefix))+ try {+ return await fn(dir)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+}++function runInstaller(args, options) {+ return new Promise((resolve, reject) => {+ execFile("bash", [installer, ...args], options, (error, stdout, stderr) => {+ if (error) {+ error.stdout = stdout+ error.stderr = stderr+ reject(error)+ } else {+ resolve({ stdout, stderr })+ }+ })+ })+}++test("OpenCode installer preserves JSONC comments while adding MCP config", async () => {+ await withTempDir("ov-opencode-jsonc-", async (dir) => {+ const home = join(dir, "home")+ const bin = join(dir, "bin")+ const configDir = join(home, ".config", "opencode")+ await mkdir(bin, { recursive: true })+ await mkdir(configDir, { recursive: true })++ const opencode = join(bin, "opencode")+ await writeFile(opencode, "#!/usr/bin/env sh\nprintf 'opencode 0.0.0-test\\n'\n")+ await chmod(opencode, 0o755)++ const configPath = join(configDir, "opencode.jsonc")+ await writeFile(configPath, [+ "{",+ " // keep this user note",+ " \"theme\": \"system\",",+ " /* keep this block note */",+ " \"mcp\": {",+ " // keep this mcp note",+ " \"other\": { \"type\": \"local\", \"command\": [\"node\", \"other.js\"] }",+ " }",+ "}",+ "",+ ].join("\n"))++ await runInstaller([+ "--harness", "opencode",+ "--source", "dev",+ "--dist", "github",+ "--lang", "en",+ "--url", "http://127.0.0.1:1933",+ "--api-key", "",+ "--yes",+ ], {+ cwd: repoRoot,+ env: {+ ...process.env,+ HOME: home,+ OPENVIKING_HOME: join(home, ".openviking"),+ PATH: `${bin}:${process.env.PATH}`,+ },+ })++ const raw = await readFile(configPath, "utf8")+ assert.match(raw, /keep this user note/)+ assert.match(raw, /keep this block note/)+ assert.match(raw, /keep this mcp note/)+ assert.match(raw, /"theme": "system"/)+ assert.match(raw, /"other": \{ "type": "local"/)+ assert.match(raw, /"openviking"/)+ assert.match(raw, /servers\/mcp-proxy\.mjs/)+ })+})diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex 39087fd1d..cd62fa2a6 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -1,13 +1,16 @@#!/usr/bin/env bash#-# OpenViking Memory Plugin shared installer for Claude Code and Codex.+# OpenViking Memory Plugin shared installer for Claude Code, Codex, OpenCode, and pi.## One-liner (GitHub):# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)# One-liner (TOS mirror, for regions where GitHub is unreachable):# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos# Non-interactive:-# bash install.sh --harness claude,codex --dist github --lang en --url http://127.0.0.1:1933 --api-key ''+# bash install.sh --harness claude,codex,opencode,pi --dist github --lang en --url http://127.0.0.1:1933 --api-key ''+# Format-compatible CLI aliases:+# bash install.sh --harness codex --codex-bin codex,traex+# bash install.sh --harness claude --claude-bin claude,seed# Fork / branch verification:# OPENVIKING_REPO_URL=https://github.com/you/OpenViking.git \# OPENVIKING_REPO_REF=my-branch bash install.sh --source remote@@ -75,6 +78,8 @@ CC_REMOTE_MKT_DIR="$OV_HOME/marketplaces/openviking-claude"CC_REMOTE_MANIFEST="$CC_REMOTE_MKT_DIR/.claude-plugin/marketplace.json"REQUESTED_HARNESSES=""+CLAUDE_BINS_ARG="${OPENVIKING_CLAUDE_BINS:-${OPENVIKING_CLAUDE_BIN:-}}"+CODEX_BINS_ARG="${OPENVIKING_CODEX_BINS:-${OPENVIKING_CODEX_BIN:-}}"SOURCE_ARG=""DIST_ARG=""LANG_ARG=""@@ -116,7 +121,9 @@ usage() {Usage: install.sh [options]Options:- --harness LIST Comma-separated harnesses: claude, codex, or both.+ --harness LIST Comma-separated harnesses: claude, codex, opencode, pi, or any combination.+ --claude-bin LIST Comma-separated Claude-format CLI commands (default: claude).+ --codex-bin LIST Comma-separated Codex-format CLI commands (default: codex).--dist CHANNEL github (default) | tos (mirror for GitHub-blocked regions).--lang LANG en | zh (interactive prompts language; auto-detected).--source MODE Advanced: remote | archive | dev (default: auto-detect).@@ -133,6 +140,8 @@ EOFwhile [ "$#" -gt 0 ]; docase "$1" in--harness) REQUESTED_HARNESSES="${2:-}"; shift 2 ;;+ --claude-bin|--claude-bins) CLAUDE_BINS_ARG="${2:-}"; shift 2 ;;+ --codex-bin|--codex-bins) CODEX_BINS_ARG="${2:-}"; shift 2 ;;--dist) DIST_ARG="${2:-}"; shift 2 ;;--lang) LANG_ARG="${2:-}"; shift 2 ;;--source) SOURCE_ARG="${2:-}"; shift 2 ;;@@ -277,6 +286,79 @@ split_harnesses() {done}+split_csv_list() {+ printf '%s\n' "$1" | tr ',' '\n' | while IFS= read -r item; do+ item=$(printf '%s' "$item" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')+ [ -n "$item" ] && printf '%s\n' "$item"+ done+}++normalize_bin_list() { # normalize_bin_list <raw-list> <default-command>+ local raw="${1:-}" def="$2"+ [ -n "$raw" ] || raw="$def"+ split_csv_list "$raw"+}++append_csv_list() { # append_csv_list <existing-lines> <extra-csv>+ local existing="$1" extra="$2" item out=""+ while IFS= read -r item; do+ [ -n "$item" ] || continue+ list_contains_line "$out" "$item" || out="${out:+$out+}$item"+ done <<EOF+$existing+$(split_csv_list "$extra")+EOF+ printf '%s\n' "$out"+}++list_contains_line() {+ local list="$1" want="$2" item+ while IFS= read -r item; do+ [ "$item" = "$want" ] && return 0+ done <<EOF+$list+EOF+ return 1+}++list_words() {+ local item out=""+ while IFS= read -r item; do+ [ -n "$item" ] || continue+ out="${out:+$out }$item"+ done <<EOF+$1+EOF+ printf '%s' "$out"+}++has_available_bin() {+ local bins="$1" bin+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ command -v "$bin" >/dev/null 2>&1 && return 0+ done <<EOF+$bins+EOF+ return 1+}++refresh_available_harnesses() {+ HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_OPENCODE=0; HAVE_PI=0+ has_available_bin "$CLAUDE_BINS" && HAVE_CLAUDE=1+ has_available_bin "$CODEX_BINS" && HAVE_CODEX=1+ command -v opencode >/dev/null 2>&1 && HAVE_OPENCODE=1+ command -v pi >/dev/null 2>&1 && HAVE_PI=1+ return 0+}++bin_basename() {+ local bin="$1"+ bin="${bin##*/}"+ printf '%s' "$bin"+}+contains_harness() {local want="$1" hwhile IFS= read -r h; do@@ -331,78 +413,371 @@ NODE# Harness selection (checkbox TUI on a tty, text fallback otherwise)# ----------------------------------------------------------------------------HAVE_CLAUDE=0; HAVE_CODEX=0-command -v claude >/dev/null 2>&1 && HAVE_CLAUDE=1-command -v codex >/dev/null 2>&1 && HAVE_CODEX=1+CLAUDE_BINS="$(normalize_bin_list "$CLAUDE_BINS_ARG" claude)"+CODEX_BINS="$(normalize_bin_list "$CODEX_BINS_ARG" codex)"++HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_OPENCODE=0; HAVE_PI=0+refresh_available_harnesses++TUI_CLAUDE_BINS="$CLAUDE_BINS"+TUI_CODEX_BINS="$CODEX_BINS"+SEL_CLAUDE_BINS=""+SEL_CODEX_BINS=""+SEL_OPENCODE=0+SEL_PI=0+TUI_CURSOR=0; TUI_LINES=0++list_count() {+ local list="$1" item n=0+ while IFS= read -r item; do+ [ -n "$item" ] && n=$((n + 1))+ done <<EOF+$list+EOF+ printf '%s' "$n"+}++tui_selectable_count() {+ printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 2 ))+}-SEL_CLAUDE=0; SEL_CODEX=0; TUI_CURSOR=0; TUI_LINES=0+tui_total_count() {+ printf '%s' $(( $(tui_selectable_count) + 1 ))+}-tui_item_line() { # tui_item_line <index> <selected> <label> <detected>- local mark='[ ]' cur=' ' note=''- [ "$2" -eq 1 ] && mark="[${GREEN}x${RESET}]"- [ "$TUI_CURSOR" -eq "$1" ] && cur="${CYAN}>${RESET} "- if [ "$4" -eq 1 ]; then+tui_item_at() { # tui_item_at <index> -> kind|bin, or add|+ local idx="$1" i=0 bin+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if [ "$i" -eq "$idx" ]; then printf 'claude|%s' "$bin"; return 0; fi+ i=$((i + 1))+ done <<EOF+$TUI_CLAUDE_BINS+EOF+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if [ "$i" -eq "$idx" ]; then printf 'codex|%s' "$bin"; return 0; fi+ i=$((i + 1))+ done <<EOF+$TUI_CODEX_BINS+EOF+ if [ "$i" -eq "$idx" ]; then printf 'opencode|opencode'; return 0; fi+ i=$((i + 1))+ if [ "$i" -eq "$idx" ]; then printf 'pi|pi'; return 0; fi+ printf 'add|'+}++tui_find_bin_index() { # tui_find_bin_index <kind> <bin>+ local want_kind="$1" want_bin="$2" idx=0 spec kind bin total+ total="$(tui_selectable_count)"+ while [ "$idx" -lt "$total" ]; do+ spec="$(tui_item_at "$idx")"+ kind="${spec%%|*}"+ bin="${spec#*|}"+ if [ "$kind" = "$want_kind" ] && [ "$bin" = "$want_bin" ]; then+ printf '%s' "$idx"+ return 0+ fi+ idx=$((idx + 1))+ done+ printf '0'+}++tui_bin_label() {+ local kind="$1" bin="$2"+ case "$kind:$bin" in+ claude:claude) printf 'Claude Code' ;;+ codex:codex) printf 'Codex' ;;+ opencode:*) printf 'OpenCode' ;;+ pi:*) printf 'pi' ;;+ claude:*) printf '%s %s' "$bin" "$(t '(Claude-format)' '(Claude 格式)')" ;;+ codex:*) printf '%s %s' "$bin" "$(t '(Codex-format)' '(Codex 格式)')" ;;+ esac+}++tui_bin_selected() {+ local kind="$1" bin="$2"+ if [ "$kind" = "claude" ]; then+ list_contains_line "$SEL_CLAUDE_BINS" "$bin"+ elif [ "$kind" = "codex" ]; then+ list_contains_line "$SEL_CODEX_BINS" "$bin"+ elif [ "$kind" = "opencode" ]; then+ [ "$SEL_OPENCODE" -eq 1 ]+ else+ [ "$SEL_PI" -eq 1 ]+ fi+}++tui_bin_detected() {+ command -v "$1" >/dev/null 2>&1+}++tui_set_all_bins() {+ SEL_CLAUDE_BINS="$TUI_CLAUDE_BINS"+ SEL_CODEX_BINS="$TUI_CODEX_BINS"+ SEL_OPENCODE=1+ SEL_PI=1+}++tui_toggle_bin() {+ local kind="$1" bin="$2" item out="" selected+ if [ "$kind" = "claude" ]; then+ selected="$SEL_CLAUDE_BINS"+ elif [ "$kind" = "codex" ]; then+ selected="$SEL_CODEX_BINS"+ elif [ "$kind" = "opencode" ]; then+ SEL_OPENCODE=$((1 - SEL_OPENCODE))+ return 0+ else+ SEL_PI=$((1 - SEL_PI))+ return 0+ fi+ if list_contains_line "$selected" "$bin"; then+ while IFS= read -r item; do+ [ -n "$item" ] || continue+ [ "$item" = "$bin" ] && continue+ out="${out:+$out+}$item"+ done <<EOF+$selected+EOF+ else+ out="$(append_csv_list "$selected" "$bin")"+ fi+ if [ "$kind" = "claude" ]; then+ SEL_CLAUDE_BINS="$out"+ else+ SEL_CODEX_BINS="$out"+ fi+}++tui_item_line() { # tui_item_line <index> <kind> <bin>+ local idx="$1" kind="$2" bin="$3" mark='[ ]' cur=' ' note='' label+ label="$(tui_bin_label "$kind" "$bin")"+ tui_bin_selected "$kind" "$bin" && mark="[${GREEN}x${RESET}]"+ [ "$TUI_CURSOR" -eq "$idx" ] && cur="${CYAN}>${RESET} "+ if tui_bin_detected "$bin"; thennote=" ${GREEN}$(t '(detected)' '(已检测到)')${RESET}"elsenote=" ${YELLOW}$(t '(not found in PATH)' '(PATH 中未找到)')${RESET}"fi- printf '\r\033[K %s%s %s%s\n' "$cur" "$mark" "$3" "$note" >/dev/tty+ printf '\r\033[K %s%s %s%s\n' "$cur" "$mark" "$label" "$note" >/dev/tty+}++tui_add_item_line() {+ local idx="$1" cur=' '+ [ "$TUI_CURSOR" -eq "$idx" ] && cur="${CYAN}>${RESET} "+ printf '\r\033[K %s%s %s\n' "$cur" "${CYAN}+${RESET}" "$(t 'Add compatible CLI...' '新增兼容 CLI...')" >/dev/tty}tui_draw() {+ local idx=0 spec kind bin total[ "$TUI_LINES" -gt 0 ] && printf '\033[%dA' "$TUI_LINES" >/dev/tty- tui_item_line 0 "$SEL_CLAUDE" "Claude Code" "$HAVE_CLAUDE"- tui_item_line 1 "$SEL_CODEX" "Codex" "$HAVE_CODEX"- printf '\r\033[K %s%s%s\n' "$CYAN" "$(t '↑/↓ move · space toggle · a all · enter confirm' '↑/↓ 移动 · 空格勾选 · a 全选 · 回车确认')" "$RESET" >/dev/tty- TUI_LINES=3+ total="$(tui_total_count)"+ while [ "$idx" -lt "$total" ]; do+ spec="$(tui_item_at "$idx")"+ kind="${spec%%|*}"+ bin="${spec#*|}"+ if [ "$kind" = "add" ]; then+ add_idx="$idx"+ tui_add_item_line "$idx"+ else+ tui_item_line "$idx" "$kind" "$bin"+ fi+ idx=$((idx + 1))+ done+ printf '\r\033[K %s%s%s\n' "$CYAN" "$(t '↑/↓ move · space toggle · enter confirm · enter on + to add · a all' '↑/↓ 移动 · 空格勾选 · 回车确认 · 在 + 上回车新增 · a 全选')" "$RESET" >/dev/tty+ TUI_LINES=$((total + 1))+}++tui_reset_bin_selection() {+ local bin any=0+ SEL_CLAUDE_BINS=""+ SEL_CODEX_BINS=""+ SEL_OPENCODE=0+ SEL_PI=0+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if command -v "$bin" >/dev/null 2>&1; then+ SEL_CLAUDE_BINS="${SEL_CLAUDE_BINS:+$SEL_CLAUDE_BINS+}$bin"; any=1+ fi+ done <<EOF+$TUI_CLAUDE_BINS+EOF+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if command -v "$bin" >/dev/null 2>&1; then+ SEL_CODEX_BINS="${SEL_CODEX_BINS:+$SEL_CODEX_BINS+}$bin"; any=1+ fi+ done <<EOF+$TUI_CODEX_BINS+EOF+ if command -v opencode >/dev/null 2>&1; then SEL_OPENCODE=1; any=1; fi+ if command -v pi >/dev/null 2>&1; then SEL_PI=1; any=1; fi+ if [ "$any" -ne 1 ]; then+ SEL_CLAUDE_BINS="$TUI_CLAUDE_BINS"+ SEL_CODEX_BINS="$TUI_CODEX_BINS"+ fi+}++tui_choose_cli_format() {+ local cursor=0 key rest lines=0+ TUI_FORMAT_CHOICE=""+ printf '%s%s%s\n' "$BOLD" "$(t 'Choose compatible format:' '选择兼容格式:')" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+ while :; do+ [ "$lines" -gt 0 ] && printf '\033[%dA' "$lines" >/dev/tty+ if [ "$cursor" -eq 0 ]; then+ printf '\r\033[K %s>%s (%s•%s) %s\n' "$CYAN" "$RESET" "$GREEN" "$RESET" "$(t 'Claude-format' 'Claude 格式')" >/dev/tty+ printf '\r\033[K ( ) %s\n' "$(t 'Codex-format' 'Codex 格式')" >/dev/tty+ else+ printf '\r\033[K ( ) %s\n' "$(t 'Claude-format' 'Claude 格式')" >/dev/tty+ printf '\r\033[K %s>%s (%s•%s) %s\n' "$CYAN" "$RESET" "$GREEN" "$RESET" "$(t 'Codex-format' 'Codex 格式')" >/dev/tty+ fi+ printf '\r\033[K %s%s%s\n' "$CYAN" "$(t '↑/↓ move · enter confirm · q cancel' '↑/↓ 移动 · 回车确认 · q 取消')" "$RESET" >/dev/tty+ lines=3+ if ! IFS= read -rsn1 key <&3; then+ continue+ fi+ case "$key" in+ $'\x1b')+ rest=""+ IFS= read -rsn2 -t 1 rest <&3 || rest=""+ case "$rest" in+ '[A'|'[B') cursor=$((1 - cursor)) ;;+ esac+ ;;+ k|j) cursor=$((1 - cursor)) ;;+ 1) TUI_FORMAT_CHOICE="claude"; break ;;+ 2) TUI_FORMAT_CHOICE="codex"; break ;;+ ''|$'\n'|$'\r')+ if [ "$cursor" -eq 0 ]; then TUI_FORMAT_CHOICE="claude"; else TUI_FORMAT_CHOICE="codex"; fi+ break+ ;;+ q|Q) TUI_FORMAT_CHOICE=""; break ;;+ esac+ done+ printf '\033[?25h' >/dev/tty+}++tui_add_compatible_cli() {+ local kind bin+ printf '\033[?25h' >/dev/tty+ printf '\n%s%s%s\n' "$BOLD" "$(t 'Add compatible CLI' '新增兼容 CLI')" "$RESET" >/dev/tty+ tui_choose_cli_format+ kind="$TUI_FORMAT_CHOICE"+ if [ -z "$kind" ]; then+ warn "$(t 'Skipped adding compatible CLI.' '已跳过新增兼容 CLI。')"+ TUI_LINES=0+ printf '%s%s%s\n' "$BOLD" "$(t 'Select the harnesses to install for:' '选择要安装的 harness:')" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+ return 0+ fi+ ask "$(t 'Command name or path: ' '命令名或路径: ')"+ read_tty bin+ bin="$(printf '%s' "$bin" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"+ if [ -z "$bin" ]; then+ warn "$(t 'Skipped adding compatible CLI.' '已跳过新增兼容 CLI。')"+ TUI_LINES=0+ printf '%s%s%s\n' "$BOLD" "$(t 'Select the harnesses to install for:' '选择要安装的 harness:')" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+ return 0+ fi+ if [ "$kind" = "claude" ]; then+ TUI_CLAUDE_BINS="$(append_csv_list "$TUI_CLAUDE_BINS" "$bin")"+ SEL_CLAUDE_BINS="$(append_csv_list "$SEL_CLAUDE_BINS" "$bin")"+ info "$(t 'Added Claude-format CLI:' '已新增 Claude 格式 CLI:') $bin"+ else+ TUI_CODEX_BINS="$(append_csv_list "$TUI_CODEX_BINS" "$bin")"+ SEL_CODEX_BINS="$(append_csv_list "$SEL_CODEX_BINS" "$bin")"+ info "$(t 'Added Codex-format CLI:' '已新增 Codex 格式 CLI:') $bin"+ fi+ TUI_CURSOR="$(tui_find_bin_index "$kind" "$bin")"+ TUI_LINES=0+ printf '%s%s%s\n' "$BOLD" "$(t 'Select the harnesses to install for:' '选择要安装的 harness:')" "$RESET" >/dev/tty+ printf '\033[?25l' >/dev/tty+}++tui_has_selection() {+ [ -n "$(list_words "$SEL_CLAUDE_BINS")" ] || [ -n "$(list_words "$SEL_CODEX_BINS")" ] || [ "$SEL_OPENCODE" -eq 1 ] || [ "$SEL_PI" -eq 1 ]+}++tui_finish_selection() {+ CLAUDE_BINS="$SEL_CLAUDE_BINS"+ CODEX_BINS="$SEL_CODEX_BINS"+ SELECTED_HARNESSES=""+ [ -n "$(list_words "$CLAUDE_BINS")" ] && SELECTED_HARNESSES="claude"+ [ -n "$(list_words "$CODEX_BINS")" ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}codex"+ [ "$SEL_OPENCODE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}opencode"+ [ "$SEL_PI" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}pi"}tui_select_harnesses() {- local key rest- SEL_CLAUDE=$HAVE_CLAUDE; SEL_CODEX=$HAVE_CODEX- if [ "$SEL_CLAUDE$SEL_CODEX" = "00" ]; then SEL_CLAUDE=1; SEL_CODEX=1; fi+ local key rest spec kind bin total add_idx+ tui_reset_bin_selectionprintf '%s%s%s\n' "$BOLD" "$(t 'Select the harnesses to install for:' '选择要安装的 harness:')" "$RESET" >/dev/ttyprintf '\033[?25l' >/dev/ttytrap 'printf "\033[?25h" >/dev/tty' EXITTUI_LINES=0tui_drawwhile :; do- IFS= read -rsn1 key <&3 || key=""+ total="$(tui_total_count)"+ add_idx=$((total - 1))+ if ! IFS= read -rsn1 key <&3; then+ tui_draw+ continue+ ficase "$key" in$'\x1b')rest=""IFS= read -rsn2 -t 1 rest <&3 || rest=""case "$rest" in- '[A') TUI_CURSOR=0 ;;- '[B') TUI_CURSOR=1 ;;+ '[A') TUI_CURSOR=$(( (TUI_CURSOR + total - 1) % total )) ;;+ '[B') TUI_CURSOR=$(( (TUI_CURSOR + 1) % total )) ;;esac;;- k) TUI_CURSOR=0 ;;- j) TUI_CURSOR=1 ;;+ k) TUI_CURSOR=$(( (TUI_CURSOR + total - 1) % total )) ;;+ j) TUI_CURSOR=$(( (TUI_CURSOR + 1) % total )) ;;' ')- if [ "$TUI_CURSOR" -eq 0 ]; then SEL_CLAUDE=$((1 - SEL_CLAUDE)); else SEL_CODEX=$((1 - SEL_CODEX)); fi+ if [ "$TUI_CURSOR" -eq "$add_idx" ]; then+ tui_add_compatible_cli+ else+ spec="$(tui_item_at "$TUI_CURSOR")"; kind="${spec%%|*}"; bin="${spec#*|}"+ tui_toggle_bin "$kind" "$bin"+ fi+ ;;+ a|A) tui_set_all_bins ;;+ n|N|+)+ TUI_CURSOR="$add_idx"+ tui_add_compatible_cli;;- a|A) SEL_CLAUDE=1; SEL_CODEX=1 ;;''|$'\n'|$'\r')- if [ $((SEL_CLAUDE + SEL_CODEX)) -eq 0 ]; then continue; fi- break+ if [ "$TUI_CURSOR" -eq "$add_idx" ]; then+ tui_add_compatible_cli+ else+ tui_has_selection || { tui_draw; continue; }+ break+ fi;;- q|Q) break ;;+ q|Q) tui_has_selection && break ;;esac+ total="$(tui_total_count)"+ [ "$TUI_CURSOR" -lt "$total" ] || TUI_CURSOR=$((total - 1))tui_drawdoneprintf '\033[?25h' >/dev/ttytrap - EXIT- SELECTED_HARNESSES=""- [ "$SEL_CLAUDE" -eq 1 ] && SELECTED_HARNESSES="claude"- [ "$SEL_CODEX" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}codex"- [ -n "$SELECTED_HARNESSES" ] || SELECTED_HARNESSES="claude,codex"+ tui_finish_selection}select_harnesses() {local detected="" reply default[ "$HAVE_CLAUDE" -eq 1 ] && detected="claude"[ "$HAVE_CODEX" -eq 1 ] && detected="${detected:+$detected,}codex"+ [ "$HAVE_OPENCODE" -eq 1 ] && detected="${detected:+$detected,}opencode"+ [ "$HAVE_PI" -eq 1 ] && detected="${detected:+$detected,}pi"if [ -n "$REQUESTED_HARNESSES" ]; thenSELECTED_HARNESSES="$REQUESTED_HARNESSES"@@ -421,11 +796,34 @@ select_harnesses() {fi}+select_compatible_bins() {+ local reply+ [ "$INTERACTIVE" -eq 1 ] || return 0+ [ -w /dev/tty ] && return 0+ if contains_harness claude && [ -z "$CLAUDE_BINS_ARG" ]; then+ ask "$(t 'Extra Claude-format CLI commands, comma-separated (e.g. seed)' '额外 Claude 格式 CLI 命令,逗号分隔(如 seed)') [$(t 'none' '无')]: "+ read_tty reply+ if [ -n "$reply" ]; then+ CLAUDE_BINS="$(append_csv_list "$CLAUDE_BINS" "$reply")"+ info "$(t 'Claude-format commands:' 'Claude 格式命令:') $(list_words "$CLAUDE_BINS")"+ fi+ fi+ if contains_harness codex && [ -z "$CODEX_BINS_ARG" ]; then+ ask "$(t 'Extra Codex-format CLI commands, comma-separated (e.g. traex)' '额外 Codex 格式 CLI 命令,逗号分隔(如 traex)') [$(t 'none' '无')]: "+ read_tty reply+ if [ -n "$reply" ]; then+ CODEX_BINS="$(append_csv_list "$CODEX_BINS" "$reply")"+ info "$(t 'Codex-format commands:' 'Codex 格式命令:') $(list_words "$CODEX_BINS")"+ fi+ fi+ refresh_available_harnesses+}+validate_selected_harnesses() {local h bad=0while IFS= read -r h; docase "$h" in- claude|codex) ;;+ claude|codex|opencode|pi) ;;*) err "Unsupported harness: $h"; bad=1 ;;esacdone <<EOF@@ -434,6 +832,40 @@ EOF[ "$bad" -eq 0 ] || exit 2}+validate_selected_bins() {+ local bin ok=0+ if contains_harness claude; then+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if command -v "$bin" >/dev/null 2>&1; then+ ok=1+ else+ warn "$(t 'Selected Claude-format CLI not found in PATH:' '已选择的 Claude 格式 CLI 不在 PATH 中:') $bin"+ fi+ done <<EOF+$CLAUDE_BINS+EOF+ fi+ if contains_harness codex; then+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ if command -v "$bin" >/dev/null 2>&1; then+ ok=1+ else+ warn "$(t 'Selected Codex-format CLI not found in PATH:' '已选择的 Codex 格式 CLI 不在 PATH 中:') $bin"+ fi+ done <<EOF+$CODEX_BINS+EOF+ fi+ if contains_harness opencode && command -v opencode >/dev/null 2>&1; then ok=1; fi+ if contains_harness pi && command -v pi >/dev/null 2>&1; then ok=1; fi+ if [ "$ok" -ne 1 ]; then+ err "$(t 'No selected compatible CLI command was found in PATH.' '未在 PATH 中找到任何已选择的兼容 CLI 命令。')"+ exit 2+ fi+}+# ---------------------------------------------------------------------------# Distribution channel (github vs tos mirror)# ---------------------------------------------------------------------------@@ -738,12 +1170,40 @@ cleanup_rc_wrappers() {# Claude Code# ---------------------------------------------------------------------------+CLAUDE_BIN="claude"++is_native_claude_bin() {+ [ "$(bin_basename "$CLAUDE_BIN")" = "claude" ]+}++claude_cmd() {+ command "$CLAUDE_BIN" "$@"+}+has_plugin_subcommand() {- command claude plugin --help >/dev/null 2>&1+ claude_cmd plugin --help >/dev/null 2>&1}# Current registered source string for our Claude marketplace ("" if absent).claude_marketplace_current_source() {+ local raw+ raw="$(claude_cmd plugin marketplace list --json 2>/dev/null || true)"+ if [ -n "$raw" ]; then+ printf '%s' "$raw" | node -e '+ let raw = "";+ process.stdin.on("data", (d) => { raw += d; });+ process.stdin.on("end", () => {+ try {+ const parsed = JSON.parse(raw);+ const list = Array.isArray(parsed) ? parsed : (parsed.marketplaces || []);+ const m = list.find((x) => x.name === process.argv[1]);+ if (m) process.stdout.write(String(m.path || m.repo || m.url || m.source || ""));+ } catch {}+ });+ ' "$MARKETPLACE_NAME" 2>/dev/null || true+ return 0+ fi+ is_native_claude_bin || return 0node -e 'try {const m = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))[process.argv[2]];@@ -755,17 +1215,17 @@ claude_marketplace_current_source() {migrate_claude_legacy_marketplace() {local id plugin_list marketplace_list- plugin_list="$(command claude plugin list 2>/dev/null || true)"+ plugin_list="$(claude_cmd plugin list 2>/dev/null || true)"for id in $CC_OLD_IDS; doif str_contains "$plugin_list" "$id"; theninfo "$(t 'Removing pre-unification plugin install' '移除旧命名的插件安装') ($id)"- command claude plugin uninstall "$id" >/dev/null 2>&1 || true+ claude_cmd plugin uninstall "$id" >/dev/null 2>&1 || truefidone- marketplace_list="$(command claude plugin marketplace list 2>/dev/null || true)"+ marketplace_list="$(claude_cmd plugin marketplace list 2>/dev/null || true)"if str_contains "$marketplace_list" "$OLD_MARKETPLACE_NAME"; theninfo "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"- command claude plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true+ claude_cmd plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || truefi}@@ -798,19 +1258,22 @@ claude_marketplace_sync() { # claude_marketplace_sync <add-target> <expected-soulocal target="$1" needle="$2" currentcurrent="$(claude_marketplace_current_source)"if [ -n "$current" ] && [ "$current" = "$needle" ]; then- info "claude plugin marketplace update ($MARKETPLACE_NAME)"- command claude plugin marketplace update "$MARKETPLACE_NAME" || \+ info "$CLAUDE_BIN plugin marketplace update ($MARKETPLACE_NAME)"+ claude_cmd plugin marketplace update "$MARKETPLACE_NAME" || \warn 'marketplace update returned non-zero — continuing'return 0fiif [ -n "$current" ]; theninfo "$(t 'Marketplace points elsewhere; re-registering' 'marketplace 指向其他来源,重新注册') ($current)"- command claude plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true- command claude plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ claude_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ claude_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ elif ! is_native_claude_bin; then+ claude_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ claude_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || truefi- info "claude plugin marketplace add ($target)"- command claude plugin marketplace add "$target" || {- err 'claude plugin marketplace add failed'+ info "$CLAUDE_BIN plugin marketplace add ($target)"+ claude_cmd plugin marketplace add "$target" || {+ err "$CLAUDE_BIN plugin marketplace add failed"return 1}}@@ -825,15 +1288,15 @@ install_claude_modern() {claude_marketplace_sync "$MKT_DIR" "$MKT_DIR" || return 1;;esac- if str_contains "$(command claude plugin list 2>/dev/null || true)" "$PLUGIN_ID"; then- info "claude plugin update ($PLUGIN_ID)"- command claude plugin update "$PLUGIN_ID" || warn 'claude plugin update returned non-zero'+ if str_contains "$(claude_cmd plugin list 2>/dev/null || true)" "$PLUGIN_ID"; then+ info "$CLAUDE_BIN plugin update ($PLUGIN_ID)"+ claude_cmd plugin update "$PLUGIN_ID" || warn "$CLAUDE_BIN plugin update returned non-zero"else- info "claude plugin install ($PLUGIN_ID)"- command claude plugin install "$PLUGIN_ID" || { err 'claude plugin install failed'; return 1; }+ info "$CLAUDE_BIN plugin install ($PLUGIN_ID)"+ claude_cmd plugin install "$PLUGIN_ID" || { err "$CLAUDE_BIN plugin install failed"; return 1; }fi- command claude plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true- info "$(t 'Claude plugin installed:' 'Claude 插件已安装:') $PLUGIN_ID"+ claude_cmd plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true+ info "$(t 'Claude-format plugin installed:' 'Claude 格式插件已安装:') $CLAUDE_BIN -> $PLUGIN_ID"}install_claude_legacy() {@@ -845,10 +1308,10 @@ install_claude_legacy() {hooks_src="$plugin_dir/hooks/hooks.json"ts=$(date +%Y%m%d-%H%M%S)- info "Legacy mode: claude mcp add (stdio proxy) + merging hooks into $CC_SETTINGS"- command claude mcp remove openviking -s user >/dev/null 2>&1 || true- command claude mcp add --scope user openviking -- node "$plugin_dir/servers/mcp-proxy.mjs" || {- err 'claude mcp add failed'+ info "Legacy mode: $CLAUDE_BIN mcp add (stdio proxy) + merging hooks into $CC_SETTINGS"+ claude_cmd mcp remove openviking -s user >/dev/null 2>&1 || true+ claude_cmd mcp add --scope user openviking -- node "$plugin_dir/servers/mcp-proxy.mjs" || {+ err "$CLAUDE_BIN mcp add failed"return 1}@@ -932,15 +1395,19 @@ NODEinstall_claude() {heading "$(t '4. Claude Code plugin' '4. Claude Code 插件')"- if [ "$HAVE_CLAUDE" -ne 1 ]; then- warn "$(t 'claude CLI not found; skipping Claude Code install.' '未找到 claude 命令,跳过 Claude Code 安装。')"+ command -v "$CLAUDE_BIN" >/dev/null 2>&1 || {+ warn "$(t 'Claude-format CLI not found; skipping:' '未找到 Claude 格式 CLI,跳过:') $CLAUDE_BIN"return 0- fi+ }if has_plugin_subcommand; thenmigrate_claude_legacy_marketplaceinstall_claude_modern || return 1else- warn "$(t "This Claude Code build doesn't expose 'claude plugin' (introduced in 2.0)." '当前 Claude Code 版本没有 claude plugin 子命令(2.0 引入)。')"+ warn "$(t "This Claude-format CLI doesn't expose 'plugin'." '当前 Claude 格式 CLI 没有 plugin 子命令。') ($CLAUDE_BIN)"+ if ! is_native_claude_bin; then+ warn "$(t 'Legacy compatibility mode is only supported for the native claude command; skipping this custom CLI.' '旧版兼容模式仅支持原生 claude 命令;跳过这个自定义 CLI。')"+ return 0+ fiif [ "$INTERACTIVE" -eq 1 ]; thentui_menu "$(t 'Use legacy compatibility mode (claude mcp add + settings.json merge)?' '使用旧版兼容模式(claude mcp add + settings.json 合并)?')" 0 \"$(t 'Yes, install in legacy mode' '是,用兼容模式安装')" \@@ -952,37 +1419,57 @@ install_claude() {fiinstall_claude_legacy || return 1fi- register_statusline || true+ if is_native_claude_bin; then+ register_statusline || true+ fi}# ---------------------------------------------------------------------------# Codex# ---------------------------------------------------------------------------+CODEX_BIN="codex"++is_native_codex_bin() {+ [ "$(bin_basename "$CODEX_BIN")" = "codex" ]+}++codex_cmd() {+ command "$CODEX_BIN" "$@"+}+codex_marketplace_current_source() {- command codex plugin marketplace list --json 2>/dev/null | node -e '+ local raw+ raw="$(codex_cmd plugin marketplace list --json 2>/dev/null || true)"+ [ -n "$raw" ] || return 0+ printf '%s' "$raw" | node -e 'let raw = "";process.stdin.on("data", (d) => { raw += d; });process.stdin.on("end", () => {try {- const list = JSON.parse(raw).marketplaces || [];+ const parsed = JSON.parse(raw);+ const list = Array.isArray(parsed) ? parsed : (parsed.marketplaces || []);const m = list.find((x) => x.name === process.argv[1]);if (m && m.marketplaceSource) process.stdout.write(String(m.marketplaceSource.source || ""));+ else if (m) process.stdout.write(String(m.path || m.repo || m.url || m.source || ""));} catch {}});' "$MARKETPLACE_NAME" 2>/dev/null || true}migrate_codex_legacy_marketplace() {- command codex plugin remove "$CODEX_OLD_ID" >/dev/null 2>&1 || true- if str_contains "$(command codex plugin marketplace list 2>/dev/null || true)" "$OLD_MARKETPLACE_NAME"; then+ codex_cmd plugin remove "$CODEX_OLD_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$CODEX_OLD_ID" >/dev/null 2>&1 || true+ if str_contains "$(codex_cmd plugin marketplace list 2>/dev/null || true)" "$OLD_MARKETPLACE_NAME"; theninfo "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"- command codex plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true+ fi+ if is_native_codex_bin; then+ [ -d "$CODEX_OLD_MARKETPLACE_ROOT" ] && rm -rf "$CODEX_OLD_MARKETPLACE_ROOT"+ [ -d "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME" ] && rm -rf "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME"fi- [ -d "$CODEX_OLD_MARKETPLACE_ROOT" ] && rm -rf "$CODEX_OLD_MARKETPLACE_ROOT"- [ -d "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME" ] && rm -rf "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME"# Drop the old plugin id's config.toml section; the unified id gets its own.- if [ -f "$CODEX_CONFIG" ] && grep -qF "plugins.\"$CODEX_OLD_ID\"" "$CODEX_CONFIG"; then+ if is_native_codex_bin && [ -f "$CODEX_CONFIG" ] && grep -qF "plugins.\"$CODEX_OLD_ID\"" "$CODEX_CONFIG"; thennode - "$CODEX_CONFIG" "$CODEX_OLD_ID" <<'NODE' || trueconst fs = require("node:fs");const [path, oldId] = process.argv.slice(2);@@ -1005,18 +1492,23 @@ codex_marketplace_sync() { # codex_marketplace_sync <expected-source> <add-args.shiftcurrent="$(codex_marketplace_current_source)"if [ -n "$current" ] && [ "$current" = "$needle" ]; then- info "codex plugin marketplace upgrade ($MARKETPLACE_NAME)"- command codex plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ info "$CODEX_BIN plugin marketplace upgrade ($MARKETPLACE_NAME)"+ codex_cmd plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || truereturn 0fiif [ -n "$current" ]; theninfo "$(t 'Marketplace points elsewhere; re-registering' 'marketplace 指向其他来源,重新注册') ($current)"- command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true- command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ elif ! is_native_codex_bin; then+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || truefi- info "codex plugin marketplace add $*"- command codex plugin marketplace add "$@" >/dev/null || {- err 'codex plugin marketplace add failed'+ info "$CODEX_BIN plugin marketplace add $*"+ codex_cmd plugin marketplace add "$@" >/dev/null || {+ err "$CODEX_BIN plugin marketplace add failed"return 1}}@@ -1056,25 +1548,26 @@ NODEinstall_codex() {heading "$(t '4. Codex plugin' '4. Codex 插件')"- if [ "$HAVE_CODEX" -ne 1 ]; then- warn "$(t 'codex CLI not found; skipping Codex install.' '未找到 codex 命令,跳过 Codex 安装。')"+ command -v "$CODEX_BIN" >/dev/null 2>&1 || {+ warn "$(t 'Codex-format CLI not found; skipping:' '未找到 Codex 格式 CLI,跳过:') $CODEX_BIN"return 0- fi+ }migrate_codex_legacy_marketplacecase "$SOURCE_MODE" inremote)# Codex doesn't expose which --ref a registered git marketplace is# pinned to (`marketplace upgrade` silently refreshes the OLD ref), so# a matching URL is not enough — re-register deterministically.- command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true- command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true- info "codex plugin marketplace add $REPO_URL --ref $REPO_REF"+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ info "$CODEX_BIN plugin marketplace add $REPO_URL --ref $REPO_REF"# Sparse must include .agents/ — the marketplace manifest lives there,# and a plugin-dir-only sparse checkout fails manifest resolution.- command codex plugin marketplace add "$REPO_URL" --ref "$REPO_REF" \+ codex_cmd plugin marketplace add "$REPO_URL" --ref "$REPO_REF" \--sparse examples/codex-memory-plugin --sparse .agents >/dev/null 2>&1 || \- command codex plugin marketplace add "$REPO_URL" --ref "$REPO_REF" >/dev/null || {- err 'codex plugin marketplace add failed'+ codex_cmd plugin marketplace add "$REPO_URL" --ref "$REPO_REF" >/dev/null || {+ err "$CODEX_BIN plugin marketplace add failed"return 1};;@@ -1089,61 +1582,587 @@ install_codex() {codex_marketplace_sync "$MKT_DIR" "$MKT_DIR" || return 1;;esac- if ! command codex plugin add "$PLUGIN_ID" >/dev/null 2>&1; then- command codex plugin install "$PLUGIN_ID" >/dev/null 2>&1 || \- warn "codex plugin add/install returned non-zero for $PLUGIN_ID; config was still updated"+ if ! codex_cmd plugin add "$PLUGIN_ID" >/dev/null 2>&1; then+ codex_cmd plugin install "$PLUGIN_ID" >/dev/null 2>&1 || \+ warn "$CODEX_BIN plugin add/install returned non-zero for $PLUGIN_ID"+ fi+ codex_cmd plugin enable "$PLUGIN_ID" >/dev/null 2>&1 || true+ if is_native_codex_bin; then+ ensure_codex_config+ info "$(t 'Codex plugin enabled in' 'Codex 插件已在配置中启用:') $CODEX_CONFIG"+ else+ info "$(t 'Codex-format plugin installed:' 'Codex 格式插件已安装:') $CODEX_BIN -> $PLUGIN_ID"fi- ensure_codex_config- info "$(t 'Codex plugin enabled in' 'Codex 插件已在配置中启用:') $CODEX_CONFIG"}# Codex can clone git repos served over dumb HTTP from static hosting, so the# TOS mirror hosts a slim marketplace git repo — unlike Claude Code, Codex# keeps remote update support (`codex plugin marketplace upgrade`) on TOS.install_codex_tos_git() {- info "codex plugin marketplace add $CODEX_TOS_GIT_URL"+ info "$CODEX_BIN plugin marketplace add $CODEX_TOS_GIT_URL"local currentcurrent="$(codex_marketplace_current_source)"if [ -n "$current" ] && [ "$current" = "$CODEX_TOS_GIT_URL" ]; then- command codex plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace upgrade "$MARKETPLACE_NAME" >/dev/null 2>&1 || truereturn 0fiif [ -n "$current" ]; then- command codex plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true- command codex plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || true+ elif ! is_native_codex_bin; then+ codex_cmd plugin remove "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin uninstall "$PLUGIN_ID" >/dev/null 2>&1 || true+ codex_cmd plugin marketplace remove "$MARKETPLACE_NAME" >/dev/null 2>&1 || truefi- if ! command codex plugin marketplace add "$CODEX_TOS_GIT_URL" >/dev/null 2>&1; then+ if ! codex_cmd plugin marketplace add "$CODEX_TOS_GIT_URL" >/dev/null 2>&1; thenwarn "$(t 'TOS git marketplace unavailable; falling back to the archive directory.' 'TOS git marketplace 不可用,回退到归档目录方式。')"return 1fi}+# ---------------------------------------------------------------------------+# OpenCode+# ---------------------------------------------------------------------------++install_opencode() {+ heading "$(t '4. OpenCode plugin' '4. OpenCode 插件')"+ if ! command -v opencode >/dev/null 2>&1; then+ warn "$(t 'opencode CLI not found; skipping OpenCode install.' '未找到 opencode 命令,跳过 OpenCode 安装。')"+ return 0+ fi+ case "$SOURCE_MODE" in+ remote)+ opencode_register_npm_plugin+ ;;+ archive|dev)+ opencode_install_file_plugin+ ;;+ esac+}++opencode_config_file() {+ local json="$HOME/.config/opencode/opencode.json" jsonc="$HOME/.config/opencode/opencode.jsonc"+ if [ -f "$jsonc" ] && grep -q '"plugin"' "$jsonc" 2>/dev/null; then printf '%s' "$jsonc"; return; fi+ if [ -f "$json" ]; then printf '%s' "$json"; return; fi+ if [ -f "$jsonc" ]; then printf '%s' "$jsonc"; return; fi+ printf '%s' "$json"+}++opencode_register_npm_plugin() {+ local cfg plugin_dir proxy_root proxy+ cfg="$(opencode_config_file)"+ plugin_dir="$(plugin_dir_on_disk opencode-plugin)" || {+ warn "$(t 'OpenCode plugin sources not found; registering npm package without MCP fallback.' '未找到 OpenCode 插件源码;仅注册 npm 包,不写 MCP fallback。')"+ opencode_write_config "$cfg" "@openviking/opencode-plugin" ""+ return 0+ }+ proxy_root="$OV_HOME/opencode-mcp-proxy/openviking"+ proxy="$(opencode_install_mcp_proxy_snapshot "$plugin_dir" "$proxy_root")"+ opencode_write_config "$cfg" "@openviking/opencode-plugin" "$proxy"+ info "$(t 'OpenCode plugin registered in' 'OpenCode 插件已注册到:') $cfg"+}++opencode_install_mcp_proxy_snapshot() {+ local plugin_dir="$1" dest="$2"+ rm -rf "$dest.tmp"+ mkdir -p "$dest.tmp"+ (cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - package.json lib servers) | (cd "$dest.tmp" && tar -xf -)+ rm -rf "$dest"+ mkdir -p "$(dirname "$dest")"+ mv "$dest.tmp" "$dest"+ printf '%s' "$dest/servers/mcp-proxy.mjs"+}++opencode_write_config() {+ local cfg="$1" plugin_spec="$2" mcp_proxy="$3"+ mkdir -p "$(dirname "$cfg")"+ [ -f "$cfg" ] || printf '{\n}\n' > "$cfg"+ cp "$cfg" "$cfg.bak.$(date +%Y%m%d-%H%M%S)"+ node - "$cfg" "$plugin_spec" "$mcp_proxy" <<'NODE'+const fs = require("node:fs");+const file = process.argv[2];+const pluginSpec = process.argv[3] || "";+const mcpProxy = process.argv[4] || "";+let raw = "";+try { raw = fs.readFileSync(file, "utf8"); } catch {}++function stripJsonc(s) {+ let out = "";+ let i = 0;+ while (i < s.length) {+ const ch = s[i];+ const next = s[i + 1];+ if (ch === '"' || ch === "'") {+ const end = readStringEnd(s, i);+ out += s.slice(i, end);+ i = end;+ } else if (ch === "/" && next === "/") {+ i += 2;+ while (i < s.length && s[i] !== "\n") i++;+ } else if (ch === "/" && next === "*") {+ i += 2;+ while (i < s.length && !(s[i] === "*" && s[i + 1] === "/")) i++;+ i = Math.min(s.length, i + 2);+ } else {+ out += ch;+ i++;+ }+ }+ return out.replace(/,\s*([}\]])/g, "$1");+}++function readStringEnd(s, start) {+ const quote = s[start];+ let i = start + 1;+ while (i < s.length) {+ if (s[i] === "\\") {+ i += 2;+ } else if (s[i] === quote) {+ return i + 1;+ } else {+ i++;+ }+ }+ return s.length;+}++function skipTrivia(s, i, end = s.length) {+ while (i < end) {+ if (/\s/.test(s[i])) {+ i++;+ } else if (s[i] === "/" && s[i + 1] === "/") {+ i += 2;+ while (i < end && s[i] !== "\n") i++;+ } else if (s[i] === "/" && s[i + 1] === "*") {+ i += 2;+ while (i < end && !(s[i] === "*" && s[i + 1] === "/")) i++;+ i = Math.min(end, i + 2);+ } else {+ break;+ }+ }+ return i;+}++function parseStringLiteral(s, start) {+ const end = readStringEnd(s, start);+ try {+ return { value: JSON.parse(s.slice(start, end)), end };+ } catch {+ return { value: "", end };+ }+}++function findTopLevelObject(s) {+ const start = skipTrivia(s, 0);+ if (s[start] !== "{") return null;+ let depth = 0;+ let i = start;+ while (i < s.length) {+ if (s[i] === '"' || s[i] === "'") {+ i = readStringEnd(s, i);+ continue;+ }+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {+ i = skipTrivia(s, i);+ continue;+ }+ if (s[i] === "{" || s[i] === "[") depth++;+ if (s[i] === "}" || s[i] === "]") {+ depth--;+ if (depth === 0 && s[i] === "}") return { start, end: i };+ }+ i++;+ }+ return null;+}++function findObjectRangeAt(s, start, end = s.length) {+ const objectStart = skipTrivia(s, start, end);+ if (s[objectStart] !== "{") return null;+ let depth = 0;+ let i = objectStart;+ while (i < end) {+ if (s[i] === '"' || s[i] === "'") {+ i = readStringEnd(s, i);+ continue;+ }+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {+ i = skipTrivia(s, i, end);+ continue;+ }+ if (s[i] === "{" || s[i] === "[") depth++;+ if (s[i] === "}" || s[i] === "]") {+ depth--;+ if (depth === 0 && s[i] === "}") return { start: objectStart, end: i };+ }+ i++;+ }+ return null;+}++function findArrayRangeAt(s, start, end = s.length) {+ const arrayStart = skipTrivia(s, start, end);+ if (s[arrayStart] !== "[") return null;+ let depth = 0;+ let i = arrayStart;+ while (i < end) {+ if (s[i] === '"' || s[i] === "'") {+ i = readStringEnd(s, i);+ continue;+ }+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {+ i = skipTrivia(s, i, end);+ continue;+ }+ if (s[i] === "{" || s[i] === "[") depth++;+ if (s[i] === "}" || s[i] === "]") {+ depth--;+ if (depth === 0 && s[i] === "]") return { start: arrayStart, end: i };+ }+ i++;+ }+ return null;+}++function findTopLevelProperty(s, objectRange, name) {+ let depth = 1;+ let i = objectRange.start + 1;+ while (i < objectRange.end) {+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {+ i = skipTrivia(s, i, objectRange.end);+ continue;+ }+ if (s[i] === '"' || s[i] === "'") {+ const keyStart = i;+ const parsed = parseStringLiteral(s, i);+ i = parsed.end;+ const afterKey = skipTrivia(s, i, objectRange.end);+ if (depth === 1 && parsed.value === name && s[afterKey] === ":") {+ const valueStart = skipTrivia(s, afterKey + 1, objectRange.end);+ return {+ keyStart,+ valueStart,+ replaceEnd: findPropertyReplaceEnd(s, valueStart, objectRange.end),+ };+ }+ continue;+ }+ if (s[i] === "{" || s[i] === "[") depth++;+ if (s[i] === "}" || s[i] === "]") depth--;+ i++;+ }+ return null;+}++function findPropertyReplaceEnd(s, valueStart, objectEnd) {+ let depth = 0;+ let i = skipTrivia(s, valueStart, objectEnd);+ let lastTokenEnd = i;+ while (i < objectEnd) {+ if (s[i] === '"' || s[i] === "'") {+ i = readStringEnd(s, i);+ lastTokenEnd = i;+ continue;+ }+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {+ i = skipTrivia(s, i, objectEnd);+ continue;+ }+ if (depth === 0 && s[i] === ",") return lastTokenEnd;+ if (s[i] === "{" || s[i] === "[") depth++;+ if (s[i] === "}" || s[i] === "]") depth--;+ if (!/\s/.test(s[i])) lastTokenEnd = i + 1;+ i++;+ }+ return lastTokenEnd;+}++function findLineIndent(s, index) {+ const lineStart = s.lastIndexOf("\n", index - 1) + 1;+ const prefix = s.slice(lineStart, index);+ return /^[ \t]*$/.test(prefix) ? prefix : "";+}++function detectPropertyIndent(s, objectRange) {+ let i = objectRange.start + 1;+ while (i < objectRange.end) {+ i = skipTrivia(s, i, objectRange.end);+ if (s[i] === '"' || s[i] === "'") return findLineIndent(s, i) || " ";+ if (s[i] === "{" || s[i] === "[") break;+ i++;+ }+ const closeIndent = findLineIndent(s, objectRange.end);+ return `${closeIndent} `;+}++function hasTopLevelProperty(s, objectRange) {+ let i = objectRange.start + 1;+ while (i < objectRange.end) {+ i = skipTrivia(s, i, objectRange.end);+ if (s[i] === '"' || s[i] === "'") return true;+ i++;+ }+ return false;+}++function objectEndsWithComma(s, objectRange) {+ const body = s.slice(objectRange.start + 1, objectRange.end);+ return body.trimEnd().endsWith(",");+}++function rangeHasValue(s, range) {+ let i = range.start + 1;+ while (i < range.end) {+ i = skipTrivia(s, i, range.end);+ if (i < range.end) return true;+ }+ return false;+}++function formatProperty(name, value, indent) {+ const json = JSON.stringify(value, null, 2);+ const formatted = json.split("\n").map((line, idx) => idx === 0 ? line : `${indent}${line}`).join("\n");+ return `${JSON.stringify(name)}: ${formatted}`;+}++function setPropertyInObject(s, objectRange, name, value) {+ const existing = findTopLevelProperty(s, objectRange, name);+ if (existing) {+ const indent = findLineIndent(s, existing.keyStart) || detectPropertyIndent(s, objectRange);+ return `${s.slice(0, existing.keyStart)}${formatProperty(name, value, indent)}${s.slice(existing.replaceEnd)}`;+ }++ const indent = detectPropertyIndent(s, objectRange);+ const closeIndent = findLineIndent(s, objectRange.end);+ const needsComma = hasTopLevelProperty(s, objectRange) && !objectEndsWithComma(s, objectRange);+ const prefix = needsComma ? "," : "";+ const insertion = `${prefix}\n${indent}${formatProperty(name, value, indent)}\n${closeIndent}`;+ return `${s.slice(0, objectRange.end)}${insertion}${s.slice(objectRange.end)}`;+}++function setTopLevelProperty(s, name, value) {+ let objectRange = findTopLevelObject(s);+ if (!objectRange) {+ s = "{\n}\n";+ objectRange = findTopLevelObject(s);+ }+ return setPropertyInObject(s, objectRange, name, value);+}++function setNestedObjectProperty(s, parentName, childName, childValue, fallbackParentValue) {+ let objectRange = findTopLevelObject(s);+ if (!objectRange) {+ s = "{\n}\n";+ objectRange = findTopLevelObject(s);+ }+ const parent = findTopLevelProperty(s, objectRange, parentName);+ if (!parent) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);+ const parentRange = findObjectRangeAt(s, parent.valueStart, parent.replaceEnd);+ if (!parentRange) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);+ return setPropertyInObject(s, parentRange, childName, childValue);+}++function appendStringToTopLevelArray(s, name, value) {+ let objectRange = findTopLevelObject(s);+ if (!objectRange) {+ s = "{\n}\n";+ objectRange = findTopLevelObject(s);+ }+ const prop = findTopLevelProperty(s, objectRange, name);+ if (!prop) return setPropertyInObject(s, objectRange, name, [value]);+ const arrayRange = findArrayRangeAt(s, prop.valueStart, prop.replaceEnd);+ if (!arrayRange) return setPropertyInObject(s, objectRange, name, [value]);+ const propIndent = findLineIndent(s, prop.keyStart) || detectPropertyIndent(s, objectRange);+ const itemIndent = `${propIndent} `;+ const closeIndent = findLineIndent(s, arrayRange.end) || propIndent;+ const needsComma = rangeHasValue(s, arrayRange) && !s.slice(arrayRange.start + 1, arrayRange.end).trimEnd().endsWith(",");+ const prefix = needsComma ? "," : "";+ const insertion = `${prefix}\n${itemIndent}${JSON.stringify(value)}\n${closeIndent}`;+ return `${s.slice(0, arrayRange.end)}${insertion}${s.slice(arrayRange.end)}`;+}++let data = {};+try { data = raw.trim() ? JSON.parse(stripJsonc(raw)) : {}; } catch { data = {}; }+let nextRaw = raw.trim() ? raw : "{\n}\n";+if (pluginSpec) {+ const next = Array.isArray(data.plugin) ? data.plugin.slice() : [];+ if (!next.includes(pluginSpec)) {+ next.push(pluginSpec);+ nextRaw = appendStringToTopLevelArray(nextRaw, "plugin", pluginSpec);+ }+ data.plugin = next;+}+if (mcpProxy) {+ data.mcp = data.mcp && typeof data.mcp === "object" && !Array.isArray(data.mcp) ? data.mcp : {};+ if (!data.mcp.openviking || data.mcp.openviking.enabled !== false) {+ data.mcp.openviking = {+ type: "local",+ command: ["node", mcpProxy],+ enabled: true,+ timeout: 15000,+ };+ nextRaw = setNestedObjectProperty(nextRaw, "mcp", "openviking", data.mcp.openviking, data.mcp);+ }+}+if (!nextRaw.endsWith("\n")) nextRaw += "\n";+fs.writeFileSync(file, nextRaw);+NODE+}++opencode_install_file_plugin() {+ local plugin_dir dest+ plugin_dir="$(plugin_dir_on_disk opencode-plugin)" || {+ warn "$(t 'OpenCode plugin sources not found; skipping.' '未找到 OpenCode 插件源码,跳过。')"+ return 0+ }+ dest="$HOME/.config/opencode/plugins/openviking"+ mkdir -p "$(dirname "$dest")"+ if [ "$SOURCE_MODE" = "dev" ]; then+ rm -rf "$dest"+ ln -sfn "$plugin_dir" "$dest"+ else+ rm -rf "$dest.tmp" "$dest"+ mkdir -p "$dest.tmp"+ (cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - .) | (cd "$dest.tmp" && tar -xf -)+ mv "$dest.tmp" "$dest"+ fi+ if [ -f "$plugin_dir/wrappers/openviking.js" ]; then+ cp "$plugin_dir/wrappers/openviking.js" "$HOME/.config/opencode/plugins/openviking.js"+ else+ printf '%s\n' 'export { OpenVikingPlugin, default } from "./openviking/index.mjs"' > "$HOME/.config/opencode/plugins/openviking.js"+ fi+ opencode_write_config "$(opencode_config_file)" "" "$dest/servers/mcp-proxy.mjs"+ info "$(t 'OpenCode file plugin installed:' 'OpenCode 文件插件已安装:') $dest"+}++# ---------------------------------------------------------------------------+# pi+# ---------------------------------------------------------------------------++install_pi() {+ heading "$(t '4. pi extension' '4. pi 扩展')"+ if ! command -v pi >/dev/null 2>&1; then+ warn "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"+ return 0+ fi+ local plugin_dir dest tmp keep_config+ plugin_dir="$(plugin_dir_on_disk pi-coding-agent-extension)" || {+ warn "$(t 'pi extension sources not found; skipping.' '未找到 pi 扩展源码,跳过。')"+ return 0+ }+ dest="$HOME/.pi/agent/extensions/openviking"+ tmp="$dest.tmp"+ keep_config=""+ [ -f "$dest/config.json" ] && keep_config="$dest/config.json"+ rm -rf "$tmp"+ mkdir -p "$tmp"+ (cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - .) | (cd "$tmp" && tar -xf -)+ if [ -n "$keep_config" ]; then+ cp "$keep_config" "$tmp/config.json"+ fi+ rm -rf "$dest"+ mkdir -p "$(dirname "$dest")"+ mv "$tmp" "$dest"+ pi install "$dest" || warn "$(t 'pi extension copied but pi install registration failed; run pi install manually.' 'pi 扩展文件已复制,但 pi install 注册失败;请手动运行 pi install。')"+ info "$(t 'pi extension installed:' 'pi 扩展已安装:') $dest"+}+# ---------------------------------------------------------------------------# Validation# ---------------------------------------------------------------------------validate_install() {heading "$(t '5. Validation' '5. 安装校验')"- local ok=1 cached codex_list- if contains_harness claude && [ "$HAVE_CLAUDE" -eq 1 ] && has_plugin_subcommand; then- if str_contains "$(command claude plugin list 2>/dev/null || true)" "$PLUGIN_NAME"; then- info "claude: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ local ok=1 cached list bin+ if contains_harness claude; then+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ command -v "$bin" >/dev/null 2>&1 || continue+ CLAUDE_BIN="$bin"+ if has_plugin_subcommand; then+ list="$(claude_cmd plugin list 2>/dev/null || true)"+ if str_contains "$list" "$PLUGIN_NAME"; then+ info "$CLAUDE_BIN: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ else+ warn "$CLAUDE_BIN: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ ok=0+ fi+ fi+ done <<EOF+$CLAUDE_BINS+EOF+ fi+ if contains_harness codex; then+ while IFS= read -r bin; do+ [ -n "$bin" ] || continue+ command -v "$bin" >/dev/null 2>&1 || continue+ CODEX_BIN="$bin"+ list="$(codex_cmd plugin list 2>/dev/null || true)"+ if str_contains "$list" "$PLUGIN_NAME"; then+ info "$CODEX_BIN: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ else+ warn "$CODEX_BIN: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ ok=0+ fi+ if is_native_codex_bin; then+ cached=$(find "$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME" -name 'mcp-proxy.mjs' -path '*/servers/*' 2>/dev/null | sort | tail -n 1)+ if [ -n "$cached" ]; then+ node --check "$cached" && info "codex: $(t 'cached stdio proxy parses' '缓存中的 stdio 代理语法正常') ($cached)" || ok=0+ fi+ fi+ done <<EOF+$CODEX_BINS+EOF+ fi+ if contains_harness opencode; then+ local ocfg="$HOME/.config/opencode/opencode.json"+ local ocfgc="$HOME/.config/opencode/opencode.jsonc"+ if grep -q '@openviking/opencode-plugin' "$ocfg" "$ocfgc" 2>/dev/null || { [ -f "$HOME/.config/opencode/plugins/openviking.js" ] && [ -f "$HOME/.config/opencode/plugins/openviking/index.mjs" ]; }; then+ info "opencode: $PLUGIN_NAME $(t 'appears installed' '看起来已安装')"+ else+ warn "opencode: $PLUGIN_NAME $(t 'not found in config/plugin dir' '未在配置或插件目录中找到')"+ ok=0+ fi+ if [ -f "$HOME/.config/opencode/plugins/openviking.js" ]; then+ node --check "$HOME/.config/opencode/plugins/openviking.js" || ok=0+ fi+ if [ -f "$HOME/.config/opencode/plugins/openviking/index.mjs" ]; then+ node --check "$HOME/.config/opencode/plugins/openviking/index.mjs" || ok=0+ fi+ if [ -f "$HOME/.config/opencode/plugins/openviking/servers/mcp-proxy.mjs" ]; then+ node --check "$HOME/.config/opencode/plugins/openviking/servers/mcp-proxy.mjs" || ok=0+ elif [ -f "$OV_HOME/opencode-mcp-proxy/openviking/servers/mcp-proxy.mjs" ]; then+ node --check "$OV_HOME/opencode-mcp-proxy/openviking/servers/mcp-proxy.mjs" || ok=0+ else+ warn "opencode: $(t 'OpenViking MCP proxy not found' '未找到 OpenViking MCP proxy')"+ ok=0+ fi+ if grep -q '"openviking"' "$ocfg" "$ocfgc" 2>/dev/null && grep -q '"mcp"' "$ocfg" "$ocfgc" 2>/dev/null; then+ info "opencode: $(t 'MCP server registered' 'MCP server 已注册')"else- warn "claude: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ warn "opencode: $(t 'MCP server not found in config' '配置中未找到 MCP server')"ok=0fifi- if contains_harness codex && [ "$HAVE_CODEX" -eq 1 ]; then- codex_list="$(command codex plugin list 2>/dev/null || true)"- if str_contains "$codex_list" "$PLUGIN_NAME"; then- info "codex: $PLUGIN_NAME $(t 'visible in plugin list' '已出现在插件列表')"+ if contains_harness pi; then+ if [ -f "$HOME/.pi/agent/extensions/openviking/index.ts" ] || [ -f "$HOME/.pi/agent/extensions/openviking/index.js" ]; then+ info "pi: $PLUGIN_NAME $(t 'extension files present' '扩展文件已存在')"else- warn "codex: $PLUGIN_NAME $(t 'not visible in plugin list' '未出现在插件列表')"+ warn "pi: $PLUGIN_NAME $(t 'extension files not found' '未找到扩展文件')"ok=0fi- cached=$(find "$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME" -name 'mcp-proxy.mjs' -path '*/servers/*' 2>/dev/null | sort | tail -n 1)- if [ -n "$cached" ]; then- node --check "$cached" && info "codex: $(t 'cached stdio proxy parses' '缓存中的 stdio 代理语法正常') ($cached)" || ok=0+ if command -v pi >/dev/null 2>&1; then+ if pi list 2>/dev/null | grep -q 'extensions/openviking'; then+ info "pi: $PLUGIN_NAME $(t 'registered in pi settings' '已注册到 pi settings')"+ else+ warn "pi: $PLUGIN_NAME $(t 'not registered in pi settings' '未注册到 pi settings')"+ ok=0+ fi+ fi+ if [ -f "$HOME/.pi/agent/extensions/openviking/shared/recall-core.mjs" ]; then+ node --check "$HOME/.pi/agent/extensions/openviking/shared/recall-core.mjs" || ok=0fifiif [ -n "$MKT_DIR" ] && [ -f "$MKT_DIR/claude-code-memory-plugin/scripts/marketplace.test.mjs" ] && [ -d "$MKT_DIR/../.git" ]; then@@ -1174,7 +2193,12 @@ command -v curl >/dev/null 2>&1 || warn "curl not found; archive installs may faresolve_self_checkoutselect_harnessesvalidate_selected_harnesses+select_compatible_bins+refresh_available_harnessesinfo "$(t 'Selected harnesses:' '已选择:') $(printf '%s' "$SELECTED_HARNESSES" | tr ',' ' ')"+if contains_harness claude; then info "$(t 'Claude-format commands:' 'Claude 格式命令:') $(list_words "$CLAUDE_BINS")"; fi+if contains_harness codex; then info "$(t 'Codex-format commands:' 'Codex 格式命令:') $(list_words "$CODEX_BINS")"; fi+validate_selected_binsselect_distconfigure_ovcli@@ -1182,8 +2206,24 @@ resolve_source_modeprepare_marketplace_dircleanup_rc_wrappers-if contains_harness claude; then install_claude; fi-if contains_harness codex; then install_codex; fi+if contains_harness claude; then+ while IFS= read -r CLAUDE_BIN; do+ [ -n "$CLAUDE_BIN" ] || continue+ install_claude+ done <<EOF+$CLAUDE_BINS+EOF+fi+if contains_harness codex; then+ while IFS= read -r CODEX_BIN; do+ [ -n "$CODEX_BIN" ] || continue+ install_codex+ done <<EOF+$CODEX_BINS+EOF+fi+if contains_harness opencode; then install_opencode; fi+if contains_harness pi; then install_pi; fivalidate_installheading "$(t 'Done' '完成')"@@ -1192,5 +2232,7 @@ case "$SOURCE_MODE" inremote) info "Marketplace: remote ($REPO_URL @ $REPO_REF)" ;;*) info "Marketplace: ${MKT_DIR:-$CODEX_TOS_GIT_URL}" ;;esac-if contains_harness claude; then info "Claude: $PLUGIN_ID"; fi-if contains_harness codex; then info "Codex: $PLUGIN_ID"; fi+if contains_harness claude; then info "Claude-format: $(list_words "$CLAUDE_BINS") -> $PLUGIN_ID"; fi+if contains_harness codex; then info "Codex-format: $(list_words "$CODEX_BINS") -> $PLUGIN_ID"; fi+if contains_harness opencode; then info "OpenCode: @openviking/opencode-plugin"; fi+if contains_harness pi; then info "pi: ~/.pi/agent/extensions/openviking"; fidiff --git a/examples/memory-plugin-shared/lib/capture-utils.mjs b/examples/memory-plugin-shared/lib/capture-utils.mjsindex 005175bad..0eae451ed 100644--- a/examples/memory-plugin-shared/lib/capture-utils.mjs+++ b/examples/memory-plugin-shared/lib/capture-utils.mjs@@ -71,6 +71,17 @@ function stringifyCompact(value, maxChars) {}}+function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}+function blockText(block) {if (!block || typeof block !== "object") return "";if (typeof block.text === "string") return block.text;@@ -114,6 +125,51 @@ function toolPayload(block, kind) {"";}+function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}+function formatToolBlock(block, kind, maxChars) {const name = toolName(block);const payload = toolPayload(block, kind);@@ -192,6 +248,121 @@ export function extractTextFromPayload(payload, options = {}) {return chunks.join("\n\n");}+function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}+export function normalizeCaptureRole(role) {const value = normalizeType(role);if (value === "user") return "user";diff --git a/examples/memory-plugin-shared/lib/credentials.mjs b/examples/memory-plugin-shared/lib/credentials.mjsindex dd94e089a..4cfad5b5f 100644--- a/examples/memory-plugin-shared/lib/credentials.mjs+++ b/examples/memory-plugin-shared/lib/credentials.mjs@@ -94,13 +94,24 @@ function sourceMode(env) {return "auto";}-function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+function hasEnvCredentialFields(env) {+ return Boolean(+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||+ str(env.OPENVIKING_MCP_URL, "") ||+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(env.OPENVIKING_USER, "") ||+ str(env.OPENVIKING_PEER_ID, ""),+ );+}++function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));const cliUrl = str(cliFile.url, "");+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");- if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");- if (!useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");const server = ovFile.server || {};const ovUrl = str(server.url, "");@@ -114,11 +125,13 @@ function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {export function resolveOpenVikingCredentials(env = process.env) {const files = loadCredentialFiles(env);const mode = sourceMode(env);- const useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const envHasCredentials = hasEnvCredentialFields(env);+ const useCli = mode === "cli" ||+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));const cx = files.ovFile.codex || {};const server = files.ovFile.server || {};- const baseUrl = deriveBaseUrl({ env, ...files, useCli });+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });const apiKey = useCli? str(files.cliFile.api_key, "")@@ -155,11 +168,11 @@ export function resolveOpenVikingCredentials(env = process.env) {);const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");- const mcpUrl = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;return {...files,- credentialSource: useCli ? "ovcli" : (mode === "env" ? "env" : "auto"),+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),baseUrl,mcpUrl,apiKey,diff --git a/examples/memory-plugin-shared/lib/pending-queue.mjs b/examples/memory-plugin-shared/lib/pending-queue.mjsindex bae9a1981..e049de794 100644--- a/examples/memory-plugin-shared/lib/pending-queue.mjs+++ b/examples/memory-plugin-shared/lib/pending-queue.mjs@@ -396,7 +396,7 @@ export async function replayPending(fetchJSON, log) {} else if (entry.type === "commitSession") {res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {method: "POST",- body: JSON.stringify({}),+ body: JSON.stringify(entry.payload || {}),});} else {await dequeue(claimedFilename);diff --git a/examples/memory-plugin-shared/lib/profile-inject.mjs b/examples/memory-plugin-shared/lib/profile-inject.mjsnew file mode 100644index 000000000..1b4bec26a--- /dev/null+++ b/examples/memory-plugin-shared/lib/profile-inject.mjs@@ -0,0 +1,293 @@+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url, {}, { actorPeerId });+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/memory-plugin-shared/lib/recall-core.mjs b/examples/memory-plugin-shared/lib/recall-core.mjsnew file mode 100644index 000000000..0041c679c--- /dev/null+++ b/examples/memory-plugin-shared/lib/recall-core.mjs@@ -0,0 +1,281 @@+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },+];++let userSpaceCache = "";++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);+ return {+ query: "",+ quotas: {+ events: limit,+ entities: limit,+ preferences: Math.max(1, Math.min(limit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (userSpaceCache) return userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ if (items.length === 0) return null;++ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),+ });++ return lines.join("\n");+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}++export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return null;++ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);+ if (endpointBlock !== null) return endpointBlock || null;++ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return null;++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return null;+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}diff --git a/examples/memory-plugin-shared/lib/uri-guard.mjs b/examples/memory-plugin-shared/lib/uri-guard.mjsnew file mode 100644index 000000000..84906f32e--- /dev/null+++ b/examples/memory-plugin-shared/lib/uri-guard.mjs@@ -0,0 +1,55 @@+const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+ "pattern",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args);+}++export function findVikingUriInValue(value) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}diff --git a/examples/memory-plugin-shared/recall-core.test.mjs b/examples/memory-plugin-shared/recall-core.test.mjsnew file mode 100644index 000000000..c60527b4c--- /dev/null+++ b/examples/memory-plugin-shared/recall-core.test.mjs@@ -0,0 +1,80 @@+import test from "node:test";+import assert from "node:assert/strict";+import { buildRecallBlock, buildRecallEndpointBody } from "./lib/recall-core.mjs";++test("buildRecallEndpointBody maps quotas and max chars", () => {+ const body = buildRecallEndpointBody({+ recallLimit: 6,+ recallMaxContentChars: 500,+ scoreThreshold: 0.35,+ });+ assert.deepEqual(body.quotas, {+ events: 6,+ entities: 6,+ preferences: 3,+ experiences: 0,+ });+ assert.equal(body.max_chars, 3000);+ assert.equal(body.min_score, 0.35);+ assert.equal(body.render, true);+});++test("buildRecallBlock uses recall endpoint render when available", async () => {+ const calls = [];+ const block = await buildRecallBlock(async (path, init) => {+ calls.push({ path, body: init?.body ? JSON.parse(init.body) : null });+ return { ok: true, result: { rendered: "- [memory 90%] viking://user/default/memories/a.md" } };+ }, {+ recallLimit: 2,+ recallMaxContentChars: 500,+ scoreThreshold: 0.35,+ }, "hello world");++ assert.equal(calls[0].path, "/api/v1/search/recall");+ assert.equal(calls[0].body.quotas.events, 2);+ assert.match(block, /^<openviking-context>/);+ assert.match(block, /Relevant memory from OpenViking/);+ assert.match(block, /viking:\/\/user\/default\/memories\/a\.md/);+ assert.match(block, /<\/openviking-context>$/);+});++test("buildRecallBlock falls back to find and keeps first item over budget", async () => {+ const calls = [];+ const longAbstract = "x".repeat(1200);+ const fetchJSON = async (path) => {+ calls.push(path);+ if (path === "/api/v1/search/recall") return { ok: false, status: 404 };+ if (path === "/api/v1/system/status") return { ok: true, result: { user: "default" } };+ if (path.startsWith("/api/v1/fs/ls")) return { ok: true, result: [] };+ if (path === "/api/v1/search/find") {+ return {+ ok: true,+ result: {+ memories: [{+ uri: "viking://user/default/memories/events/a.md",+ score: 0.9,+ abstract: longAbstract,+ level: 1,+ category: "events",+ }],+ skills: [],+ },+ };+ }+ return { ok: false, status: 404 };+ };++ const block = await buildRecallBlock(fetchJSON, {+ recallLimit: 1,+ recallMaxContentChars: 500,+ recallTokenBudget: 20,+ scoreThreshold: 0.35,+ recallPreferAbstract: true,+ }, "what happened yesterday");++ assert.ok(calls.includes("/api/v1/search/recall"));+ assert.ok(calls.includes("/api/v1/search/find"));+ assert.match(block, /^<openviking-context>/);+ assert.match(block, /\[memory 90%\]/);+ assert.match(block, /x{100}/);+});diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsindex b992b2d04..b4411e152 100644--- a/examples/memory-plugin-shared/sync.mjs+++ b/examples/memory-plugin-shared/sync.mjs@@ -6,9 +6,23 @@ import { fileURLToPath } from "node:url";const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");const SHARED_DIR = join(ROOT, "examples", "memory-plugin-shared", "lib");+const HARNESS_SHARED_FILES = [+ "credentials.mjs",+ "capture-utils.mjs",+ "session-model.mjs",+ "pending-queue.mjs",+ "debug-log.mjs",+ "setup-wizard.mjs",+ "recall-core.mjs",+ "profile-inject.mjs",+ "uri-guard.mjs",+];+const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs"];const TARGETS = [- join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"),- join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"),+ { dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: null },+ { dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: null },+ { dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },+ { dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },];const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";@@ -27,11 +41,15 @@ async function copySharedFile(file, targetDir) {}async function main() {- const files = await listSharedFiles();- for (const targetDir of TARGETS) {+ const allFiles = await listSharedFiles();+ for (const target of TARGETS) {+ const files = target.files ?? allFiles;for (const file of files) {- await copySharedFile(file, targetDir);- process.stdout.write(`synced ${file} -> ${relative(ROOT, targetDir)}\n`);+ if (!allFiles.includes(file)) {+ throw new Error(`shared file not found: ${file}`);+ }+ await copySharedFile(file, target.dir);+ process.stdout.write(`synced ${file} -> ${relative(ROOT, target.dir)}\n`);}}}diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjsindex d2d2454ff..0405bec75 100644--- a/examples/memory-plugin-shared/sync.test.mjs+++ b/examples/memory-plugin-shared/sync.test.mjs@@ -6,9 +6,23 @@ import { fileURLToPath } from "node:url";const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");const SHARED_DIR = join(ROOT, "examples", "memory-plugin-shared", "lib");+const HARNESS_SHARED_FILES = [+ "credentials.mjs",+ "capture-utils.mjs",+ "session-model.mjs",+ "pending-queue.mjs",+ "debug-log.mjs",+ "setup-wizard.mjs",+ "recall-core.mjs",+ "profile-inject.mjs",+ "uri-guard.mjs",+];+const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs"];const TARGETS = [- join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"),- join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"),+ { dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: null },+ { dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: null },+ { dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },+ { dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },];const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";@@ -16,14 +30,16 @@ test("vendored shared modules are synchronized", async () => {const files = (await readdir(SHARED_DIR)).filter((file) => file.endsWith(".mjs")).sort();assert.ok(files.length > 0, "expected shared modules");- for (const targetDir of TARGETS) {+ for (const target of TARGETS) {+ const targetFiles = target.files ?? files;for (const file of files) {+ if (!targetFiles.includes(file)) continue;const expected = `${GENERATED_HEADER}${await readFile(join(SHARED_DIR, file), "utf-8")}`;- const actual = await readFile(join(targetDir, file), "utf-8");+ const actual = await readFile(join(target.dir, file), "utf-8");assert.equal(actual,expected,- `${relative(ROOT, join(targetDir, file))} is out of sync; run node examples/memory-plugin-shared/sync.mjs`,+ `${relative(ROOT, join(target.dir, file))} is out of sync; run node examples/memory-plugin-shared/sync.mjs`,);}}diff --git a/examples/memory-plugin-shared/uri-guard.test.mjs b/examples/memory-plugin-shared/uri-guard.test.mjsnew file mode 100644index 000000000..238dcec6a--- /dev/null+++ b/examples/memory-plugin-shared/uri-guard.test.mjs@@ -0,0 +1,36 @@+import test from "node:test"+import assert from "node:assert/strict"+import { buildGuardMessage, findVikingUri, findVikingUriInValue, normalizeToolName } from "./lib/uri-guard.mjs"++test("findVikingUri detects common path and URI argument keys", () => {+ assert.equal(findVikingUri({ filePath: "viking://resources/a.md" }), "viking://resources/a.md")+ assert.equal(findVikingUri({ file_path: "viking://resources/b.md" }), "viking://resources/b.md")+ assert.equal(findVikingUri({ target_uri: "viking://resources/c/" }), "viking://resources/c/")+ assert.equal(findVikingUri({ path: "/tmp/file.md" }), null)+})++test("findVikingUri detects nested command strings", () => {+ assert.equal(+ findVikingUri({ args: { command: "cat viking://resources/project/file.md" } }),+ "viking://resources/project/file.md",+ )+ assert.equal(+ findVikingUriInValue(["grep", "needle", "viking://resources/project/"]),+ "viking://resources/project/",+ )+})++test("buildGuardMessage names replacement tool and example", () => {+ const message = buildGuardMessage("viking://resources/project/file.md", {+ tool: "openviking_read",+ example: 'openviking_read(uri="viking://resources/project/file.md")',+ })++ assert.match(message, /virtual paths/)+ assert.match(message, /Use openviking_read instead/)+ assert.match(message, /Example:/)+})++test("normalizeToolName trims and lowercases", () => {+ assert.equal(normalizeToolName(" Read "), "read")+})diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex 264262aaf..761616b92 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -2,10 +2,10 @@这个插件新增了一个面向 OpenCode 的统一 OpenViking 插件:-- 外部仓库语义检索+- 面向 memory、resources 和 code context 的 OpenViking MCP 工具- 长期记忆、session 同步、生命周期边界 commit、自动 recall-这是仓库中唯一继续维护的 OpenCode 插件示例。这个插件不再安装 `skills/openviking/SKILL.md`,也不要求 agent 使用 `ov` 命令。原 skill 风格的能力会通过 OpenCode tools 暴露。+这是仓库中唯一继续维护的 OpenCode 插件示例。这个插件不再安装 `skills/openviking/SKILL.md`,也不要求 agent 使用 `ov` 命令。模型工具由 Claude Code 和 Codex 记忆插件同款的 stdio MCP proxy 提供。## 前置条件@@ -13,7 +13,7 @@- OpenCode- OpenViking HTTP Server-- Node.js / npm,用于安装插件依赖+- Node.js 18+- 如果服务端启用了认证,需要可用的 OpenViking API Key建议先启动 OpenViking:@@ -53,8 +53,7 @@ mkdir -p ~/.config/opencode/plugins/openvikingcp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.jscp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install+cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/```安装后结构应类似:@@ -66,7 +65,7 @@ npm install├── index.mjs├── package.json├── lib/- └── node_modules/+ └── servers/```顶层 `openviking.js` 只负责把 OpenCode 能发现的一级 `.js` 入口转发到插件目录:@@ -92,22 +91,22 @@ export { OpenVikingPlugin, default } from "./openviking/index.mjs"```json{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },"autoRecall": {"enabled": true,"limit": 6,- "scoreThreshold": 0.15,+ "scoreThreshold": 0.35,"maxContentChars": 500,"preferAbstract": true,- "tokenBudget": 2000- }+ "tokenBudget": 2000,+ "minQueryLength": 3+ },+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000}```@@ -117,7 +116,7 @@ export { OpenVikingPlugin, default } from "./openviking/index.mjs"export OPENVIKING_API_KEY="your-api-key-here"```-`apiKey` 会作为 `X-API-Key` 发送。`account` 和 `user` 是 trusted mode+API key 会从环境变量或 `~/.openviking/ovcli.conf` 读取,并由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送。`account` 和 `user` 是 trusted mode身份头,会作为 `X-OpenViking-Account`、`X-OpenViking-User` 发送;使用user/admin API key 的 API_KEY mode 时应留空。`peerId` 会作为 `X-OpenViking-Actor-Peer` 用于数据面的 memory/resource 请求;捕获 session message 时仍写入 body `peer_id`。需要 peer 维度路由时请显式配置。@@ -132,13 +131,13 @@ user/admin API key 的 API_KEY mode 时应留空。修改插件或 OpenViking 配置后,需要重启 OpenCode。-进入新的 OpenCode session 后,可以让 agent 浏览 OpenViking memory,或搜索一个已索引的资源。插件应暴露这些 tools:+进入新的 OpenCode session 后,可以让 agent 浏览 OpenViking memory,或搜索一个已索引的资源。插件应暴露 OpenViking MCP server,OpenCode 中的工具名会带 `openviking_` 前缀:-- `memsearch`、`memread`、`membrowse`-- `memgrep`、`memglob`-- `memadd`、`memwrite`、`memremove`、`memqueue`-- `memcommit`-- `codesearch`、`codeoutline`、`codeexpand`+- `openviking_recall`、`openviking_search`、`openviking_find`+- `openviking_read`、`openviking_list`、`openviking_grep`、`openviking_glob`+- `openviking_remember`、`openviking_add_resource`、`openviking_forget`、`openviking_health`+- `openviking_list_watches`、`openviking_cancel_watch`+- `openviking_code_search`、`openviking_code_outline`、`openviking_code_expand`如果行为异常,先查看运行时文件:@@ -153,35 +152,37 @@ tail -n 100 ~/.config/opencode/openviking/openviking-memory.logcurl http://localhost:1933/health```-## 可用工具+## 可用 MCP 工具-插件会通过 OpenCode `tool` hook 暴露这些工具:+插件会通过 OpenCode config 注册 OpenViking stdio MCP proxy。服务端实际返回的 `tools/list` 是最终工具清单;当前 OpenViking server 暴露:-- `memsearch`:语义检索 memories/resources/skills-- `memread`:读取具体 `viking://` URI-- `membrowse`:浏览 OpenViking 文件系统-- `memcommit`:提交当前 session 并触发记忆提取-- `memgrep`:精确文本或模式搜索,替代原 `ov grep`-- `memglob`:文件 glob 枚举,替代原 `ov glob`-- `memadd`:添加远端 URL 或本地文件资源,替代常见 `ov add-resource` 场景-- `memwrite`:通过 `/api/v1/content/write` 直接写入 `viking://` 文本文件-- `memremove`:删除资源,替代 `ov rm`-- `memqueue`:查看处理队列,替代 `ov observer queue`+- `openviking_recall`:面向当前任务的平衡召回+- `openviking_search`:跨 memories/resources/skills 的深度语义检索+- `openviking_find`:快速语义检索+- `openviking_remember`:存储重要事实或决策,供记忆提取+- `openviking_read`:读取一个或多个 `viking://` 文件+- `openviking_list`:列出 `viking://` 目录+- `openviking_grep`:精确文本或正则搜索+- `openviking_glob`:glob 文件匹配+- `openviking_add_resource`:添加 URL、本地文件、sitemap 或 feed+- `openviking_forget`:在用户明确确认后删除 `viking://` URI+- `openviking_list_watches` / `openviking_cancel_watch`:查看或取消资源 watch+- `openviking_code_search`、`openviking_code_outline`、`openviking_code_expand`:查看已索引代码符号+- `openviking_health`:检查 OpenViking server 健康状态使用建议:-- 概念性问题用 `memsearch`-- 精确符号、函数名、类名、报错字符串用 `memgrep`-- 枚举文件用 `memglob`-- 读取内容用 `memread`-- 探索目录结构用 `membrowse`-- 持久化笔记或小型文本更新用 `memwrite`;默认是 `create`,避免误覆盖-- 删除前必须先获得用户明确确认,再调用 `memremove` 且传入 `confirm: true`-- 如果 agent 误用 OpenCode 本地 `read`、`glob`、`grep` 工具访问 `viking://` URI,插件会阻止这次本地文件系统调用,并提示改用 `memread`、`membrowse` 或 `memsearch`。+- 概念性问题用 `openviking_search`+- 精确符号、函数名、类名、报错字符串用 `openviking_grep`+- 枚举文件用 `openviking_glob`+- 读取内容用 `openviking_read`+- 探索目录结构用 `openviking_list`+- 删除前必须先获得用户明确确认,再调用 `openviking_forget`+- 如果 agent 误用 OpenCode 本地 `read`、`glob`、`grep` 工具访问 `viking://` URI,插件会阻止这次本地文件系统调用,并提示改用 MCP 工具。-## `memadd` 本地文件+## `openviking_add_resource` 本地文件-`memadd` 支持三类输入:+`openviking_add_resource` 支持三类输入:- 远端 `http(s)` URL:直接调用 `/api/v1/resources`- 本地文件路径:先调用 `/api/v1/resources/temp_upload`,再用返回的 `temp_file_id` 添加资源@@ -190,9 +191,9 @@ curl http://localhost:1933/health相对路径会按 OpenCode 当前项目目录解析。示例:```text-memadd path="https://example.com/spec.md" to="viking://resources/spec"-memadd path="./docs/notes.md" parent="viking://resources/"-memadd path="file:///home/alice/project/notes.md" reason="project notes"+openviking_add_resource(path="https://example.com/spec.md", to="viking://resources/spec")+openviking_add_resource(path="./docs/notes.md", to="viking://resources/notes.md")+openviking_add_resource(path="file:///home/alice/project/notes.md", description="project notes")```当前仍不支持本地目录自动打 zip 上传;传入目录时会返回明确错误。@@ -208,7 +209,7 @@ memadd path="file:///home/alice/project/notes.md" reason="project notes"可能包含:- `openviking-memory.log`-- `openviking-session-map.json`+- `openviking-session-state.json`可以通过配置里的 `runtime.dataDir` 修改这个目录。@@ -219,7 +220,7 @@ memadd path="file:///home/alice/project/notes.md" reason="project notes"| 问题 | 排查方向 ||------|----------|| 插件没有加载 | package 安装检查 `~/.config/opencode/opencode.json` 是否包含 `@openviking/opencode-plugin`;源码安装检查 `~/.config/opencode/plugins/openviking.js` 是否存在 |-| Tools 连到了错误的 server | 检查 `~/.config/opencode/openviking-config.json` 里的 `endpoint`,或用 `OPENVIKING_PLUGIN_CONFIG` 指向正确配置文件 |+| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量 / `OPENVIKING_PLUGIN_CONFIG` 指向正确配置 || OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` || recall 为空 | 确认 OpenViking 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |-| 本地 `memadd` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |+| 本地 `openviking_add_resource` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex 4cee0c3ce..08f412f48 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -2,10 +2,10 @@This plugin adds one unified OpenViking plugin for OpenCode:-- Semantic retrieval for external repositories+- OpenViking MCP tools for memory, resources, and code context- Long-term memory, session synchronization, lifecycle commit, and automatic recall-This is the only OpenCode plugin example maintained in this repository. It does not install `skills/openviking/SKILL.md`, and it does not require the agent to use the `ov` command. The former skill-style capabilities are exposed as OpenCode tools here.+This is the only OpenCode plugin example maintained in this repository. It does not install `skills/openviking/SKILL.md`, and it does not require the agent to use the `ov` command. Model tools are provided by the same stdio MCP proxy used by the Claude Code and Codex memory plugins.## Prerequisites@@ -13,7 +13,7 @@ Prepare the following first:- OpenCode- OpenViking HTTP Server-- Node.js / npm, used to install plugin dependencies+- Node.js 18+- A valid OpenViking API key if authentication is enabled on the serverStart OpenViking first:@@ -53,8 +53,7 @@ mkdir -p ~/.config/opencode/plugins/openvikingcp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.jscp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install+cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/```After installation, the layout should look like this:@@ -66,7 +65,7 @@ After installation, the layout should look like this:├── index.mjs├── package.json├── lib/- └── node_modules/+ └── servers/```The top-level `openviking.js` forwards the first-level `.js` entry that OpenCode can discover to the actual plugin directory:@@ -92,22 +91,22 @@ Example configuration:```json{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },"autoRecall": {"enabled": true,"limit": 6,- "scoreThreshold": 0.15,+ "scoreThreshold": 0.35,"maxContentChars": 500,"preferAbstract": true,- "tokenBudget": 2000- }+ "tokenBudget": 2000,+ "minQueryLength": 3+ },+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000}```@@ -117,7 +116,7 @@ It is recommended to provide the API key through an environment variable insteadexport OPENVIKING_API_KEY="your-api-key-here"```-`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`.+API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`.`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `openviking-config.json`.@@ -127,13 +126,13 @@ For advanced setups, use `OPENVIKING_PLUGIN_CONFIG` to point to another configurRestart OpenCode after changing plugin or OpenViking configuration.-In a new OpenCode session, ask the agent to browse OpenViking memory or search for a known indexed resource. The plugin should expose these tools:+In a new OpenCode session, ask the agent to browse OpenViking memory or search for a known indexed resource. The plugin should expose the OpenViking MCP server, with tools namespaced by OpenCode as `openviking_*`:-- `memsearch`, `memread`, `membrowse`-- `memgrep`, `memglob`-- `memadd`, `memwrite`, `memremove`, `memqueue`-- `memcommit`-- `codesearch`, `codeoutline`, `codeexpand`+- `openviking_recall`, `openviking_search`, `openviking_find`+- `openviking_read`, `openviking_list`, `openviking_grep`, `openviking_glob`+- `openviking_remember`, `openviking_add_resource`, `openviking_forget`, `openviking_health`+- `openviking_list_watches`, `openviking_cancel_watch`+- `openviking_code_search`, `openviking_code_outline`, `openviking_code_expand`If anything looks wrong, check the runtime files:@@ -148,35 +147,37 @@ For a local server, also confirm OpenViking is reachable:curl http://localhost:1933/health```-## Available Tools+## Available MCP Tools-The plugin exposes the following tools through the OpenCode `tool` hook:+The plugin registers OpenViking's stdio MCP proxy through OpenCode config. The server's real `tools/list` response is the source of truth; current OpenViking servers expose:-- `memsearch`: semantic retrieval across memories, resources, and skills-- `memread`: read a specific `viking://` URI-- `membrowse`: browse the OpenViking filesystem-- `memcommit`: commit the current session and trigger memory extraction-- `memgrep`: exact text or pattern search, replacing the former `ov grep` use case-- `memglob`: file glob enumeration, replacing the former `ov glob` use case-- `memadd`: add a remote URL or local file resource, replacing common `ov add-resource` scenarios-- `memwrite`: write text to a `viking://` file through `/api/v1/content/write`-- `memremove`: remove resources, replacing `ov rm`-- `memqueue`: inspect the processing queue, replacing `ov observer queue`+- `openviking_recall`: balanced current-task recall.+- `openviking_search`: deep semantic retrieval across memories, resources, and skills.+- `openviking_find`: fast semantic retrieval.+- `openviking_remember`: store important facts or decisions for memory extraction.+- `openviking_read`: read one or more `viking://` files.+- `openviking_list`: list a `viking://` directory.+- `openviking_grep`: exact text or regex search.+- `openviking_glob`: glob file matching.+- `openviking_add_resource`: add a URL, local file, sitemap, or feed.+- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.+- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.+- `openviking_code_search`, `openviking_code_outline`, `openviking_code_expand`: inspect indexed code symbols.+- `openviking_health`: check OpenViking server health.Usage guidance:-- Use `memsearch` for conceptual questions.-- Use `memgrep` for exact symbols, function names, class names, or error strings.-- Use `memglob` to enumerate files.-- Use `memread` to read content.-- Use `membrowse` to explore directory structure.-- Use `memwrite` for durable notes or small direct text updates; default mode is `create`.-- Before deleting anything, obtain explicit user confirmation first; then call `memremove` with `confirm: true`.-- If an agent tries to use OpenCode's local `read`, `glob`, or `grep` tools on a `viking://` URI, the plugin blocks that call and points it to `memread`, `membrowse`, or `memsearch`.+- Use `openviking_search` for conceptual questions.+- Use `openviking_grep` for exact symbols, function names, class names, or error strings.+- Use `openviking_glob` to enumerate files.+- Use `openviking_read` to read content.+- Use `openviking_list` to explore directory structure.+- Before deleting anything, obtain explicit user confirmation first; then call `openviking_forget`.+- If an agent tries to use OpenCode's local `read`, `glob`, or `grep` tools on a `viking://` URI, the plugin blocks that call and points it to the MCP tools.-## Local Files with `memadd`+## Local Files with `openviking_add_resource`-`memadd` supports three input types:+`openviking_add_resource` supports three input types:- Remote `http(s)` URL: directly calls `/api/v1/resources`- Local file path: first calls `/api/v1/resources/temp_upload`, then adds the resource using the returned `temp_file_id`@@ -185,9 +186,9 @@ Usage guidance:Relative paths are resolved against the current OpenCode project directory. Examples:```text-memadd path="https://example.com/spec.md" to="viking://resources/spec"-memadd path="./docs/notes.md" parent="viking://resources/"-memadd path="file:///home/alice/project/notes.md" reason="project notes"+openviking_add_resource(path="https://example.com/spec.md", to="viking://resources/spec")+openviking_add_resource(path="./docs/notes.md", to="viking://resources/notes.md")+openviking_add_resource(path="file:///home/alice/project/notes.md", description="project notes")```Automatic zip upload for local directories is not supported yet. Passing a directory will return a clear error.@@ -203,7 +204,7 @@ By default, the plugin writes runtime files to:Possible files include:- `openviking-memory.log`-- `openviking-session-map.json`+- `openviking-session-state.json`You can change this directory with `runtime.dataDir` in the configuration.@@ -214,7 +215,7 @@ These are local runtime files and should not be committed to the repository.| Issue | What to check ||-------|---------------|| Plugin does not load | For package installs, confirm `~/.config/opencode/opencode.json` contains `@openviking/opencode-plugin`; for source installs, confirm `~/.config/opencode/plugins/openviking.js` exists |-| Tools call the wrong server | Check `endpoint` in `~/.config/opencode/openviking-config.json`, or set `OPENVIKING_PLUGIN_CONFIG` to the intended config path |+| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_PLUGIN_CONFIG` to the intended config path || 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` || Recall is empty | Confirm OpenViking has indexed memories/resources and `autoRecall.enabled` is `true` |-| Local `memadd` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |+| Local `openviking_add_resource` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex 0371d6178..96acb2d41 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -4,17 +4,17 @@ A unified OpenCode plugin for OpenViking repository retrieval and long-term memoThis is the only OpenCode plugin example maintained in this repository. It supersedes the former split examples for indexed repository prompt injection and long-term memory.-The new plugin exposes everything through OpenCode tool hooks and talks to OpenViking through HTTP APIs. It does not install or require an OpenCode skill, and agents do not need to run `ov` shell commands.+The plugin uses OpenCode hooks for lifecycle behavior and registers OpenViking's standard stdio MCP proxy for model tools. It does not install or require an OpenCode skill, and agents do not need to run `ov` shell commands.## What It Does- Injects indexed `viking://resources/` repositories into the system prompt.-- Exposes repository search, grep, glob, read, browse, add, write, remove, and queue status as tools.+- Exposes the same OpenViking MCP tools used by the Claude Code and Codex memory plugins.- Maps each OpenCode session to an OpenViking session.- Captures user and assistant text messages into OpenViking.- Commits sessions at lifecycle boundaries for memory extraction.- Automatically recalls relevant memories and injects them as hidden synthetic context for the current user message.-- Blocks accidental local filesystem reads of `viking://` URIs and points the agent back to `memread`, `membrowse`, or `memsearch`.+- Blocks accidental local filesystem reads of `viking://` URIs and points the agent back to `openviking_read`, `openviking_glob`, or `openviking_search`.## Files@@ -25,26 +25,29 @@ examples/opencode-plugin/├── README.md├── INSTALL-ZH.md├── lib/+│ ├── config.mjs+│ ├── mcp-config.mjs│ ├── runtime.mjs│ ├── repo-context.mjs│ ├── memory-session.mjs-│ ├── memadd-local.mjs-│ ├── memory-tools.mjs│ ├── memory-recall.mjs+│ ├── session-inject.mjs│ ├── viking-uri-guard.mjs│ └── utils.mjs+├── servers/+│ └── mcp-proxy.mjs├── tests/└── wrappers/└── openviking.js```-There is intentionally no `skills/openviking/SKILL.md`. The former skill behavior is implemented as tools.+There is intentionally no `skills/openviking/SKILL.md`. The tool surface comes from OpenViking's MCP endpoint.## Requirements- OpenCode- OpenViking HTTP server-- Node.js / npm for installing the plugin dependency+- Node.js 18+- An OpenViking API key if your server requires authenticationStart OpenViking first:@@ -80,8 +83,7 @@ mkdir -p ~/.config/opencode/plugins/openvikingcp examples/opencode-plugin/wrappers/openviking.js ~/.config/opencode/plugins/openviking.jscp examples/opencode-plugin/index.mjs examples/opencode-plugin/package.json ~/.config/opencode/plugins/openviking/cp -r examples/opencode-plugin/lib ~/.config/opencode/plugins/openviking/-cd ~/.config/opencode/plugins/openviking-npm install+cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/```This creates a stable OpenCode plugin layout:@@ -93,7 +95,7 @@ This creates a stable OpenCode plugin layout:├── index.mjs├── package.json├── lib/- └── node_modules/+ └── servers/```The top-level `openviking.js` is only a wrapper:@@ -111,26 +113,26 @@ Create `~/.config/opencode/openviking-config.json`:```json{- "endpoint": "http://localhost:1933",- "apiKey": "",- "account": "",- "user": "",- "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },"autoRecall": {"enabled": true,"limit": 6,- "scoreThreshold": 0.15,+ "scoreThreshold": 0.35,"maxContentChars": 500,"preferAbstract": true,- "tokenBudget": 2000- }+ "tokenBudget": 2000,+ "minQueryLength": 3+ },+ "commitTokenThreshold": 20000,+ "commitKeepRecentCount": 10,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000}```-`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity+API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode identityheaders sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them emptywhen using API-key mode with user/admin API keys.`peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource@@ -138,124 +140,39 @@ requests; captured session messages store it as body `peer_id`. Configure`peerId` explicitly when peer-scoped memory routing is needed.`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`,-and `OPENVIKING_PEER_ID` take-precedence over values in this file.+and `OPENVIKING_PEER_ID` take precedence over values in this file.For advanced setups, `OPENVIKING_PLUGIN_CONFIG` can point to another config file path.OpenCode's local `read`, `glob`, and `grep` tools cannot read `viking://` URIs.When the agent accidentally tries that, the plugin blocks the filesystem tool-call and points it to `memread`, `membrowse`, or `memsearch`.+call and points it to the OpenViking MCP tools.-## Tools+## MCP Tools-### `memsearch`+OpenCode sees the OpenViking MCP server as `openviking`, so tool names are namespaced with `openviking_`.-Semantic search across memories, resources, and skills.+- `openviking_recall`: balanced current-task recall using OpenViking's `/recall` endpoint.+- `openviking_search`: deep semantic retrieval across memories, resources, and skills.+- `openviking_find`: fast semantic retrieval.+- `openviking_remember`: store important facts or decisions for memory extraction.+- `openviking_read`: read one or more `viking://` files.+- `openviking_list`: list a `viking://` directory.+- `openviking_grep`: exact text or regex search.+- `openviking_glob`: glob file matching.+- `openviking_add_resource`: add a URL, local file, sitemap, or feed.+- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.+- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.+- `openviking_code_search`, `openviking_code_outline`, `openviking_code_expand`: inspect indexed code symbols.+- `openviking_health`: check OpenViking server health.-Use for conceptual questions, repository internals, user preferences, and context-aware retrieval. Use `target_uri` to narrow scope, for example `viking://resources/fastapi/`.--### `memread`--Read a specific `viking://` URI using `abstract`, `overview`, `read`, or `auto`.--Use after `memsearch`, `memgrep`, `memglob`, or `membrowse` returns a URI.--### `membrowse`--Browse OpenViking filesystem structure with `list`, `tree`, or `stat`.--Use to discover exact URIs before reading content.--### `memcommit`--Commit the current OpenCode session to OpenViking and trigger memory extraction.--The plugin also commits at session deletion, session error, compaction, and plugin shutdown boundaries.--### `memgrep`--Pattern search through OpenViking content.--Use for exact symbols, class names, function names, error strings, or known keywords.--### `memglob`--Glob file matching through OpenViking content.--Use to enumerate files such as `**/*.py`, `**/test_*.ts`, or `**/*.md`.--### `memadd`--Add a remote URL or local file resource to OpenViking.--Remote `http(s)` URLs go directly through `POST /api/v1/resources`.-Local files use the safer two-step server flow: upload the file to-`POST /api/v1/resources/temp_upload`, then add it through-`POST /api/v1/resources` with the returned `temp_file_id`.--Local paths may be absolute, relative to the OpenCode project directory, or-`file://` URLs. Local directory upload is not supported yet.--Examples:--```text-memadd path="https://example.com/spec.md" to="viking://resources/spec"-memadd path="./docs/notes.md" parent="viking://resources/"-memadd path="file:///home/alice/project/notes.md" reason="project notes"-```--After adding a resource, the tool also returns `GET /api/v1/observer/queue` status.--### `memwrite`--Write text content to a `viking://` file through `POST /api/v1/content/write`.--Use this for durable notes, small project memory files, or resource text that-should be updated directly. The default mode is `create` to avoid accidental-overwrites. Use `append` to extend an existing file and `replace` only when the-user explicitly wants to overwrite the file.--Examples:--```text-memwrite uri="viking://user/memories/project-notes.md" content="# Decision\n\nUse PostgreSQL." wait=true-memwrite uri="viking://resources/docs/api.md" content="\n\n## New endpoint" mode="append"-```--### `memremove`--Remove a `viking://` URI through `DELETE /api/v1/fs`.--This tool requires `confirm: true`. The user must explicitly confirm deletion before the agent calls it.--### `memqueue`--Return OpenViking observer queue status for embedding and semantic processing.--### `codesearch`--Search AST-supported symbol names across a confirmed ingested code repository or source subtree.--Use this after you have evidence that a `viking://` URI contains supported source files.--### `codeoutline`--Show symbol structure for a confirmed `viking://` source file.--Use this after `memglob`, `membrowse`, or `codesearch` finds an exact source file URI.--### `codeexpand`--Return the full source for one named symbol from a confirmed `viking://` source file.--Use this after `codeoutline` or other evidence shows the symbol exists in that file.+The proxy forwards the server's real `tools/list` response; the plugin does not maintain a separate native tool list.## Runtime FilesThe plugin writes runtime files to `~/.config/opencode/openviking/` by default:- `openviking-memory.log`-- `openviking-session-map.json`+- `openviking-session-state.json`Set `runtime.dataDir` in config to override this directory.diff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjsindex 94831bc8a..b6c9e3c3a 100644--- a/examples/opencode-plugin/index.mjs+++ b/examples/opencode-plugin/index.mjs@@ -3,17 +3,15 @@ import { fileURLToPath } from "url"import { initializeRuntime } from "./lib/runtime.mjs"import { createRepoContext } from "./lib/repo-context.mjs"import { createMemorySessionManager } from "./lib/memory-session.mjs"-import { createCodeTools } from "./lib/code-tools.mjs"-import { createMemoryTools } from "./lib/memory-tools.mjs"import { createMemoryRecall } from "./lib/memory-recall.mjs"+import { createSessionInject } from "./lib/session-inject.mjs"import { createVikingUriGuard } from "./lib/viking-uri-guard.mjs"-import { initLogger, loadConfig, log, resolveDataDir } from "./lib/utils.mjs"+import { injectOpenVikingMcpConfig } from "./lib/mcp-config.mjs"+import { loadConfig, resolveDataDir } from "./lib/config.mjs"+import { initLogger, log, makeToast } from "./lib/utils.mjs"const pluginRoot = dirname(fileURLToPath(import.meta.url))-/**- * @type {import('@opencode-ai/plugin').Plugin}- */export async function OpenVikingPlugin({ client, directory }) {const config = loadConfig(pluginRoot, directory)const dataDir = resolveDataDir(pluginRoot, config)@@ -27,11 +25,17 @@ export async function OpenVikingPlugin({ client, directory }) {const repoContext = createRepoContext({ config })const sessionManager = createMemorySessionManager({ config, pluginRoot: dataDir })const recall = createMemoryRecall({ config })+ const sessionInject = createSessionInject({ config, sessionManager })const vikingUriGuard = createVikingUriGuard()- const tools = createMemoryTools({ config, sessionManager, projectDirectory: directory })- const codeTools = createCodeTools({ config })await sessionManager.init()+ const toast = makeToast(client)+ if (config.legacyCredentialsUsed) {+ log("WARN", "config", "Legacy OpenCode credential fields are still in use; run node scripts/setup.mjs to migrate to ovcli.conf", {+ configPath: config.configPath,+ })+ await toast("OpenViking credentials in openviking-config.json are deprecated. Run node scripts/setup.mjs to migrate.", "warning")+ }Promise.resolve().then(async () => {const ready = await initializeRuntime(config, client)@@ -39,6 +43,11 @@ export async function OpenVikingPlugin({ client, directory }) {})return {+ config: async (opencodeConfig) => {+ const injected = injectOpenVikingMcpConfig(opencodeConfig, pluginRoot)+ log(injected ? "INFO" : "WARN", "mcp", injected ? "Registered OpenViking MCP server" : "OpenViking MCP server was not registered")+ },+event: async ({ event }) => {await sessionManager.handleEvent(event)if (event?.type === "session.created") {@@ -48,8 +57,6 @@ export async function OpenVikingPlugin({ client, directory }) {"tool.execute.before": vikingUriGuard,- tool: { ...tools, ...codeTools },-"experimental.chat.system.transform": (_input, output) => {const prompt = repoContext.getRepoSystemPrompt()if (prompt) output.system.push(prompt)@@ -57,6 +64,7 @@ export async function OpenVikingPlugin({ client, directory }) {"chat.message": async (input, output) => {try {+ await sessionInject.injectSessionContext(input, output)if (!config.autoRecall?.enabled) returnawait recall.injectRelevantMemories(input, output)} catch (error) {@@ -74,9 +82,9 @@ export async function OpenVikingPlugin({ client, directory }) {})},- stop: async () => {+ dispose: async () => {await sessionManager.flushAll({ commit: true })- log("INFO", "plugin", "OpenViking plugin stopped")+ log("INFO", "plugin", "OpenViking plugin disposed")},}}diff --git a/examples/opencode-plugin/lib/code-tools.mjs b/examples/opencode-plugin/lib/code-tools.mjsdeleted file mode 100644index 5b8d47636..000000000--- a/examples/opencode-plugin/lib/code-tools.mjs+++ /dev/null@@ -1,134 +0,0 @@-import { tool } from "@opencode-ai/plugin"-import { effectivePeerId, log, makeRequest, unwrapResponse, validateVikingUri } from "./utils.mjs"--const z = tool.schema--const CODE_TOOL_ENDPOINTS = {- search: "/api/v1/code/search",- outline: "/api/v1/code/outline",- expand: "/api/v1/code/expand",-}--function codeToolRequestOptions(kind, { uri, query, symbol, actorPeerId, abortSignal }) {- const body = { uri }- if (kind === "search") body.query = query- if (kind === "expand") body.symbol = symbol-- return {- method: "POST",- endpoint: CODE_TOOL_ENDPOINTS[kind],- body,- abortSignal,- actorPeerId,- }-}--export function createCodeTools({ config }) {- const actorPeerId = effectivePeerId(config)- return {- codesearch: tool({- description:- "Search AST-supported symbol names (classes, functions, methods) by substring across a confirmed viking:// code repository or source subtree. " +- "Use only after you have evidence that the uri contains supported source files. " +- "Use when you do not know which file contains a symbol. " +- "Do not use for general memory search, documentation-only resources, plain text notes, chat/session history, or local filesystem paths. " +- "Returns structured results: symbol name, class context, file URI, line range. " +- "Typical workflow: verify code repo with ls/glob/add_resource output, then codesearch, codeoutline, codeexpand.",- args: {- query: z.string().describe("Symbol name substring to search for (case-insensitive)."),- uri: z- .string()- .describe(- "Viking URI for a confirmed ingested code repository or source subtree. Do not pass a local path or an unverified viking:// directory.",- ),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "codesearch")- if (validationError) return validationError- try {- const response = await makeRequest(config, {- ...codeToolRequestOptions("search", {- uri: args.uri,- query: args.query,- actorPeerId,- abortSignal: context.abort,- }),- })- return unwrapResponse(response)- } catch (error) {- log("ERROR", "codesearch", "Search failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- codeoutline: tool({- description:- "Show the symbol structure of a confirmed viking:// source file: classes, functions, methods, and line spans. " +- "Use only for source files inside an ingested code repository, after you know the exact viking:// file URI. " +- "Do not use on directories, documentation-only files, plain text notes, or files that are not supported source code. " +- "Use read instead when you need the full file content.",- args: {- uri: z- .string()- .describe(- "Viking URI of a confirmed supported source file, e.g. viking://resources/myproject/src/main.py.",- ),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "codeoutline")- if (validationError) return validationError- try {- const response = await makeRequest(config, {- ...codeToolRequestOptions("outline", {- uri: args.uri,- actorPeerId,- abortSignal: context.abort,- }),- })- return unwrapResponse(response)- } catch (error) {- log("ERROR", "codeoutline", "Outline failed", { error: error?.message, uri: args.uri })- return `Error: ${error.message}`- }- },- }),-- codeexpand: tool({- description:- "Return the full source of one named symbol from a confirmed viking:// source file. " +- "Use only after codeoutline or other evidence shows the symbol exists in that file. " +- "Do not use for broad exploration, non-code files, documentation, chat/session history, or unverified viking:// resources. " +- "Accepts 'bar' (top-level function or class) or 'Foo.bar' (method inside class Foo). " +- "For multiple symbols from the same file, read may be more efficient.",- args: {- uri: z- .string()- .describe("Viking URI of the confirmed supported source file containing the symbol."),- symbol: z- .string()- .describe(- "Symbol name: 'foo' for top-level, 'Foo.bar' for a method inside class Foo.",- ),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "codeexpand")- if (validationError) return validationError- try {- const response = await makeRequest(config, {- ...codeToolRequestOptions("expand", {- uri: args.uri,- symbol: args.symbol,- actorPeerId,- abortSignal: context.abort,- }),- })- return unwrapResponse(response)- } catch (error) {- log("ERROR", "codeexpand", "Expand failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),- }-}diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjsnew file mode 100644index 000000000..0a5723a9b--- /dev/null+++ b/examples/opencode-plugin/lib/config.mjs@@ -0,0 +1,272 @@+import fs from "fs"+import path from "path"+import { homedir } from "os"+import { resolveOpenVikingCredentials } from "./shared/credentials.mjs"++const DEFAULT_CONFIG = {+ endpoint: "http://127.0.0.1:1933",+ apiKey: "",+ account: "",+ user: "",+ peerId: "",+ enabled: true,+ timeoutMs: 30000,+ runtime: {+ dataDir: "",+ },+ repoContext: {+ enabled: true,+ cacheTtlMs: 60000,+ },+ autoRecall: {+ enabled: true,+ limit: 6,+ scoreThreshold: 0.35,+ maxContentChars: 500,+ preferAbstract: true,+ tokenBudget: 2000,+ minQueryLength: 3,+ },+ autoCapture: true,+ captureMode: "semantic",+ captureMaxLength: 24000,+ captureAssistantTurns: true,+ captureToolMaxChars: 2000,+ commitTokenThreshold: 20000,+ commitKeepRecentCount: 10,+ profileTokenBudget: 10000,+ resumeContextBudget: 32000,+ noAutoInject: false,+ bypassSession: false,+ bypassSessionPatterns: [],+ debug: false,+ debugLogPath: path.join(homedir(), ".openviking", "logs", "opencode-plugin.log"),+}++function cloneDefaultConfig() {+ return JSON.parse(JSON.stringify(DEFAULT_CONFIG))+}++function normalizeNumber(value, fallback, min, max) {+ const next = Number(value)+ if (!Number.isFinite(next)) return fallback+ return Math.max(min, Math.min(max, next))+}++function envBool(name) {+ const value = process.env[name]+ if (value == null || value === "") return undefined+ const lower = String(value).trim().toLowerCase()+ if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false+ if (lower === "1" || lower === "true" || lower === "yes" || lower === "on") return true+ return undefined+}++function str(value, fallback = "") {+ return typeof value === "string" && value.trim() ? value.trim() : fallback+}++function expandHome(value) {+ if (!value || typeof value !== "string") return value+ if (value === "~") return homedir()+ if (value.startsWith("~/") || value.startsWith("~\\")) return path.join(homedir(), value.slice(2))+ return value+}++function readConfigFile(pluginRoot, projectDirectory) {+ for (const configPath of getConfigPaths(pluginRoot, projectDirectory)) {+ try {+ if (!fs.existsSync(configPath)) continue+ return { path: configPath, data: JSON.parse(fs.readFileSync(configPath, "utf8")) }+ } catch (error) {+ console.warn(`Failed to load OpenViking config from ${configPath}:`, error)+ }+ }+ return { path: "", data: {} }+}++function getConfigPaths(pluginRoot, projectDirectory) {+ const paths = []+ if (process.env.OPENVIKING_PLUGIN_CONFIG) paths.push(expandHome(process.env.OPENVIKING_PLUGIN_CONFIG))+ if (projectDirectory) paths.push(path.join(projectDirectory, ".opencode", "openviking-config.json"))+ paths.push(path.join(homedir(), ".config", "opencode", "openviking-config.json"))+ paths.push(path.join(pluginRoot, "openviking-config.json"))+ return paths+}++function applyLegacyConnection(config, fileConfig) {+ const hasLegacyCredentials = ["endpoint", "apiKey", "account", "user", "peerId"]+ .some((key) => fileConfig[key] !== undefined && fileConfig[key] !== "")+ if (!hasLegacyCredentials) return false++ if (fileConfig.endpoint !== undefined) config.endpoint = fileConfig.endpoint+ if (fileConfig.apiKey !== undefined) config.apiKey = fileConfig.apiKey+ if (fileConfig.account !== undefined) config.account = fileConfig.account+ if (fileConfig.user !== undefined) config.user = fileConfig.user+ if (fileConfig.peerId !== undefined) config.peerId = fileConfig.peerId+ return true+}++function applyBehaviorConfig(config, fileConfig = {}) {+ if (fileConfig.enabled !== undefined) config.enabled = fileConfig.enabled !== false+ if (fileConfig.timeoutMs !== undefined) config.timeoutMs = fileConfig.timeoutMs+ config.runtime = {+ ...DEFAULT_CONFIG.runtime,+ ...(fileConfig.runtime ?? {}),+ }+ config.repoContext = {+ ...DEFAULT_CONFIG.repoContext,+ ...(fileConfig.repoContext ?? {}),+ }++ const autoRecall = fileConfig.autoRecall ?? {}+ config.autoRecall = {+ ...DEFAULT_CONFIG.autoRecall,+ ...autoRecall,+ enabled: autoRecall.enabled !== false,+ limit: autoRecall.limit ?? fileConfig.recallLimit ?? DEFAULT_CONFIG.autoRecall.limit,+ scoreThreshold: autoRecall.scoreThreshold ?? fileConfig.scoreThreshold ?? DEFAULT_CONFIG.autoRecall.scoreThreshold,+ maxContentChars: autoRecall.maxContentChars ?? fileConfig.recallMaxContentChars ?? DEFAULT_CONFIG.autoRecall.maxContentChars,+ preferAbstract: autoRecall.preferAbstract ?? fileConfig.recallPreferAbstract ?? DEFAULT_CONFIG.autoRecall.preferAbstract,+ tokenBudget: autoRecall.tokenBudget ?? fileConfig.recallTokenBudget ?? DEFAULT_CONFIG.autoRecall.tokenBudget,+ minQueryLength: autoRecall.minQueryLength ?? fileConfig.minQueryLength ?? DEFAULT_CONFIG.autoRecall.minQueryLength,+ }++ for (const key of [+ "autoCapture",+ "captureMode",+ "captureMaxLength",+ "captureAssistantTurns",+ "captureToolMaxChars",+ "commitTokenThreshold",+ "commitKeepRecentCount",+ "profileTokenBudget",+ "resumeContextBudget",+ "noAutoInject",+ "bypassSession",+ "bypassSessionPatterns",+ "debug",+ "debugLogPath",+ ]) {+ if (fileConfig[key] !== undefined) config[key] = fileConfig[key]+ }+}++function applyEnv(config) {+ if (process.env.OPENVIKING_TIMEOUT_MS) config.timeoutMs = process.env.OPENVIKING_TIMEOUT_MS+ if (process.env.OPENVIKING_AUTO_RECALL !== undefined) {+ config.autoRecall.enabled = envBool("OPENVIKING_AUTO_RECALL") ?? config.autoRecall.enabled+ }+ if (process.env.OPENVIKING_RECALL_LIMIT) config.autoRecall.limit = process.env.OPENVIKING_RECALL_LIMIT+ if (process.env.OPENVIKING_SCORE_THRESHOLD) config.autoRecall.scoreThreshold = process.env.OPENVIKING_SCORE_THRESHOLD+ if (process.env.OPENVIKING_RECALL_MAX_CONTENT_CHARS) {+ config.autoRecall.maxContentChars = process.env.OPENVIKING_RECALL_MAX_CONTENT_CHARS+ }+ if (process.env.OPENVIKING_RECALL_TOKEN_BUDGET) config.autoRecall.tokenBudget = process.env.OPENVIKING_RECALL_TOKEN_BUDGET+ if (process.env.OPENVIKING_RECALL_PREFER_ABSTRACT !== undefined) {+ config.autoRecall.preferAbstract = envBool("OPENVIKING_RECALL_PREFER_ABSTRACT") ?? config.autoRecall.preferAbstract+ }+ if (process.env.OPENVIKING_MIN_QUERY_LENGTH) config.autoRecall.minQueryLength = process.env.OPENVIKING_MIN_QUERY_LENGTH+ if (process.env.OPENVIKING_AUTO_CAPTURE !== undefined) {+ config.autoCapture = envBool("OPENVIKING_AUTO_CAPTURE") ?? config.autoCapture+ }+ if (process.env.OPENVIKING_CAPTURE_MODE) config.captureMode = process.env.OPENVIKING_CAPTURE_MODE+ if (process.env.OPENVIKING_CAPTURE_MAX_LENGTH) config.captureMaxLength = process.env.OPENVIKING_CAPTURE_MAX_LENGTH+ if (process.env.OPENVIKING_CAPTURE_ASSISTANT_TURNS !== undefined) {+ config.captureAssistantTurns = envBool("OPENVIKING_CAPTURE_ASSISTANT_TURNS") ?? config.captureAssistantTurns+ }+ if (process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS) {+ config.captureToolMaxChars = process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS+ }+ if (process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD) {+ config.commitTokenThreshold = process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD+ }+ if (process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT) {+ config.commitKeepRecentCount = process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT+ }+ if (process.env.OPENVIKING_PROFILE_TOKEN_BUDGET) config.profileTokenBudget = process.env.OPENVIKING_PROFILE_TOKEN_BUDGET+ if (process.env.OPENVIKING_RESUME_CONTEXT_BUDGET) config.resumeContextBudget = process.env.OPENVIKING_RESUME_CONTEXT_BUDGET+ if (process.env.OPENVIKING_NO_AUTO_INJECT !== undefined) {+ config.noAutoInject = envBool("OPENVIKING_NO_AUTO_INJECT") ?? config.noAutoInject+ }+ if (process.env.OPENVIKING_BYPASS_SESSION !== undefined) {+ config.bypassSession = envBool("OPENVIKING_BYPASS_SESSION") ?? config.bypassSession+ }+ if (process.env.OPENVIKING_BYPASS_SESSION_PATTERNS) {+ config.bypassSessionPatterns = process.env.OPENVIKING_BYPASS_SESSION_PATTERNS+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean)+ }+ if (process.env.OPENVIKING_DEBUG !== undefined) config.debug = envBool("OPENVIKING_DEBUG") ?? config.debug+ if (process.env.OPENVIKING_DEBUG_LOG) config.debugLogPath = process.env.OPENVIKING_DEBUG_LOG+}++function normalizeConfig(config) {+ config.endpoint = str(config.endpoint, DEFAULT_CONFIG.endpoint).replace(/\/+$/, "")+ config.baseUrl = config.endpoint+ config.accountId = config.account+ config.userId = config.user+ config.timeoutMs = normalizeNumber(config.timeoutMs, DEFAULT_CONFIG.timeoutMs, 1000, 300000)+ config.repoContext.cacheTtlMs = normalizeNumber(+ config.repoContext.cacheTtlMs,+ DEFAULT_CONFIG.repoContext.cacheTtlMs,+ 1000,+ 60 * 60 * 1000,+ )+ config.autoRecall.limit = Math.max(1, Math.min(50, Math.round(Number(config.autoRecall.limit) || 6)))+ config.autoRecall.scoreThreshold = Math.max(0, Math.min(1, Number(config.autoRecall.scoreThreshold) || 0))+ config.autoRecall.maxContentChars = Math.max(100, Math.min(5000, Math.round(Number(config.autoRecall.maxContentChars) || 500)))+ config.autoRecall.tokenBudget = Math.max(200, Math.min(50000, Math.round(Number(config.autoRecall.tokenBudget) || 2000)))+ config.autoRecall.minQueryLength = Math.max(1, Math.min(64, Math.round(Number(config.autoRecall.minQueryLength) || 3)))+ config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic"+ config.captureMaxLength = Math.max(200, Math.min(100000, Math.round(Number(config.captureMaxLength) || 24000)))+ config.captureToolMaxChars = Math.max(200, Math.min(20000, Math.round(Number(config.captureToolMaxChars) || 2000)))+ config.commitTokenThreshold = Math.max(1000, Math.round(Number(config.commitTokenThreshold) || 20000))+ config.commitKeepRecentCount = Math.max(0, Math.round(Number(config.commitKeepRecentCount) || 10))+ config.profileTokenBudget = Math.max(500, Math.round(Number(config.profileTokenBudget) || 10000))+ config.resumeContextBudget = Math.max(1024, Math.round(Number(config.resumeContextBudget) || 32000))+ if (!Array.isArray(config.bypassSessionPatterns)) config.bypassSessionPatterns = []++ config.recallLimit = config.autoRecall.limit+ config.scoreThreshold = config.autoRecall.scoreThreshold+ config.recallMaxContentChars = config.autoRecall.maxContentChars+ config.recallPreferAbstract = config.autoRecall.preferAbstract !== false+ config.recallTokenBudget = config.autoRecall.tokenBudget+ config.minQueryLength = config.autoRecall.minQueryLength+ return config+}++export function loadConfig(pluginRoot, projectDirectory) {+ const config = cloneDefaultConfig()+ const { path: configPath, data: fileConfig } = readConfigFile(pluginRoot, projectDirectory)+ applyBehaviorConfig(config, fileConfig)++ const creds = resolveOpenVikingCredentials()+ config.endpoint = creds.baseUrl+ config.apiKey = creds.apiKey+ config.account = creds.account+ config.user = creds.user+ config.peerId = creds.peerId+ config.mcpUrl = creds.mcpUrl+ config.credentialSource = creds.credentialSource+ config.credentialPath = creds.cliPath || creds.ovPath || ""++ const mayUseLegacyCredentials = creds.credentialSource !== "env" &&+ creds.credentialSource !== "ovcli" &&+ !creds.apiKey &&+ !creds.account &&+ !creds.user &&+ !creds.peerId+ const legacyUsed = mayUseLegacyCredentials ? applyLegacyConnection(config, fileConfig) : false+ applyEnv(config)+ config.configPath = configPath+ config.legacyCredentialsUsed = legacyUsed && creds.credentialSource !== "env"+ return normalizeConfig(config)+}++export function resolveDataDir(pluginRoot, config) {+ const configured = config.runtime?.dataDir+ if (configured) return expandHome(configured)+ return path.join(homedir(), ".config", "opencode", "openviking")+}diff --git a/examples/opencode-plugin/lib/mcp-config.mjs b/examples/opencode-plugin/lib/mcp-config.mjsnew file mode 100644index 000000000..a5188b161--- /dev/null+++ b/examples/opencode-plugin/lib/mcp-config.mjs@@ -0,0 +1,21 @@+import { resolve as resolvePath } from "node:path"++export const OPENCODE_MCP_NAME = "openviking"++export function createOpenVikingMcpConfig(pluginRoot) {+ return {+ type: "local",+ command: ["node", resolvePath(pluginRoot, "servers", "mcp-proxy.mjs")],+ enabled: true,+ timeout: 15000,+ }+}++export function injectOpenVikingMcpConfig(config, pluginRoot) {+ if (!config || typeof config !== "object") return false+ config.mcp = config.mcp && typeof config.mcp === "object" ? config.mcp : {}+ const current = config.mcp[OPENCODE_MCP_NAME]+ if (current?.enabled === false) return false+ config.mcp[OPENCODE_MCP_NAME] = createOpenVikingMcpConfig(pluginRoot)+ return true+}diff --git a/examples/opencode-plugin/lib/memadd-local.mjs b/examples/opencode-plugin/lib/memadd-local.mjsdeleted file mode 100644index ce62d4980..000000000--- a/examples/opencode-plugin/lib/memadd-local.mjs+++ /dev/null@@ -1,118 +0,0 @@-import fs from "fs"-import path from "path"-import { fileURLToPath } from "url"-import {- ensureRemoteUrl,- makeMultipartRequest,- makeRequest,- unwrapResponse,-} from "./utils.mjs"--export const MEMADD_LOCAL_FILE_ONLY_ERROR = "Error: memadd local upload currently supports files only."--const ADD_RESOURCE_KEYS = [- "to",- "parent",- "reason",- "instruction",- "wait",- "timeout",- "watch_interval",-]--export function resolveMemaddSource(inputPath, projectDirectory = process.cwd()) {- if (ensureRemoteUrl(inputPath)) {- return { kind: "remote", path: inputPath }- }-- let filePath- try {- filePath = resolveLocalPath(inputPath, projectDirectory)- } catch (error) {- return { kind: "error", error: `Error: ${error.message}` }- }-- let stat- try {- stat = fs.statSync(filePath)- } catch (error) {- if (error?.code === "ENOENT" || error?.code === "ENOTDIR") {- return { kind: "error", error: `Error: Local file not found: ${filePath}` }- }- return { kind: "error", error: `Error: Unable to access local file: ${filePath}: ${error.message}` }- }-- if (!stat.isFile()) {- return { kind: "error", error: MEMADD_LOCAL_FILE_ONLY_ERROR }- }-- return { kind: "local", path: filePath, filename: path.basename(filePath) }-}--export function resolveLocalPath(inputPath, projectDirectory = process.cwd()) {- if (typeof inputPath !== "string" || inputPath.trim() === "") {- throw new Error("memadd path is required.")- }-- let localPath = inputPath- if (isFileUrl(inputPath)) {- localPath = fileURLToPath(inputPath)- }-- if (path.isAbsolute(localPath)) return path.normalize(localPath)- return path.resolve(projectDirectory || process.cwd(), localPath)-}--export function buildAddResourceBody(args, source, tempFileId) {- const body = source.kind === "remote" ? { path: source.path } : { temp_file_id: tempFileId }- for (const key of ADD_RESOURCE_KEYS) {- if (args[key] !== undefined) body[key] = args[key]- }- return body-}--export async function uploadLocalResource(config, source, abortSignal, actorPeerId) {- const bytes = await fs.promises.readFile(source.path)- const form = new FormData()- form.append("file", new Blob([bytes], { type: "application/octet-stream" }), source.filename)-- const uploadResponse = await makeMultipartRequest(config, {- method: "POST",- endpoint: "/api/v1/resources/temp_upload",- body: form,- abortSignal,- actorPeerId,- })- const tempFileId = unwrapResponse(uploadResponse)?.temp_file_id- if (!tempFileId) {- throw new Error("OpenViking temp upload did not return temp_file_id")- }- return tempFileId-}--export async function addMemaddResource(config, args, projectDirectory, abortSignal, actorPeerId) {- const source = resolveMemaddSource(args.path, projectDirectory)- if (source.kind === "error") return { error: source.error }-- const tempFileId = source.kind === "local"- ? await uploadLocalResource(config, source, abortSignal, actorPeerId)- : undefined- const body = buildAddResourceBody(args, source, tempFileId)- const addResponse = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/resources",- body,- abortSignal,- timeoutMs: args.wait ? Math.max(config.timeoutMs, (args.timeout ?? 300) * 1000) : config.timeoutMs,- actorPeerId,- })- return { addResponse, source }-}--function isFileUrl(value) {- try {- return new URL(value).protocol === "file:"- } catch {- return false- }-}diff --git a/examples/opencode-plugin/lib/memory-recall.mjs b/examples/opencode-plugin/lib/memory-recall.mjsindex b004f3cf4..2a7860efa 100644--- a/examples/opencode-plugin/lib/memory-recall.mjs+++ b/examples/opencode-plugin/lib/memory-recall.mjs@@ -1,59 +1,34 @@-import { effectivePeerId, log, makeRequest, unwrapResponse } from "./utils.mjs"--const AUTO_RECALL_TIMEOUT_MS = 5000-const RECALL_STOPWORDS = new Set([- "what", "when", "where", "which", "who", "whom", "whose", "why", "how",- "did", "does", "is", "are", "was", "were", "the", "and", "for", "with",- "from", "that", "this", "your", "you",-])-const RECALL_TOKEN_RE = /[a-z0-9]{2,}/gi-const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i-const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天|上周|下周|上个月|下个月|去年|明年/i+import { buildRecallBlock } from "./shared/recall-core.mjs"+import { isBypassed } from "./shared/session-model.mjs"+import { effectivePeerId, fetchJSON, log } from "./utils.mjs"export function createMemoryRecall({ config }) {async function injectRelevantMemories(input, output) {if (!config.autoRecall?.enabled) returnconst query = extractCurrentUserText(output.parts ?? [])if (!query) return-- const rawResults = await performRecallSearch(query)- if (rawResults.length === 0) return-- const ranked = pickMemoriesForInjection(- rawResults,- config.autoRecall.limit,+ if (query.length < config.minQueryLength) return+ if (isBypassed(config, {+ sessionId: input.sessionID ?? output.message?.sessionID,+ cwd: input.directory ?? input.cwd,+ })) return++ const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })+ if (!health.ok) return++ const block = await buildRecallBlock(+ (path, init = {}, options = {}) => fetchJSON(config, path, init, { ...options, timeoutMs: 5000 }),+ config,query,- config.autoRecall.scoreThreshold,- )- if (ranked.length === 0) return-- const processed = postProcessMemories(- ranked,- config.autoRecall.maxContentChars,- config.autoRecall.preferAbstract,+ {+ actorPeerId: effectivePeerId(config),+ log: (stage, data) => log("DEBUG", "recall", stage, data),+ },)- const block = formatMemoryBlock(processed, config.autoRecall.tokenBudget)if (!block) returnif (prependSyntheticRecallPart(input, output, block)) {- log("INFO", "recall", `Injected ${processed.length} memories`)- }- }-- async function performRecallSearch(query) {- try {- const body = { query: query.slice(0, 4000), limit: 20 }- const response = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/search/find",- body,- timeoutMs: AUTO_RECALL_TIMEOUT_MS,- actorPeerId: effectivePeerId(config),- })- const result = unwrapResponse(response)- return result?.memories ?? result?.results ?? []- } catch {- return []+ log("INFO", "recall", "Injected OpenViking context")}}@@ -64,139 +39,13 @@ function extractCurrentUserText(parts) {const texts = []for (const part of parts) {if (part.type !== "text" || typeof part.text !== "string") continue- if (part.text.includes("<relevant-memories>")) return null+ if (part.text.includes("<openviking-context")) return nullif (!part.synthetic && !part.ignored) texts.push(part.text)}const joined = texts.join(" ").trim()return joined || null}-function buildRecallQueryProfile(query) {- const text = query.trim()- const allTokens = text.toLowerCase().match(RECALL_TOKEN_RE) ?? []- return {- tokens: allTokens.filter((token) => !RECALL_STOPWORDS.has(token)),- wantsPreference: PREFERENCE_QUERY_RE.test(text),- wantsTemporal: TEMPORAL_QUERY_RE.test(text),- }-}--function recallClampScore(value) {- if (typeof value !== "number" || Number.isNaN(value)) return 0- return Math.max(0, Math.min(1, value))-}--function lexicalOverlapBoost(tokens, text) {- if (tokens.length === 0 || !text) return 0- const haystack = ` ${text.toLowerCase()} `- let matched = 0- for (const token of tokens.slice(0, 8)) {- if (haystack.includes(` ${token} `) || haystack.includes(token)) matched += 1- }- return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2)-}--function isEventMemory(item) {- const category = (item.category ?? "").toLowerCase()- return category === "events" || item.uri?.includes("/events/")-}--function isPreferencesMemory(item) {- return item.category === "preferences" || item.uri?.includes("/preferences/") || item.uri?.endsWith("/preferences")-}--function isLeafLikeMemory(item) {- return item.level === 2 || item.is_leaf === true-}--function rankForInjection(item, query) {- const baseScore = recallClampScore(item.score)- const abstract = (item.abstract ?? item.overview ?? "").trim()- const leafBoost = isLeafLikeMemory(item) ? 0.12 : 0- const eventBoost = query.wantsTemporal && isEventMemory(item) ? 0.1 : 0- const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? 0.08 : 0- const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`)- return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost-}--function normalizeDedupeText(text) {- return text.toLowerCase().replace(/\s+/g, " ").trim()-}--function isEventOrCaseMemory(item) {- const category = (item.category ?? "").toLowerCase()- const uri = (item.uri ?? "").toLowerCase()- return category === "events" || category === "cases" || uri.includes("/events/") || uri.includes("/cases/")-}--function getMemoryDedupeKey(item) {- const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "")- const category = (item.category ?? "").toLowerCase() || "unknown"- if (abstract && !isEventOrCaseMemory(item)) return `abstract:${category}:${abstract}`- return `uri:${item.uri}`-}--function pickMemoriesForInjection(items, limit, queryText, scoreThreshold = 0) {- const query = buildRecallQueryProfile(queryText)- const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query))- const deduped = []- const seen = new Set()-- for (const item of sorted) {- const key = getMemoryDedupeKey(item)- if (seen.has(key)) continue- seen.add(key)- deduped.push(item)- }-- const leaves = deduped.filter((item) => isLeafLikeMemory(item))- if (leaves.length >= limit) return leaves.slice(0, limit)-- const picked = [...leaves]- const used = new Set(leaves.map((item) => item.uri))- for (const item of deduped) {- if (picked.length >= limit) break- if (used.has(item.uri)) continue- if (recallClampScore(item.score) < scoreThreshold) continue- picked.push(item)- }- return picked-}--function postProcessMemories(items, maxContentChars, preferAbstract) {- return items.map((item) => {- const abstract = (item.abstract ?? "").trim()- const content = (item.content ?? "").trim()- let displayContent = ""- if (preferAbstract && abstract) displayContent = abstract- else if (content) displayContent = content- else if (abstract) displayContent = abstract- if (displayContent.length > maxContentChars) displayContent = `${displayContent.slice(0, maxContentChars)}...`- return { ...item, content: displayContent, abstract: abstract || undefined }- })-}--function formatMemoryBlock(items, tokenBudget) {- if (items.length === 0) return ""- const maxBlockChars = tokenBudget * 4- let usedChars = 0- const lines = ["<relevant-memories>"]-- for (const item of items) {- const title = item.title ? `${item.title}\n` : ""- const content = item.content ?? ""- const entry = `<memory uri="${item.uri}">\n${title}${content}\n</memory>`- if (usedChars + entry.length + 1 > maxBlockChars) break- lines.push(entry)- usedChars += entry.length + 1- }-- if (usedChars === 0) return ""- lines.push("</relevant-memories>")- lines.push('Use `memread` with a memory URI and level="overview" or level="read" for more details.')- return lines.join("\n")-}-function prependSyntheticRecallPart(input, output, injection) {const sessionID = input.sessionID ?? output.message?.sessionIDconst messageID = input.messageID ?? output.message?.iddiff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjsindex fd3eba675..3aa5a5394 100644--- a/examples/opencode-plugin/lib/memory-session.mjs+++ b/examples/opencode-plugin/lib/memory-session.mjs@@ -1,111 +1,127 @@import fs from "fs"import path from "path"+import {+ extractPartsFromPayload,+ extractTextFromPayload,+ shouldCaptureText,+} from "./shared/capture-utils.mjs"+import {+ deriveHarnessSessionId,+} from "./shared/session-model.mjs"+import {+ enqueue,+ replayPending,+} from "./shared/pending-queue.mjs"import {log,effectivePeerId,- makeRequest,+ fetchJSON,safeStringify,- unwrapResponse,} from "./utils.mjs"-const MAX_BUFFERED_MESSAGES_PER_SESSION = 100-const BUFFERED_MESSAGE_TTL_MS = 15 * 60 * 1000-const BUFFER_CLEANUP_INTERVAL_MS = 30 * 1000-const COMMIT_WAIT_TIMEOUT_MS = 180000-export function createMemorySessionManager({ config, pluginRoot }) {- const sessionMap = new Map()- const sessionMessageBuffer = new Map()- const commitWatchers = new Map()- let sessionMapPath = path.join(pluginRoot, "openviking-session-map.json")+ const sessions = new Map()+ const statePath = path.join(pluginRoot, "openviking-session-state.json")+ const oldSessionMapPath = path.join(pluginRoot, "openviking-session-map.json")let saveTimer = null- let lastBufferCleanupAt = 0async function init() {- await loadSessionMap()- resumeBackgroundCommits()+ await migrateLegacySessionMap()+ await loadState()+ const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })+ if (health.ok) {+ await replayPending(+ (endpoint, init = {}, options = {}) => fetchJSON(config, endpoint, init, options),+ (stage, data) => log("DEBUG", "pending", stage, data),+ )+ }}- async function loadSessionMap() {+ async function loadState() {try {- if (!fs.existsSync(sessionMapPath)) {- log("INFO", "persistence", "No session map file found, starting fresh")+ if (!fs.existsSync(statePath)) {+ log("INFO", "persistence", "No session state file found, starting fresh")return}- const data = JSON.parse(await fs.promises.readFile(sessionMapPath, "utf8"))- if (data.version !== 1) {+ const data = JSON.parse(await fs.promises.readFile(statePath, "utf8"))+ if (data.version !== 2) {log("ERROR", "persistence", "Unsupported session map version", { version: data.version })return}for (const [opencodeSessionId, persisted] of Object.entries(data.sessions ?? {})) {- sessionMap.set(opencodeSessionId, deserializeSessionMapping(persisted))+ sessions.set(opencodeSessionId, deserializeSessionState(persisted))}- log("INFO", "persistence", "Session map loaded", { count: sessionMap.size })+ log("INFO", "persistence", "Session state loaded", { count: sessions.size })} catch (error) {- log("ERROR", "persistence", "Failed to load session map", { error: error?.message })- if (fs.existsSync(sessionMapPath)) {- await fs.promises.rename(sessionMapPath, `${sessionMapPath}.corrupted.${Date.now()}`)+ log("ERROR", "persistence", "Failed to load session state", { error: error?.message })+ if (fs.existsSync(statePath)) {+ await fs.promises.rename(statePath, `${statePath}.corrupted.${Date.now()}`)}}}- async function saveSessionMap() {+ async function saveState() {try {- const sessions = {}- for (const [opencodeSessionId, mapping] of sessionMap.entries()) {- sessions[opencodeSessionId] = serializeSessionMapping(mapping)+ const persisted = {}+ for (const [opencodeSessionId, state] of sessions.entries()) {+ persisted[opencodeSessionId] = serializeSessionState(state)}- const tempPath = `${sessionMapPath}.tmp`- await fs.promises.writeFile(tempPath, JSON.stringify({ version: 1, sessions, lastSaved: Date.now() }, null, 2), "utf8")- await fs.promises.rename(tempPath, sessionMapPath)- log("DEBUG", "persistence", "Session map saved", { count: sessionMap.size })+ const tempPath = `${statePath}.tmp`+ await fs.promises.writeFile(tempPath, JSON.stringify({ version: 2, sessions: persisted, lastSaved: Date.now() }, null, 2), "utf8")+ await fs.promises.rename(tempPath, statePath)+ log("DEBUG", "persistence", "Session state saved", { count: sessions.size })} catch (error) {- log("ERROR", "persistence", "Failed to save session map", { error: error?.message })+ log("ERROR", "persistence", "Failed to save session state", { error: error?.message })}}- function debouncedSaveSessionMap() {+ function debouncedSaveState() {if (saveTimer) clearTimeout(saveTimer)saveTimer = setTimeout(() => {- saveSessionMap().catch((error) => {+ saveState().catch((error) => {log("ERROR", "persistence", "Debounced save failed", { error: error?.message })})}, 300)}- function serializeSessionMapping(mapping) {+ function serializeSessionState(state) {return {- ovSessionId: mapping.ovSessionId,- createdAt: mapping.createdAt,- capturedMessages: Array.from(mapping.capturedMessages),- messageRoles: Array.from(mapping.messageRoles.entries()),- pendingMessages: Array.from(mapping.pendingMessages.entries()),- lastCommitTime: mapping.lastCommitTime,- commitInFlight: mapping.commitInFlight,- commitTaskId: mapping.commitTaskId,- commitStartedAt: mapping.commitStartedAt,- pendingCleanup: mapping.pendingCleanup,- }- }-- function deserializeSessionMapping(persisted) {+ ovSessionId: state.ovSessionId,+ createdAt: state.createdAt,+ lastActivityAt: state.lastActivityAt,+ lastCommitTime: state.lastCommitTime,+ compactedAt: state.compactedAt,+ messages: Array.from(state.messages.entries()).map(([messageId, message]) => ([+ messageId,+ {+ role: message.role,+ captured: message.captured,+ parts: Array.from(message.parts.entries()),+ },+ ])),+ }+ }++ function deserializeSessionState(persisted) {return {ovSessionId: persisted.ovSessionId,createdAt: persisted.createdAt,- capturedMessages: new Set(persisted.capturedMessages ?? []),- messageRoles: new Map(persisted.messageRoles ?? []),- pendingMessages: new Map(persisted.pendingMessages ?? []),- sendingMessages: new Set(),+ lastActivityAt: persisted.lastActivityAt,lastCommitTime: persisted.lastCommitTime,- commitInFlight: persisted.commitInFlight,- commitTaskId: persisted.commitTaskId,- commitStartedAt: persisted.commitStartedAt,- pendingCleanup: persisted.pendingCleanup,+ compactedAt: persisted.compactedAt,+ messages: new Map((persisted.messages ?? []).map(([messageId, message]) => ([+ messageId,+ {+ role: message.role,+ captured: Boolean(message.captured),+ parts: new Map(message.parts ?? []),+ },+ ]))),}}function getMappedSessionId(opencodeSessionId) {- return sessionMap.get(opencodeSessionId)?.ovSessionId+ return getOrCreateSession(opencodeSessionId).ovSessionId}async function handleEvent(event) {@@ -119,6 +135,8 @@ export function createMemorySessionManager({ config, pluginRoot }) {await handleSessionError(event)} else if (event.type === "session.compacted") {await handleSessionCompacted(event)+ } else if (event.type === "session.idle") {+ await handleSessionIdle(event)} else if (event.type === "message.updated") {await handleMessageUpdated(event)} else if (event.type === "message.part.updated") {@@ -132,56 +150,27 @@ export function createMemorySessionManager({ config, pluginRoot }) {log("ERROR", "event", "session.created event missing sessionId", { event: safeStringify(event) })return}-- const ovSessionId = await ensureOpenVikingSession(sessionId)- if (!ovSessionId) return-- const existing = sessionMap.get(sessionId)- const mapping = existing ?? createSessionMapping(ovSessionId)- mapping.ovSessionId = ovSessionId- sessionMap.set(sessionId, mapping)-- const bufferedMessages = sessionMessageBuffer.get(sessionId)- if (bufferedMessages?.length) {- for (const buffered of bufferedMessages) {- if (buffered.role) mapping.messageRoles.set(buffered.messageId, buffered.role)- if (buffered.content) {- mapping.pendingMessages.set(- buffered.messageId,- mergeMessageContent(mapping.pendingMessages.get(buffered.messageId), buffered.content),- )- }- }- sessionMessageBuffer.delete(sessionId)- await flushPendingMessages(sessionId, mapping)+ const state = getOrCreateSession(sessionId, event)+ debouncedSaveState()+ const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })+ if (health.ok) {+ await replayPending(+ (endpoint, init = {}, options = {}) => fetchJSON(config, endpoint, init, options),+ (stage, data) => log("DEBUG", "pending", stage, data),+ )}-- debouncedSaveSessionMap()- log("INFO", "event", "Session mapping established", {+ log("INFO", "event", "OpenViking session derived", {opencode_session: sessionId,- openviking_session: ovSessionId,+ openviking_session: state.ovSessionId,})}async function handleSessionDeleted(event) {const sessionId = resolveEventSessionId(event)if (!sessionId) return-- const mapping = sessionMap.get(sessionId)- if (!mapping) {- sessionMessageBuffer.delete(sessionId)- return- }-- await flushPendingMessages(sessionId, mapping)- if (mapping.capturedMessages.size > 0 || mapping.commitInFlight) {- mapping.pendingCleanup = true- if (!mapping.commitInFlight) await startBackgroundCommit(mapping, sessionId)- } else {- sessionMap.delete(sessionId)- sessionMessageBuffer.delete(sessionId)- await saveSessionMap()- }+ await flushSession(sessionId, { commit: true, reason: event.type })+ sessions.delete(sessionId)+ await saveState()}async function handleSessionError(event) {@@ -195,26 +184,18 @@ export function createMemorySessionManager({ config, pluginRoot }) {await commitSessionBoundary(event, "session.compacted")}- async function commitSessionBoundary(event, reason) {+ async function handleSessionIdle(event) {const sessionId = resolveEventSessionId(event)if (!sessionId) return+ await flushSession(sessionId, { commit: false, reason: "session.idle" })+ }- const mapping = sessionMap.get(sessionId)- if (!mapping) return-- await flushPendingMessages(sessionId, mapping)- if (mapping.commitInFlight) {- monitorBackgroundCommit(mapping, sessionId)- return- }- if (mapping.capturedMessages.size > 0) {- log("INFO", "session", "Committing OpenViking session at lifecycle boundary", {- opencode_session: sessionId,- openviking_session: mapping.ovSessionId,- reason,- })- await startBackgroundCommit(mapping, sessionId)- }+ async function commitSessionBoundary(event, reason) {+ const sessionId = resolveEventSessionId(event)+ if (!sessionId) return+ const state = getOrCreateSession(sessionId, event)+ state.compactedAt = Date.now()+ await flushSession(sessionId, { commit: true, reason })}async function handleMessageUpdated(event) {@@ -227,19 +208,17 @@ export function createMemorySessionManager({ config, pluginRoot }) {const finish = message.finishif (!sessionId || !messageId) return- const mapping = sessionMap.get(sessionId)- if (!mapping) {- upsertBufferedMessage(sessionId, messageId, role ? { role } : {})- return- }-+ const state = getOrCreateSession(sessionId, event)+ const captured = state.messages.get(messageId)+ const next = captured ?? createMessageState()if (role === "user") {- mapping.messageRoles.set(messageId, role)- } else if (role === "assistant" && finish === "stop") {- mapping.messageRoles.set(messageId, role)+ next.role = role+ } else if (role === "assistant") {+ next.role = role}-- await flushPendingMessages(sessionId, mapping)+ state.messages.set(messageId, next)+ state.lastActivityAt = Date.now()+ debouncedSaveState()}async function handleMessagePartUpdated(event) {@@ -248,256 +227,16 @@ export function createMemorySessionManager({ config, pluginRoot }) {const sessionId = part.sessionIDconst messageId = part.messageID- if (!sessionId || !messageId || part.type !== "text" || !part.text?.trim()) return-- const mapping = sessionMap.get(sessionId)- if (!mapping) {- upsertBufferedMessage(sessionId, messageId, { content: part.text })- return- }-- if (mapping.capturedMessages.has(messageId)) return- mapping.pendingMessages.set(messageId, mergeMessageContent(mapping.pendingMessages.get(messageId), part.text))- }-- async function ensureOpenVikingSession(opencodeSessionId) {- const knownSessionId = sessionMap.get(opencodeSessionId)?.ovSessionId- if (knownSessionId) {- try {- const response = await makeRequest(config, {- method: "GET",- endpoint: `/api/v1/sessions/${encodeURIComponent(knownSessionId)}`,- timeoutMs: 5000,- })- if (unwrapResponse(response)) return knownSessionId- } catch (error) {- log("INFO", "session", "Persisted OpenViking session unavailable, creating a new one", {- opencode_session: opencodeSessionId,- openviking_session: knownSessionId,- error: error?.message,- })- }- }-- try {- const response = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/sessions",- body: {},- timeoutMs: 5000,- })- const sessionId = unwrapResponse(response)?.session_id- if (!sessionId) throw new Error("OpenViking did not return a session_id")- return sessionId- } catch (error) {- log("ERROR", "session", "Failed to create OpenViking session", {- opencode_session: opencodeSessionId,- error: error?.message,- })- return null- }- }-- async function flushPendingMessages(opencodeSessionId, mapping) {- if (mapping.commitInFlight) return-- for (const messageId of Array.from(mapping.pendingMessages.keys())) {- if (mapping.capturedMessages.has(messageId) || mapping.sendingMessages.has(messageId)) continue- const role = mapping.messageRoles.get(messageId)- const content = mapping.pendingMessages.get(messageId)- if (!role || !content?.trim()) continue-- mapping.sendingMessages.add(messageId)- try {- const success = await addMessageToSession(mapping.ovSessionId, role, content)- if (success) {- const latest = mapping.pendingMessages.get(messageId)- if (latest && latest !== content) {- continue- }- mapping.pendingMessages.delete(messageId)- mapping.capturedMessages.add(messageId)- debouncedSaveSessionMap()- }- } finally {- mapping.sendingMessages.delete(messageId)- }- }- }-- async function addMessageToSession(ovSessionId, role, content) {- try {- const body = { role, content }- const peerId = effectivePeerId(config)- if (peerId) body.peer_id = peerId- const response = await makeRequest(config, {- method: "POST",- endpoint: `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`,- body,- timeoutMs: 5000,- })- unwrapResponse(response)- return true- } catch (error) {- log("ERROR", "message", "Failed to add message to OpenViking session", {- openviking_session: ovSessionId,- role,- error: error?.message,- })- return false- }- }-- async function startBackgroundCommit(mapping, opencodeSessionId, abortSignal) {- if (mapping.commitInFlight && mapping.commitTaskId) {- if (!abortSignal) monitorBackgroundCommit(mapping, opencodeSessionId)- return { mode: "background", taskId: mapping.commitTaskId }- }-- try {- const response = await makeRequest(config, {- method: "POST",- endpoint: `/api/v1/sessions/${encodeURIComponent(mapping.ovSessionId)}/commit`,- timeoutMs: 10000,- abortSignal,- })- const result = unwrapResponse(response)- const taskId = result?.task_id-- if (!taskId) {- await finalizeCommitSuccess(mapping, opencodeSessionId)- return { mode: "completed", result }- }-- mapping.commitInFlight = true- mapping.commitTaskId = taskId- mapping.commitStartedAt = Date.now()- debouncedSaveSessionMap()- if (!abortSignal) monitorBackgroundCommit(mapping, opencodeSessionId)- return { mode: "background", taskId }- } catch (error) {- if (error?.message?.includes("already has a commit in progress")) {- const taskId = await findRunningCommitTaskId(mapping.ovSessionId)- if (taskId) {- mapping.commitInFlight = true- mapping.commitTaskId = taskId- mapping.commitStartedAt = mapping.commitStartedAt ?? Date.now()- debouncedSaveSessionMap()- if (!abortSignal) monitorBackgroundCommit(mapping, opencodeSessionId)- return { mode: "background", taskId }- }- }- log("ERROR", "session", "Failed to start OpenViking commit", {- openviking_session: mapping.ovSessionId,- opencode_session: opencodeSessionId,- error: error?.message,- })- return null- }- }-- async function waitForCommitCompletion(mapping, opencodeSessionId, abortSignal, timeoutMs = COMMIT_WAIT_TIMEOUT_MS) {- const startedAt = Date.now()- while (Date.now() - startedAt < timeoutMs) {- if (abortSignal?.aborted) throw new Error("Operation aborted")- if (!mapping.commitInFlight) return null- if (!mapping.commitTaskId) {- mapping.commitTaskId = await findRunningCommitTaskId(mapping.ovSessionId)- if (!mapping.commitTaskId) {- clearCommitState(mapping)- debouncedSaveSessionMap()- return null- }- }-- const task = await getTask(mapping.commitTaskId, abortSignal)- if (task.status === "completed") {- await finalizeCommitSuccess(mapping, opencodeSessionId)- return task- }- if (task.status === "failed") {- clearCommitState(mapping)- debouncedSaveSessionMap()- throw new Error(task.error || "Background commit failed")- }- await sleep(2000, abortSignal)- }- return null- }-- async function getTask(taskId, abortSignal) {- const response = await makeRequest(config, {- method: "GET",- endpoint: `/api/v1/tasks/${encodeURIComponent(taskId)}`,- timeoutMs: 5000,- abortSignal,- })- return unwrapResponse(response)- }-- async function findRunningCommitTaskId(ovSessionId) {- try {- const response = await makeRequest(config, {- method: "GET",- endpoint: `/api/v1/tasks?task_type=session_commit&resource_id=${encodeURIComponent(ovSessionId)}&limit=10`,- timeoutMs: 5000,- })- const tasks = unwrapResponse(response) ?? []- return tasks.find((task) => task.status === "pending" || task.status === "running")?.task_id- } catch (error) {- log("WARN", "session", "Failed to query running commit tasks", { error: error?.message })- return undefined- }- }-- async function finalizeCommitSuccess(mapping, opencodeSessionId) {- mapping.lastCommitTime = Date.now()- mapping.capturedMessages.clear()- clearCommitState(mapping)- debouncedSaveSessionMap()-- await flushPendingMessages(opencodeSessionId, mapping)-- if (mapping.pendingCleanup) {- sessionMap.delete(opencodeSessionId)- sessionMessageBuffer.delete(opencodeSessionId)- await saveSessionMap()- }- }-- function resumeBackgroundCommits() {- for (const [opencodeSessionId, mapping] of sessionMap.entries()) {- if (mapping.commitInFlight) monitorBackgroundCommit(mapping, opencodeSessionId)- }- }-- function monitorBackgroundCommit(mapping, opencodeSessionId) {- if (!mapping.commitTaskId) return- if (commitWatchers.has(mapping.commitTaskId)) return+ if (!sessionId || !messageId) return- const taskId = mapping.commitTaskId- const watcher = waitForCommitCompletion(mapping, opencodeSessionId)- .then((task) => {- if (!task) {- log("WARN", "session", "Background commit is still pending after the wait timeout", {- task_id: taskId,- openviking_session: mapping.ovSessionId,- opencode_session: opencodeSessionId,- })- }- })- .catch((error) => {- log("ERROR", "session", "Background commit watcher failed", {- task_id: taskId,- openviking_session: mapping.ovSessionId,- opencode_session: opencodeSessionId,- error: error?.message,- })- })- .finally(() => {- commitWatchers.delete(taskId)- })- commitWatchers.set(taskId, watcher)+ const state = getOrCreateSession(sessionId, event)+ const message = state.messages.get(messageId) ?? createMessageState()+ if (message.captured) return+ const partId = part.id ?? `${messageId}:${message.parts.size}`+ message.parts.set(partId, part)+ state.messages.set(messageId, message)+ state.lastActivityAt = Date.now()+ debouncedSaveState()}async function flushAll({ commit = false } = {}) {@@ -505,60 +244,33 @@ export function createMemorySessionManager({ config, pluginRoot }) {clearTimeout(saveTimer)saveTimer = null}- for (const [sessionId, mapping] of sessionMap.entries()) {- await flushPendingMessages(sessionId, mapping)- if (commit) {- if (mapping.commitInFlight) {- monitorBackgroundCommit(mapping, sessionId)- } else if (mapping.capturedMessages.size > 0) {- await startBackgroundCommit(mapping, sessionId)- }- }+ for (const sessionId of sessions.keys()) {+ await flushSession(sessionId, { commit, reason: "flushAll" })}- await saveSessionMap()+ await saveState()}async function flushSession(opencodeSessionId, { commit = false, reason = "manual" } = {}) {- const mapping = sessionMap.get(opencodeSessionId)- if (!mapping) return false+ if (!opencodeSessionId) return false+ const state = sessions.get(opencodeSessionId)+ if (!state) return false- await flushPendingMessages(opencodeSessionId, mapping)+ const added = await flushPendingMessages(opencodeSessionId, state)if (commit) {- if (mapping.commitInFlight) {- monitorBackgroundCommit(mapping, opencodeSessionId)- } else if (mapping.capturedMessages.size > 0) {- log("INFO", "session", "Committing OpenViking session at lifecycle boundary", {- opencode_session: opencodeSessionId,- openviking_session: mapping.ovSessionId,- reason,- })- await startBackgroundCommit(mapping, opencodeSessionId)- }+ await commitOvSession(state.ovSessionId, { force: true, reason })+ } else if (added > 0) {+ await maybeCommitByThreshold(state)}- await saveSessionMap()+ await saveState()return true}async function commitSession(sessionId, opencodeSessionId, abortSignal) {- let mapping = opencodeSessionId ? sessionMap.get(opencodeSessionId) : undefined- if (!mapping || mapping.ovSessionId !== sessionId) {- mapping = createSessionMapping(sessionId)- } else {- await flushPendingMessages(opencodeSessionId, mapping)- }-- if (mapping.commitInFlight) {- const task = await waitForCommitCompletion(mapping, opencodeSessionId ?? sessionId, abortSignal)- if (task?.status === "completed") return { status: "completed", task }+ if (opencodeSessionId) {+ const state = sessions.get(opencodeSessionId)+ if (state) await flushPendingMessages(opencodeSessionId, state)}-- const start = await startBackgroundCommit(mapping, opencodeSessionId ?? sessionId, abortSignal)- if (!start) throw new Error("Failed to start OpenViking session commit")- if (start.mode === "completed") return { status: "completed", result: start.result }-- const task = await waitForCommitCompletion(mapping, opencodeSessionId ?? sessionId, abortSignal)- if (!task) return { status: "accepted", task_id: start.taskId }- return { status: task.status, task }+ return commitOvSession(sessionId, { force: true, abortSignal, reason: "tool" })}return {@@ -570,82 +282,193 @@ export function createMemorySessionManager({ config, pluginRoot }) {flushSession,}- function createSessionMapping(ovSessionId) {+ function createSessionState(opencodeSessionId, event = {}) {+ const parentId = event?.properties?.info?.parentID ?? event?.properties?.parentID ?? event?.parentID ?? ""+ const ovSessionId = parentId+ ? deriveHarnessSessionId("oc-", parentId, `subagent-${opencodeSessionId}`)+ : deriveHarnessSessionId("oc-", opencodeSessionId)return {ovSessionId,createdAt: Date.now(),- capturedMessages: new Set(),- messageRoles: new Map(),- pendingMessages: new Map(),- sendingMessages: new Set(),+ lastActivityAt: Date.now(),lastCommitTime: undefined,- commitInFlight: false,+ compactedAt: undefined,+ messages: new Map(),}}- function resolveEventSessionId(event) {- return event?.properties?.info?.id ?? event?.properties?.sessionID ?? event?.properties?.sessionId- }-- function mergeMessageContent(existing, incoming) {- const next = incoming?.trim()- if (!next) return existing ?? ""- if (!existing) return next- if (next === existing) return existing- if (next.startsWith(existing)) return next- if (existing.startsWith(next)) return existing- if (next.includes(existing)) return next- if (existing.includes(next)) return existing- return `${existing}\n${next}`.trim()- }-- function upsertBufferedMessage(sessionId, messageId, updates) {- const now = Date.now()- if (now - lastBufferCleanupAt >= BUFFER_CLEANUP_INTERVAL_MS) {- cleanupOrphanedMessageBuffers(now)- lastBufferCleanupAt = now+ function createMessageState() {+ return {+ role: "",+ parts: new Map(),+ captured: false,}+ }- const freshBuffer = (sessionMessageBuffer.get(sessionId) ?? [])- .filter((message) => now - message.timestamp <= BUFFERED_MESSAGE_TTL_MS)- let buffered = freshBuffer.find((message) => message.messageId === messageId)- if (!buffered) {- while (freshBuffer.length >= MAX_BUFFERED_MESSAGES_PER_SESSION) freshBuffer.shift()- buffered = { messageId, timestamp: now }- freshBuffer.push(buffered)- } else {- buffered.timestamp = now+ function getOrCreateSession(opencodeSessionId, event = {}) {+ let state = sessions.get(opencodeSessionId)+ if (!state) {+ state = createSessionState(opencodeSessionId, event)+ sessions.set(opencodeSessionId, state)}- if (updates.role) buffered.role = updates.role- if (updates.content) buffered.content = mergeMessageContent(buffered.content, updates.content)- sessionMessageBuffer.set(sessionId, freshBuffer)+ return state}- function cleanupOrphanedMessageBuffers(now) {- for (const [sessionId, buffer] of sessionMessageBuffer.entries()) {- if (sessionMap.has(sessionId)) continue- const oldest = buffer[0]- if (!oldest || now - oldest.timestamp > BUFFERED_MESSAGE_TTL_MS * 2) {- sessionMessageBuffer.delete(sessionId)+ function resolveEventSessionId(event) {+ return event?.properties?.info?.id ??+ event?.properties?.info?.sessionID ??+ event?.properties?.info?.sessionId ??+ event?.properties?.sessionID ??+ event?.properties?.sessionId ??+ event?.sessionID ??+ event?.sessionId ??+ event?.id+ }++ function resolvePartRole(part, fallbackRole) {+ if (fallbackRole) return fallbackRole+ const type = String(part?.type || part?.kind || "").toLowerCase()+ if (type.includes("tool") && type.includes("call")) return "assistant"+ if (type.includes("tool")) return "user"+ return ""+ }++ function buildCapturePayload(message) {+ const partsRaw = Array.from(message.parts.values())+ if (partsRaw.length === 0) return null+ const role = resolvePartRole(partsRaw[0], message.role)+ if (!role) return null+ if (role === "assistant" && !config.captureAssistantTurns) return null++ const rawText = partsRaw+ .map((part) => extractTextFromPayload(part, { toolMaxChars: config.captureToolMaxChars }))+ .filter(Boolean)+ .join("\n\n")+ const captureParts = partsRaw.flatMap((part) => extractPartsFromPayload(part, {+ toolMaxChars: config.captureToolMaxChars,+ }))+ const decision = shouldCaptureText(rawText, role, config)+ if (!decision.shouldCapture && captureParts.length === 0) return null+ const body = captureParts.length > 0+ ? { role, parts: captureParts }+ : { role, content: decision.text }+ const peerId = effectivePeerId(config)+ if (peerId) body.peer_id = peerId+ return body+ }++ async function flushPendingMessages(opencodeSessionId, state) {+ let added = 0+ for (const [messageId, message] of state.messages.entries()) {+ if (message.captured) continue+ const body = buildCapturePayload(message)+ if (!body) {+ message.captured = true+ continue}+ const ok = await addMessageToSession(state.ovSessionId, body)+ if (!ok) break+ message.captured = true+ added += 1+ }+ if (added > 0) {+ state.lastActivityAt = Date.now()+ debouncedSaveState()+ }+ return added+ }++ async function addMessageToSession(ovSessionId, body) {+ const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })+ if (!health.ok) {+ await enqueue("addMessage", ovSessionId, body)+ return true+ }+ const res = await fetchJSON(config, `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {+ method: "POST",+ body: JSON.stringify(body),+ }, { timeoutMs: 10000 })+ if (res.ok) return true+ if (isRetryableFailure(res)) {+ const queued = await enqueue("addMessage", ovSessionId, body)+ return Boolean(queued.ok)}+ log("ERROR", "message", "Failed to add message to OpenViking session", {+ openviking_session: ovSessionId,+ role: body.role,+ status: res.status,+ error: res.error,+ })+ return false}- function clearCommitState(mapping) {- mapping.commitInFlight = false- mapping.commitTaskId = undefined- mapping.commitStartedAt = undefined+ async function maybeCommitByThreshold(state) {+ if (config.commitTokenThreshold <= 0) return { committed: false }+ const meta = await fetchJSON(config, `/api/v1/sessions/${encodeURIComponent(state.ovSessionId)}`, {}, {+ timeoutMs: 5000,+ })+ const pendingTokens = Number(meta.result?.pending_tokens || 0)+ log("DEBUG", "session", "Pending token check", {+ openviking_session: state.ovSessionId,+ pendingTokens,+ threshold: config.commitTokenThreshold,+ })+ if (!meta.ok || pendingTokens < config.commitTokenThreshold) return { committed: false, pendingTokens }+ return commitOvSession(state.ovSessionId, { force: true, reason: "threshold" })+ }++ async function commitOvSession(ovSessionId, { force = false, reason = "manual", abortSignal } = {}) {+ if (!force && config.commitTokenThreshold <= 0) return { status: "skipped" }+ const body = { keep_recent_count: config.commitKeepRecentCount }+ const res = await fetchJSON(config, `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, {+ method: "POST",+ body: JSON.stringify(body),+ signal: abortSignal,+ }, { timeoutMs: 30000 })+ if (res.ok) {+ for (const state of sessions.values()) {+ if (state.ovSessionId === ovSessionId) state.lastCommitTime = Date.now()+ }+ log("INFO", "session", "Committed OpenViking session", { openviking_session: ovSessionId, reason })+ return { status: "accepted", result: res.result }+ }+ if (isRetryableFailure(res)) {+ await enqueue("commitSession", ovSessionId, body)+ log("WARN", "session", "Queued OpenViking session commit", { openviking_session: ovSessionId, reason })+ return { status: "queued" }+ }+ throw new Error(`Failed to commit OpenViking session ${ovSessionId}: ${res.error?.message || res.status}`)}- async function sleep(ms, abortSignal) {- await new Promise((resolve, reject) => {- const timer = setTimeout(resolve, ms)- if (!abortSignal) return- const onAbort = () => {- clearTimeout(timer)- reject(new Error("Operation aborted"))+ async function migrateLegacySessionMap() {+ if (!fs.existsSync(oldSessionMapPath)) return+ if (fs.existsSync(`${oldSessionMapPath}.migrated`)) return+ try {+ const data = JSON.parse(await fs.promises.readFile(oldSessionMapPath, "utf8"))+ const ovSessionIds = new Set()+ for (const persisted of Object.values(data.sessions ?? {})) {+ if (persisted?.ovSessionId) ovSessionIds.add(persisted.ovSessionId)}- abortSignal.addEventListener("abort", onAbort, { once: true })- })+ for (const ovSessionId of ovSessionIds) {+ try {+ await commitOvSession(ovSessionId, { force: true, reason: "legacy-migration" })+ } catch (error) {+ log("WARN", "migration", "Legacy orphan session commit failed", {+ openviking_session: ovSessionId,+ error: error?.message,+ })+ }+ }+ await fs.promises.rename(oldSessionMapPath, `${oldSessionMapPath}.migrated`)+ log("INFO", "migration", "Migrated legacy session map", { count: ovSessionIds.size })+ } catch (error) {+ log("ERROR", "migration", "Failed to migrate legacy session map", { error: error?.message })+ }+ }++ function isRetryableFailure(res) {+ if (!res || res.ok) return false+ const status = Number(res.status || 0)+ return !status || status >= 500 || status === 408 || status === 429}}diff --git a/examples/opencode-plugin/lib/memory-tools.mjs b/examples/opencode-plugin/lib/memory-tools.mjsdeleted file mode 100644index a758e3753..000000000--- a/examples/opencode-plugin/lib/memory-tools.mjs+++ /dev/null@@ -1,410 +0,0 @@-import { tool } from "@opencode-ai/plugin"-import { addMemaddResource } from "./memadd-local.mjs"-import {- log,- effectivePeerId,- makeRequest,- unwrapResponse,- validateVikingUri,-} from "./utils.mjs"--const z = tool.schema--export function createMemoryTools({ config, sessionManager, projectDirectory }) {- const actorPeerId = effectivePeerId(config)- return {- memsearch: tool({- description:- "Search OpenViking memories, indexed repositories, and skills. Use this for semantic or conceptual questions. Narrow `target_uri` whenever possible, for example viking://resources/project/ or viking://user/memories/.",- args: {- query: z.string().describe("Natural language query, question, or task description."),- target_uri: z.string().optional().describe("Optional Viking URI scope, e.g. viking://resources/ or viking://user/memories/."),- mode: z.enum(["auto", "fast", "deep"]).optional().describe("auto chooses based on query complexity; fast uses /find; deep uses /search with session context when available."),- session_id: z.string().optional().describe("Optional explicit OpenViking session ID for context-aware search."),- limit: z.number().optional().describe("Maximum number of results. Defaults to 10."),- score_threshold: z.number().optional().describe("Optional minimum score threshold."),- },- async execute(args, context) {- try {- let sessionId = args.session_id- if (!sessionId && context.sessionID) {- sessionId = sessionManager.getMappedSessionId(context.sessionID)- }-- const mode = resolveSearchMode(args.mode, args.query, sessionId)- const body = {- query: args.query,- limit: args.limit ?? 10,- }- if (args.target_uri) body.target_uri = args.target_uri- if (args.score_threshold !== undefined) body.score_threshold = args.score_threshold- if (mode === "deep" && sessionId) body.session_id = sessionId- const response = await makeRequest(config, {- method: "POST",- endpoint: mode === "deep" ? "/api/v1/search/search" : "/api/v1/search/find",- body,- abortSignal: context.abort,- actorPeerId,- })- return formatSearchResults(unwrapResponse(response), args.query, { mode })- } catch (error) {- log("ERROR", "memsearch", "Search failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- memread: tool({- description:- "Read a specific viking:// URI. Use after memsearch, membrowse, memgrep, or memglob returns a URI. `auto` chooses overview for directories and read for files.",- args: {- uri: z.string().describe("Complete Viking URI to read."),- level: z.enum(["auto", "abstract", "overview", "read"]).optional().describe("Read level. Defaults to auto."),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "memread")- if (validationError) return validationError-- try {- let level = args.level ?? "auto"- if (level === "auto") {- level = await resolveReadLevel(config, args.uri, context.abort, actorPeerId)- }- const response = await makeRequest(config, {- method: "GET",- endpoint: `/api/v1/content/${level}?uri=${encodeURIComponent(args.uri)}`,- abortSignal: context.abort,- actorPeerId,- })- const content = unwrapResponse(response)- return typeof content === "string" ? content : JSON.stringify(content, null, 2)- } catch (error) {- log("ERROR", "memread", "Read failed", { error: error?.message, uri: args.uri })- return `Error: ${error.message}`- }- },- }),-- membrowse: tool({- description:- "Browse OpenViking filesystem structure. Use list/tree/stat to discover exact URIs before reading. Scope to the narrowest useful viking:// path.",- args: {- uri: z.string().describe("Viking URI to inspect, e.g. viking://resources/ or viking://user/memories/."),- view: z.enum(["list", "tree", "stat"]).optional().describe("Browse view. Defaults to list."),- recursive: z.boolean().optional().describe("For list view only, recursively list descendants."),- simple: z.boolean().optional().describe("For list view only, return simpler URI-oriented output."),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "membrowse")- if (validationError) return validationError-- try {- const view = args.view ?? "list"- const encodedUri = encodeURIComponent(args.uri)- let endpoint- if (view === "stat") {- endpoint = `/api/v1/fs/stat?uri=${encodedUri}`- } else if (view === "tree") {- endpoint = `/api/v1/fs/tree?uri=${encodedUri}`- } else {- endpoint = `/api/v1/fs/ls?uri=${encodedUri}&recursive=${args.recursive ? "true" : "false"}&simple=${args.simple ? "true" : "false"}`- }- const response = await makeRequest(config, {- method: "GET",- endpoint,- abortSignal: context.abort,- actorPeerId,- })- return JSON.stringify({ view, result: unwrapResponse(response) }, null, 2)- } catch (error) {- log("ERROR", "membrowse", "Browse failed", { error: error?.message, uri: args.uri })- return `Error: ${error.message}`- }- },- }),-- memcommit: tool({- description:- "Commit the current OpenCode session to OpenViking and extract persistent memories. Use for immediate memory extraction before ending a conversation or after important preferences/decisions are discussed.",- args: {- session_id: z.string().optional().describe("Optional explicit OpenViking session ID. Omit to use the current OpenCode session mapping."),- },- async execute(args, context) {- let sessionId = args.session_id- if (!sessionId && context.sessionID) {- sessionId = sessionManager.getMappedSessionId(context.sessionID)- }- if (!sessionId) {- return "Error: No OpenViking session is associated with the current OpenCode session. Start or resume a normal OpenCode session first, or pass session_id."- }-- try {- const result = await sessionManager.commitSession(sessionId, context.sessionID, context.abort)- return formatCommitResult(sessionId, result)- } catch (error) {- log("ERROR", "memcommit", "Commit failed", { error: error?.message, session_id: sessionId })- return `Error: ${error.message}`- }- },- }),-- memgrep: tool({- description:- "Search exact text or regex-like patterns in OpenViking content. Use this for symbols, function names, classes, error strings, or known keywords. Narrow `uri` to the smallest relevant repository or directory.",- args: {- pattern: z.string().describe("Pattern or exact keyword to search for."),- uri: z.string().optional().describe("Starting Viking URI. Defaults to viking://resources/."),- case_insensitive: z.boolean().optional().describe("Whether search should ignore case."),- exclude_uri: z.string().optional().describe("Optional URI prefix to exclude from matches."),- level_limit: z.number().optional().describe("Optional maximum traversal depth."),- },- async execute(args, context) {- const uri = args.uri ?? "viking://resources/"- const validationError = validateVikingUri(uri, "memgrep")- if (validationError) return validationError-- try {- const body = { uri, pattern: args.pattern }- if (args.case_insensitive !== undefined) body.case_insensitive = args.case_insensitive- if (args.exclude_uri) body.exclude_uri = args.exclude_uri- if (args.level_limit !== undefined) body.level_limit = args.level_limit- const response = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/search/grep",- body,- abortSignal: context.abort,- actorPeerId,- })- return JSON.stringify(unwrapResponse(response), null, 2)- } catch (error) {- log("ERROR", "memgrep", "Grep failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- memglob: tool({- description:- "List files by glob pattern in OpenViking. Use this to enumerate candidate files before memread. Narrow `uri` to the smallest relevant repository or directory.",- args: {- pattern: z.string().describe("Glob pattern, e.g. **/*.py or **/test_*.ts."),- uri: z.string().optional().describe("Starting Viking URI. Defaults to viking://resources/."),- node_limit: z.number().optional().describe("Optional maximum number of matches."),- },- async execute(args, context) {- const uri = args.uri ?? "viking://resources/"- const validationError = validateVikingUri(uri, "memglob")- if (validationError) return validationError-- try {- const body = { uri, pattern: args.pattern }- if (args.node_limit !== undefined) body.node_limit = args.node_limit- const response = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/search/glob",- body,- abortSignal: context.abort,- actorPeerId,- })- return JSON.stringify(unwrapResponse(response), null, 2)- } catch (error) {- log("ERROR", "memglob", "Glob failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- memadd: tool({- description:- "Add a remote URL or local file resource to OpenViking under viking://resources/. Local files are uploaded through OpenViking temp upload before indexing. After adding, this returns observer queue status so indexing progress is visible.",- args: {- path: z.string().describe("Remote http(s) URL, local file path, or file:// URL to add. Relative local paths are resolved from the OpenCode project directory."),- to: z.string().optional().describe("Exact target URI under viking://resources/. Cannot be used with parent."),- parent: z.string().optional().describe("Parent URI under viking://resources/. Cannot be used with to."),- reason: z.string().optional().describe("Reason for adding this resource."),- instruction: z.string().optional().describe("Optional processing instruction."),- wait: z.boolean().optional().describe("Whether OpenViking should wait for semantic processing."),- timeout: z.number().optional().describe("Timeout seconds when wait=true."),- watch_interval: z.number().optional().describe("Minutes between scheduled refreshes. Requires to."),- },- async execute(args, context) {- if (args.to && args.parent) return "Error: Use either `to` or `parent`, not both."- if (args.to && !args.to.startsWith("viking://resources")) return "Error: `to` must be under viking://resources/."- if (args.parent && !args.parent.startsWith("viking://resources")) return "Error: `parent` must be under viking://resources/."-- try {- const result = await addMemaddResource(config, args, projectDirectory, context.abort, actorPeerId)- if (result.error) return result.error- const queue = await getQueueStatus(config, context.abort)- return JSON.stringify({ add_resource: unwrapResponse(result.addResponse), queue }, null, 2)- } catch (error) {- log("ERROR", "memadd", "Add resource failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- memwrite: tool({- description:- "Write text content to a viking:// file through OpenViking content/write. Use create for new durable notes or resources, append to extend an existing file, and replace only when the user explicitly wants to overwrite existing content.",- args: {- uri: z.string().describe("Complete viking:// file URI to write, e.g. viking://user/memories/project-notes.md or viking://resources/docs/api.md."),- content: z.string().describe("Text content to write."),- mode: z.enum(["create", "append", "replace"]).optional().describe("Write mode. Defaults to create to avoid accidental overwrite."),- wait: z.boolean().optional().describe("Whether OpenViking should wait for semantic/vector refresh."),- timeout: z.number().optional().describe("Timeout seconds when wait=true."),- },- async execute(args, context) {- const validationError = validateVikingUri(args.uri, "memwrite")- if (validationError) return validationError-- try {- const body = {- uri: args.uri,- content: args.content,- mode: args.mode ?? "create",- wait: args.wait ?? false,- }- if (args.timeout !== undefined) body.timeout = args.timeout- const response = await makeRequest(config, {- method: "POST",- endpoint: "/api/v1/content/write",- body,- abortSignal: context.abort,- actorPeerId,- })- return JSON.stringify({ write: unwrapResponse(response) }, null, 2)- } catch (error) {- log("ERROR", "memwrite", "Write failed", { error: error?.message, args: { ...args, content: `[${args.content?.length ?? 0} chars]` } })- return `Error: ${error.message}`- }- },- }),-- memremove: tool({- description:- "Remove a viking:// resource. The user must explicitly confirm deletion before this tool is called. Set confirm=true, otherwise deletion is refused.",- args: {- uri: z.string().describe("Viking URI to remove."),- recursive: z.boolean().optional().describe("Recursively remove a directory."),- confirm: z.boolean().describe("Must be true after explicit user confirmation."),- },- async execute(args, context) {- if (!args.confirm) {- return "Error: Refusing to delete. Ask the user for explicit confirmation, then call memremove with confirm=true."- }- const validationError = validateVikingUri(args.uri, "memremove")- if (validationError) return validationError-- try {- const response = await makeRequest(config, {- method: "DELETE",- endpoint: `/api/v1/fs?uri=${encodeURIComponent(args.uri)}&recursive=${args.recursive ? "true" : "false"}`,- abortSignal: context.abort,- actorPeerId,- })- return JSON.stringify(unwrapResponse(response), null, 2)- } catch (error) {- log("ERROR", "memremove", "Remove failed", { error: error?.message, args })- return `Error: ${error.message}`- }- },- }),-- memqueue: tool({- description: "Return OpenViking observer queue status for embedding and semantic processing after resource indexing operations.",- args: {},- async execute(_args, context) {- try {- const queue = await getQueueStatus(config, context.abort)- return JSON.stringify(queue, null, 2)- } catch (error) {- log("ERROR", "memqueue", "Queue status failed", { error: error?.message })- return `Error: ${error.message}`- }- },- }),- }-}--async function resolveReadLevel(config, uri, abortSignal, actorPeerId) {- try {- const statResponse = await makeRequest(config, {- method: "GET",- endpoint: `/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,- abortSignal,- actorPeerId,- })- return unwrapResponse(statResponse)?.isDir ? "overview" : "read"- } catch {- return "read"- }-}--function resolveSearchMode(requestedMode, query, sessionId) {- if (requestedMode === "fast" || requestedMode === "deep") return requestedMode- if (sessionId) return "deep"- const normalized = query.trim()- const wordCount = normalized ? normalized.split(/\s+/).length : 0- return normalized.includes("?") || normalized.length >= 80 || wordCount >= 8 ? "deep" : "fast"-}--function formatSearchResults(result, query, extra) {- const memories = result?.memories ?? []- const resources = result?.resources ?? []- const skills = result?.skills ?? []- const allResults = [...memories, ...resources, ...skills]- if (allResults.length === 0) {- return "No results found matching the query."- }- return JSON.stringify(- {- total: result?.total ?? allResults.length,- memories,- resources,- skills,- query_plan: result?.query_plan,- query,- ...extra,- },- null,- 2,- )-}--function formatCommitResult(sessionId, result) {- const task = result.task- const payload = task?.result ?? result.result ?? {}- const memoriesExtracted = totalMemoriesExtracted(payload.memories_extracted)- return JSON.stringify(- {- message: result.status === "accepted" ? "Commit is still processing in the background" : `Memory extraction complete: ${memoriesExtracted} memories extracted`,- session_id: payload.session_id ?? sessionId,- status: result.status,- memories_extracted: memoriesExtracted,- archived: payload.archived ?? false,- task_id: task?.task_id ?? result.task_id,- },- null,- 2,- )-}--function totalMemoriesExtracted(memories) {- if (typeof memories === "number") return memories- if (!memories || typeof memories !== "object") return 0- return Object.entries(memories).reduce((sum, [key, value]) => {- if (key === "total") return sum- return sum + (typeof value === "number" ? value : 0)- }, 0)-}--async function getQueueStatus(config, abortSignal) {- const response = await makeRequest(config, {- method: "GET",- endpoint: "/api/v1/observer/queue",- abortSignal,- timeoutMs: 5000,- })- return unwrapResponse(response)-}diff --git a/examples/opencode-plugin/lib/repo-context.mjs b/examples/opencode-plugin/lib/repo-context.mjsindex 3a32e57d1..600930475 100644--- a/examples/opencode-plugin/lib/repo-context.mjs+++ b/examples/opencode-plugin/lib/repo-context.mjs@@ -45,11 +45,11 @@ export function createRepoContext({ config }) {"When the user asks about these projects or their internals, use the OpenViking tools before answering.","","Tool guidance:",- "- Use `memsearch` for semantic or conceptual repository questions.",- "- Use `memgrep` for exact symbols, error strings, class names, function names, and regex-like searches.",- "- Use `memglob` to enumerate files by pattern.",- "- Use `membrowse` to inspect directory structure and `memread` to read specific URIs.",- "- Use `memadd`, `memremove`, and `memqueue` for repository resource management when explicitly requested.",+ "- Use the `openviking_search` MCP tool for semantic or conceptual repository questions.",+ "- Use `openviking_grep` for exact symbols, error strings, class names, function names, and regex-like searches.",+ "- Use `openviking_glob` to enumerate files by pattern.",+ "- Use `openviking_list` to inspect directory structure and `openviking_read` to read specific URIs.",+ "- Use `openviking_add_resource` and `openviking_forget` for repository resource management when explicitly requested.","",cachedRepos,].join("\n")diff --git a/examples/opencode-plugin/lib/session-inject.mjs b/examples/opencode-plugin/lib/session-inject.mjsnew file mode 100644index 000000000..988fc405f--- /dev/null+++ b/examples/opencode-plugin/lib/session-inject.mjs@@ -0,0 +1,71 @@+import { buildProfileBlock } from "./shared/profile-inject.mjs"+import { effectivePeerId, fetchJSON, log } from "./utils.mjs"++export function createSessionInject({ config, sessionManager }) {+ const injectedSessions = new Set()++ async function injectSessionContext(input, output) {+ if (config.noAutoInject) return false+ const sessionID = input.sessionID ?? output.message?.sessionID+ const messageID = input.messageID ?? output.message?.id+ if (!sessionID || !messageID || injectedSessions.has(sessionID)) return false++ const ovSessionId = sessionManager.getMappedSessionId(sessionID)+ if (ovSessionId.includes("__subagent-")) return false++ const actorPeerId = effectivePeerId(config)+ const clientFetch = (endpoint, init = {}, options = {}) =>+ fetchJSON(config, endpoint, init, { ...options, actorPeerId, timeoutMs: 10000 })++ const parts = []+ const profile = await buildProfileBlock(clientFetch, config.profileTokenBudget, actorPeerId)+ if (profile?.block) parts.push(profile.block)++ const archive = await fetchArchiveBlock(clientFetch, ovSessionId, config.resumeContextBudget)+ if (archive) parts.push(archive)++ if (parts.length === 0) {+ injectedSessions.add(sessionID)+ return false+ }++ const block = [+ '<openviking-context source="session-start">',+ ...parts,+ "</openviking-context>",+ ].join("\n")++ output.parts.unshift({+ id: `prt-ov-session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,+ type: "text",+ text: block,+ synthetic: true,+ sessionID,+ messageID,+ })+ injectedSessions.add(sessionID)+ log("INFO", "session-inject", "Injected OpenViking session context", {+ opencode_session: sessionID,+ openviking_session: ovSessionId,+ hasProfile: Boolean(profile?.block),+ hasArchive: Boolean(archive),+ })+ return true+ }++ return { injectSessionContext }+}++async function fetchArchiveBlock(fetcher, ovSessionId, tokenBudget) {+ const res = await fetcher(+ `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/context?token_budget=${Math.max(1024, tokenBudget)}`,+ )+ if (!res.ok) return ""+ const overview = String(res.result?.latest_archive_overview || "").trim()+ if (!overview) return ""+ return [+ `<session-archive session="${ovSessionId}">`,+ overview,+ "</session-archive>",+ ].join("\n")+}diff --git a/examples/opencode-plugin/lib/shared/capture-utils.mjs b/examples/opencode-plugin/lib/shared/capture-utils.mjsnew file mode 100644index 000000000..3a1fb1fec--- /dev/null+++ b/examples/opencode-plugin/lib/shared/capture-utils.mjs@@ -0,0 +1,500 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/opencode-plugin/lib/shared/credentials.mjs b/examples/opencode-plugin/lib/shared/credentials.mjsnew file mode 100644index 000000000..76b30fb8e--- /dev/null+++ b/examples/opencode-plugin/lib/shared/credentials.mjs@@ -0,0 +1,207 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";++const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";++function str(val, fallback = "") {+ if (typeof val === "string" && val.trim()) return val.trim();+ return fallback;+}++function normalizePath(value) {+ const raw = str(value, "");+ if (!raw) return "";+ if (raw === "~") return homedir();+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));+ return resolvePath(raw);+}++function tryLoadJson(path) {+ if (!path) return null;+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return null;+ }+}++function looksLikeOvcli(obj) {+ if (!obj || typeof obj !== "object") return false;+ if (obj.server && typeof obj.server === "object") return false;+ return Boolean(+ typeof obj.url === "string" ||+ typeof obj.api_key === "string" ||+ typeof obj.account === "string" ||+ typeof obj.account_id === "string" ||+ typeof obj.user === "string" ||+ typeof obj.user_id === "string" ||+ typeof obj.actor_peer_id === "string",+ );+}++function hasCredentialFields(obj) {+ if (!obj || typeof obj !== "object") return false;+ return [+ "url",+ "api_key",+ "account",+ "account_id",+ "user",+ "user_id",+ "actor_peer_id",+ "peer_id",+ ].some((key) => typeof obj[key] === "string");+}++export function loadCredentialFiles(env = process.env) {+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));++ let cliFile = tryLoadJson(cliPathCandidate);+ let cliPath = cliFile ? cliPathCandidate : "";+ let ovFile = tryLoadJson(ovPathCandidate);+ let ovPath = ovFile ? ovPathCandidate : "";++ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {+ cliFile = ovFile;+ cliPath = ovPath;+ ovFile = null;+ ovPath = "";+ }++ return {+ cliFile: cliFile || {},+ cliPath,+ cliPathCandidate,+ ovFile: ovFile || {},+ ovPath,+ };+}++function sourceMode(env) {+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))+ .toLowerCase();+ if (raw === "env" || raw === "environment") return "env";+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";+ return "auto";+}++function hasEnvCredentialFields(env) {+ return Boolean(+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||+ str(env.OPENVIKING_MCP_URL, "") ||+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(env.OPENVIKING_USER, "") ||+ str(env.OPENVIKING_PEER_ID, ""),+ );+}++function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");+ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");++ const server = ovFile.server || {};+ const ovUrl = str(server.url, "");+ if (ovUrl) return ovUrl.replace(/\/+$/, "");++ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;+ return `http://${host}:${port}`;+}++export function resolveOpenVikingCredentials(env = process.env) {+ const files = loadCredentialFiles(env);+ const mode = sourceMode(env);+ const envHasCredentials = hasEnvCredentialFields(env);+ const useCli = mode === "cli" ||+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });++ const apiKey = useCli+ ? str(files.cliFile.api_key, "")+ : (+ str(env.OPENVIKING_BEARER_TOKEN, "") ||+ str(env.OPENVIKING_API_KEY, "") ||+ str(files.cliFile.api_key, "") ||+ str(cx.apiKey, "") ||+ str(server.root_api_key, "")+ );++ const account = useCli+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))+ : (+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||+ str(cx.accountId, "")+ );++ const user = useCli+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))+ : (+ str(env.OPENVIKING_USER, "") ||+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||+ str(cx.userId, "")+ );++ const peerId = useCli+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))+ : (+ str(env.OPENVIKING_PEER_ID, "") ||+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||+ str(cx.peerId, str(cx.peer_id, ""))+ );++ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),+ baseUrl,+ mcpUrl,+ apiKey,+ account,+ user,+ peerId,+ hasApiKey: Boolean(apiKey),+ };+}++function main() {+ const cmd = process.argv[2] || "";+ if (cmd === "mcp-url") {+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);+ return;+ }+ if (cmd === "has-api-key") {+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");+ return;+ }+ if (cmd === "has-peer-id") {+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");+ return;+ }+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");+ process.exitCode = 2;+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {+ main();+}diff --git a/examples/opencode-plugin/lib/shared/debug-log.mjs b/examples/opencode-plugin/lib/shared/debug-log.mjsnew file mode 100644index 000000000..73855cf6d--- /dev/null+++ b/examples/opencode-plugin/lib/shared/debug-log.mjs@@ -0,0 +1,58 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared structured debug logger for OpenViking memory plugin hook scripts.+ *+ * Harness-specific wrappers load config and pass {debug, debugLogPath}. This+ * module stays path-agnostic so it can be vendored into each plugin snapshot.+ */++import { appendFileSync, mkdirSync } from "node:fs";+import { dirname } from "node:path";++function ensureDir(filePath) {+ try {+ mkdirSync(dirname(filePath), { recursive: true });+ } catch { /* best effort */ }+}++function writeLine(filePath, obj) {+ try {+ appendFileSync(filePath, JSON.stringify(obj) + "\n");+ } catch { /* best effort */ }+}++function localISO() {+ const d = new Date();+ const off = d.getTimezoneOffset();+ const sign = off <= 0 ? "+" : "-";+ const abs = Math.abs(off);+ const local = new Date(d.getTime() - off * 60000);+ return local.toISOString().replace(+ "Z",+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`,+ );+}++const noop = () => {};++export function createLogger(hookName, overrideCfg) {+ const c = overrideCfg || {};+ if (!c.debug) return { log: noop, logError: noop };++ const logPath = c.debugLogPath;+ if (!logPath) return { log: noop, logError: noop };+ ensureDir(logPath);++ function log(stage, data) {+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });+ }++ function logError(stage, err) {+ const error = err instanceof Error+ ? { message: err.message, stack: err.stack }+ : String(err);+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });+ }++ return { log, logError };+}diff --git a/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjs b/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjsnew file mode 100644index 000000000..f420887c4--- /dev/null+++ b/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjs@@ -0,0 +1,451 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared stdio -> streamable-HTTP MCP proxy core for OpenViking memory plugins.+ *+ * Harness-specific entrypoints provide credential/config loading; this module+ * owns only transport, session retry, SSE parsing, and protocol-clean stdio.+ */++import { statSync } from "node:fs";+import { createInterface } from "node:readline";++const DEFAULT_PROTOCOL_VERSION = "2025-06-18";+const DELETE_TIMEOUT_MS = 2000;+const MAX_CONCURRENT_REQUESTS = 16;++class HttpStatusError extends Error {+ constructor(status, statusText, bodyText, messages = []) {+ super(`HTTP ${status}${statusText ? ` ${statusText}` : ""}`);+ this.name = "HttpStatusError";+ this.status = status;+ this.statusText = statusText;+ this.bodyText = bodyText;+ this.messages = messages;+ }+}++function snapshotPaths(paths) {+ const out = new Map();+ for (const path of paths || []) {+ try {+ const st = statSync(path);+ out.set(path, `${st.mtimeMs}:${st.size}`);+ } catch {+ out.set(path, "missing");+ }+ }+ return out;+}++function snapshotsDiffer(a, b) {+ if (a.size !== b.size) return true;+ for (const [key, value] of a.entries()) {+ if (b.get(key) !== value) return true;+ }+ return false;+}++function createSemaphore(limit) {+ let active = 0;+ const queue = [];+ return async function acquire() {+ if (active >= limit) {+ await new Promise((resolve) => queue.push(resolve));+ }+ active += 1;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ active -= 1;+ const next = queue.shift();+ if (next) next();+ };+ };+}++function isRequest(message) {+ return Object.prototype.hasOwnProperty.call(message || {}, "id");+}++function messageId(message) {+ return isRequest(message) ? message.id : undefined;+}++function errorResponse(id, code, message, data) {+ const error = { code, message };+ if (data !== undefined) error.data = data;+ return { jsonrpc: "2.0", id: id ?? null, error };+}++function parseMaybeJson(text) {+ const trimmed = String(text || "").trim();+ if (!trimmed) return null;+ try {+ return JSON.parse(trimmed);+ } catch {+ return null;+ }+}++function parseSseMessages(text) {+ const messages = [];+ let dataLines = [];++ function flush() {+ if (dataLines.length === 0) return;+ const data = dataLines.join("\n").trim();+ dataLines = [];+ if (!data || data === "[DONE]") return;+ messages.push(JSON.parse(data));+ }++ for (const rawLine of String(text || "").split(/\r?\n/)) {+ if (rawLine === "") {+ flush();+ continue;+ }+ if (rawLine.startsWith(":")) continue;+ const colon = rawLine.indexOf(":");+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);+ let value = colon === -1 ? "" : rawLine.slice(colon + 1);+ if (value.startsWith(" ")) value = value.slice(1);+ if (field === "data") dataLines.push(value);+ }+ flush();+ return messages;+}++function parseHttpBody(contentType, text) {+ const ctype = String(contentType || "").toLowerCase();+ if (!String(text || "").trim()) return [];+ if (ctype.includes("text/event-stream")) return parseSseMessages(text);+ const json = parseMaybeJson(text);+ return json == null ? [] : [json];+}++function serializeBodyForError(bodyText) {+ const parsed = parseMaybeJson(bodyText);+ if (parsed?.error?.message) return parsed.error.message;+ if (parsed?.detail) return typeof parsed.detail === "string" ? parsed.detail : JSON.stringify(parsed.detail);+ const compact = String(bodyText || "").replace(/\s+/g, " ").trim();+ return compact.slice(0, 500);+}++function cloneMessage(message) {+ return JSON.parse(JSON.stringify(message));+}++export function createOpenVikingMcpProxy({+ stdin = process.stdin,+ stdout = process.stdout,+ readConfig,+ loggerFactory,+ fetchImpl = globalThis.fetch,+} = {}) {+ if (typeof fetchImpl !== "function") {+ throw new Error("global fetch is required; use Node.js 18 or newer");+ }+ if (typeof readConfig !== "function") {+ throw new Error("readConfig function is required");+ }+ if (typeof loggerFactory !== "function") {+ throw new Error("loggerFactory function is required");+ }++ let proxyConfig = readConfig();+ let logger = loggerFactory("mcp-proxy", proxyConfig);+ let watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);+ let sessionId = "";+ let initializeRequest = null;+ let initializedNotification = null;+ let protocolVersion = DEFAULT_PROTOCOL_VERSION;+ let initializeInFlight = null;+ let reinitializeInFlight = null;+ let stdoutChain = Promise.resolve();+ let shuttingDown = false;+ let reinitCounter = 0;+ const acquire = createSemaphore(MAX_CONCURRENT_REQUESTS);++ function log(stage, data) {+ try {+ logger.log(stage, data);+ } catch { /* debug logging must never affect protocol IO */ }+ }++ function logError(stage, err) {+ try {+ logger.logError(stage, err);+ } catch { /* debug logging must never affect protocol IO */ }+ }++ function reloadConfig(reason) {+ proxyConfig = readConfig();+ logger = loggerFactory("mcp-proxy", proxyConfig);+ watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);+ log("credentials_reloaded", {+ reason,+ credentialSource: proxyConfig.credentialSource,+ credentialPath: proxyConfig.credentialPath,+ mcpUrl: proxyConfig.mcpUrl,+ hasApiKey: Boolean(proxyConfig.apiKey),+ hasIdentity: Boolean(proxyConfig.account || proxyConfig.user),+ hasPeer: Boolean(proxyConfig.peerId),+ });+ }++ function reloadIfCredentialFilesChanged(reason) {+ const next = snapshotPaths(proxyConfig.watchedPaths);+ if (!snapshotsDiffer(watchedSnapshot, next)) return false;+ reloadConfig(reason);+ return true;+ }++ function headersForRequest(includeSession = true, message = null) {+ const headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": message?.params?.protocolVersion || protocolVersion,+ };+ if (includeSession && sessionId) headers["Mcp-Session-Id"] = sessionId;+ if (proxyConfig.apiKey) headers.Authorization = `Bearer ${proxyConfig.apiKey}`;+ if (proxyConfig.account) headers["X-OpenViking-Account"] = proxyConfig.account;+ if (proxyConfig.user) headers["X-OpenViking-User"] = proxyConfig.user;+ if (proxyConfig.peerId) headers["X-OpenViking-Actor-Peer"] = proxyConfig.peerId;+ return headers;+ }++ function writeMessage(obj) {+ const line = `${JSON.stringify(obj)}\n`;+ stdoutChain = stdoutChain+ .then(() => new Promise((resolve) => stdout.write(line, resolve)))+ .catch(() => {});+ return stdoutChain;+ }++ function mapError(message, err) {+ const id = messageId(message);+ if (err instanceof HttpStatusError) {+ if (err.status === 401 || err.status === 403) {+ return errorResponse(+ id,+ -32001,+ `OpenViking MCP authentication failed (HTTP ${err.status}). Check ~/.openviking/ovcli.conf or OPENVIKING_API_KEY, and verify the configured account/user for trusted mode.`,+ {+ status: err.status,+ credentialSource: proxyConfig.credentialSource,+ credentialPath: proxyConfig.credentialPath || undefined,+ serverMessage: serializeBodyForError(err.bodyText) || undefined,+ },+ );+ }+ return errorResponse(+ id,+ -32002,+ `OpenViking MCP upstream returned HTTP ${err.status}.`,+ {+ status: err.status,+ serverMessage: serializeBodyForError(err.bodyText) || undefined,+ },+ );+ }+ const msg = err instanceof Error ? err.message : String(err);+ return errorResponse(+ id,+ -32001,+ `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that 'ov serve' is running.`,+ { cause: msg },+ );+ }++ async function postToMcp(message, { includeSession = true, timeoutMs = proxyConfig.timeoutMs } = {}) {+ const release = await acquire();+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetchImpl(proxyConfig.mcpUrl, {+ method: "POST",+ headers: headersForRequest(includeSession, message),+ body: JSON.stringify(message),+ signal: controller.signal,+ });+ const text = await res.text();+ const messages = parseHttpBody(res.headers.get("content-type"), text);+ const nextSessionId = res.headers.get("mcp-session-id");+ if (nextSessionId) sessionId = nextSessionId;+ if (!res.ok) {+ throw new HttpStatusError(res.status, res.statusText, text, messages);+ }+ return { status: res.status, messages };+ } finally {+ clearTimeout(timer);+ release();+ }+ }++ async function deleteSession() {+ if (!sessionId || shuttingDown) return;+ shuttingDown = true;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), DELETE_TIMEOUT_MS);+ try {+ await fetchImpl(proxyConfig.mcpUrl, {+ method: "DELETE",+ headers: headersForRequest(true),+ signal: controller.signal,+ });+ } catch (err) {+ logError("delete_session_failed", err);+ } finally {+ clearTimeout(timer);+ sessionId = "";+ }+ }++ async function reinitialize(failedSessionId) {+ if (!initializeRequest) {+ throw new Error("MCP session expired before initialize parameters were cached");+ }+ if (reinitializeInFlight) return reinitializeInFlight;+ reinitializeInFlight = (async () => {+ if (failedSessionId && sessionId && sessionId !== failedSessionId) return;+ const reinit = cloneMessage(initializeRequest);+ reinit.id = `openviking-proxy-reinit-${Date.now()}-${++reinitCounter}`;+ sessionId = "";+ const result = await postToMcp(reinit, { includeSession: false });+ if (initializedNotification) {+ await postToMcp(cloneMessage(initializedNotification), { includeSession: true });+ }+ log("reinitialized", { mcpUrl: proxyConfig.mcpUrl, status: result.status, sessionId: Boolean(sessionId) });+ })().finally(() => {+ reinitializeInFlight = null;+ });+ return reinitializeInFlight;+ }++ async function sendWithRetry(message, { expectsResponse }) {+ if (message.method !== "initialize" && initializeInFlight) {+ await initializeInFlight.catch(() => {});+ }++ const failedSessionId = sessionId;+ try {+ return await postToMcp(message, { includeSession: message.method !== "initialize" });+ } catch (err) {+ if (err instanceof HttpStatusError && (err.status === 401 || err.status === 403)) {+ if (reloadIfCredentialFilesChanged("auth_failure")) {+ sessionId = "";+ if (message.method !== "initialize" && initializeRequest) {+ await reinitialize(failedSessionId);+ }+ return await postToMcp(message, { includeSession: message.method !== "initialize" });+ }+ }+ if (+ err instanceof HttpStatusError+ && (err.status === 400 || err.status === 404)+ && message.method !== "initialize"+ && initializeRequest+ ) {+ await reinitialize(failedSessionId);+ return await postToMcp(message, { includeSession: true });+ }+ if (!expectsResponse) {+ logError("notification_failed", err);+ }+ throw err;+ }+ }++ async function handleMessage(message) {+ if (!message || typeof message !== "object" || message.jsonrpc !== "2.0") {+ await writeMessage(errorResponse(null, -32600, "Invalid JSON-RPC message"));+ return;+ }++ const expectsResponse = isRequest(message);+ if (message.method === "initialize") {+ initializeRequest = cloneMessage(message);+ protocolVersion = message.params?.protocolVersion || protocolVersion || DEFAULT_PROTOCOL_VERSION;+ sessionId = "";+ }+ if (message.method === "notifications/initialized") {+ initializedNotification = cloneMessage(message);+ }++ try {+ const send = sendWithRetry(message, { expectsResponse });+ if (message.method === "initialize") {+ initializeInFlight = send+ .catch(() => {})+ .finally(() => {+ initializeInFlight = null;+ });+ }+ const result = await send;+ if (!expectsResponse) return;+ if (result.messages.length === 0) {+ await writeMessage(errorResponse(message.id, -32003, "OpenViking MCP upstream returned an empty response"));+ return;+ }+ for (const outbound of result.messages) {+ await writeMessage(outbound);+ }+ } catch (err) {+ if (expectsResponse) {+ await writeMessage(mapError(message, err));+ } else {+ logError("notification_unhandled", err);+ }+ }+ }++ async function handleLine(line) {+ const trimmed = line.trim();+ if (!trimmed) return;+ let message;+ try {+ message = JSON.parse(trimmed);+ } catch {+ await writeMessage(errorResponse(null, -32700, "Parse error"));+ return;+ }+ await handleMessage(message);+ }++ async function closeAndExit(code = 0) {+ await deleteSession();+ await stdoutChain;+ process.exit(code);+ }++ async function closeSession() {+ await deleteSession();+ await stdoutChain;+ }++ function start() {+ log("start", {+ mcpUrl: proxyConfig.mcpUrl,+ credentialSource: proxyConfig.credentialSource,+ credentialPath: proxyConfig.credentialPath,+ hasApiKey: Boolean(proxyConfig.apiKey),+ });+ const rl = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });+ rl.on("line", (line) => {+ void handleLine(line);+ });+ rl.on("close", () => {+ void closeAndExit(0);+ });+ process.on("SIGINT", () => {+ void closeAndExit(130);+ });+ process.on("SIGTERM", () => {+ void closeAndExit(143);+ });+ return { close: () => closeAndExit(0) };+ }++ return { start, handleMessage, parseSseMessages, closeSession };+}diff --git a/examples/opencode-plugin/lib/shared/pending-queue.mjs b/examples/opencode-plugin/lib/shared/pending-queue.mjsnew file mode 100644index 000000000..cbf6d445f--- /dev/null+++ b/examples/opencode-plugin/lib/shared/pending-queue.mjs@@ -0,0 +1,439 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Local pending queue for offline resilience.+ *+ * When the OpenViking server is temporarily unreachable, write operations+ * (addMessage, commitSession) serialize their payloads to+ * `~/.openviking/pending/` as JSON files. On the next session-start, the+ * queue is replayed in small batches. This is a session-start-triggered retry+ * path with maxRetries/TTL, not a long-running background worker.+ *+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }+ *+ * Config (env vars):+ * OPENVIKING_PENDING_DIR pending queue directory+ * (default: ~/.openviking/pending)+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup+ * (default: 7)+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start+ * (default: 50)+ */++import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join } from "node:path";+import { homedir } from "node:os";++const DEFAULT_MAX_RETRIES = 3;+const DEFAULT_TTL_DAYS = 7;+const DEFAULT_REPLAY_LIMIT = 50;+const PROCESSING_STALE_MS = 10 * 60 * 1000;+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");++// Pending queue files may contain raw memory payload / transcript content.+// Use restrictive permissions explicitly so we don't depend on umask.+// - dir: 0o700 (owner: rwx; group/other: none)+// - file: 0o600 (owner: rw; group/other: none)+const PENDING_DIR_MODE = 0o700;+const PENDING_FILE_MODE = 0o600;++/**+ * Ensure the pending directory exists with 0o700 permissions. If the+ * directory was created by a previous version of this code (or by hand)+ * with looser permissions, best-effort chmod it on first use.+ */+async function ensurePendingDir(dir) {+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });+ try {+ await chmod(dir, PENDING_DIR_MODE);+ } catch {+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.+ }+}++function getPendingDir() {+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();+}++function getMaxRetries() {+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;+}++function getTTLDays() {+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;+}++function getReplayLimit() {+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;+}++function stableStringify(value) {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;+}++function makeDedupKey(type, sessionId, payload) {+ return createHash("sha256")+ .update(type)+ .update("\n")+ .update(sessionId)+ .update("\n")+ .update(stableStringify(payload))+ .digest("hex");+}++function pendingFilename(dedupKey, retries = 0) {+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;+}++function retryFilename(filename, retries) {+ const bare = filename.replace(/\.(json|processing)$/, "");+ const nextBare = /_\d+$/.test(bare)+ ? bare.replace(/_\d+$/, `_${retries}`)+ : `${bare}_${retries}`;+ return `${nextBare}.json`;+}++function processingFilename(filename) {+ return filename.replace(/\.json$/, ".processing");+}++function pendingFromProcessingFilename(filename) {+ return filename.replace(/\.processing$/, ".json");+}++function isRetryableReplayFailure(res) {+ if (!res || res.ok) return false;+ const status = Number(res.status || 0);+ return !status || status >= 500 || status === 408 || status === 429;+}++async function readEntry(dir, filename) {+ const raw = await readFile(join(dir, filename), "utf-8");+ return JSON.parse(raw);+}++async function findExistingByDedupKey(dir, dedupKey) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return null;+ }++ // Fast path: filenames are `${dedupKey}_${retries}.json` (or+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.+ // Filter on prefix BEFORE opening the file to avoid readFile ++ // JSON.parse on every entry in the directory on every enqueue call —+ // the previous implementation was O(n²) in queue size. Worst case here+ // is O(n) readdir entries, but only the (typically single) prefix+ // match actually gets opened and parsed.+ const prefix = `${dedupKey}_`;++ for (const f of files) {+ if (!f.startsWith(prefix)) continue;+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;+ try {+ const entry = await readEntry(dir, f);+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };+ } catch {+ // Corrupted file - ignore for dedup lookup.+ }+ }+ return null;+}++async function recoverStaleProcessing(dir) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return 0;+ }++ const now = Date.now();+ let recovered = 0;+ for (const f of files) {+ if (!f.endsWith(".processing")) continue;+ const from = join(dir, f);+ try {+ const s = await stat(from);+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;+ const to = join(dir, pendingFromProcessingFilename(f));+ await rename(from, to);+ recovered++;+ } catch {+ // Best effort. A concurrent process may have already handled it.+ }+ }+ return recovered;+}++/**+ * Enqueue a failed operation to local disk.+ *+ * @param {string} type - "addMessage" or "commitSession"+ * @param {string} sessionId - OV session ID+ * @param {object} payload - the data that failed to send+ */+export async function enqueue(type, sessionId, payload) {+ const dir = getPendingDir();+ const now = Date.now();+ const dedupKey = makeDedupKey(type, sessionId, payload);+ const filename = pendingFilename(dedupKey, 0);+ const entry = {+ type,+ sessionId,+ payload,+ createdAt: now,+ retries: 0,+ dedupKey,+ };++ try {+ await ensurePendingDir(dir);+ } catch (err) {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }++ const existing = await findExistingByDedupKey(dir, dedupKey);+ if (existing) {+ return { ok: true, path: existing.filename, deduped: true, dedupKey };+ }++ try {+ await writeFile(join(dir, filename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ return { ok: true, path: filename, dedupKey };+ } catch (err) {+ if (err?.code !== "EEXIST") {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }+ }++ const duplicate = await findExistingByDedupKey(dir, dedupKey);+ if (duplicate) {+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };+ }+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };+}++/**+ * List all pending queue entries.+ * Returns array of { filename, entry } sorted by createdAt ascending.+ */+export async function listPending() {+ const dir = getPendingDir();+ let files;+ try {+ await recoverStaleProcessing(dir);+ files = await readdir(dir);+ } catch {+ return [];+ }++ const entries = [];+ for (const f of files) {+ if (!f.endsWith(".json")) continue;+ try {+ const entry = await readEntry(dir, f);+ entries.push({ filename: f, entry });+ } catch {+ // Corrupted file - skip.+ }+ }++ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));+ return entries;+}++/**+ * Atomically claim a pending file for replay. Only the process that successfully+ * renames the file may send the HTTP replay.+ */+export async function claimForReplay(filename) {+ if (!filename.endsWith(".json")) return null;+ const dir = getPendingDir();+ const claimed = processingFilename(filename);+ try {+ await rename(join(dir, filename), join(dir, claimed));+ return claimed;+ } catch {+ return null;+ }+}++/**+ * Remove a pending entry after successful replay.+ */+export async function dequeue(filename) {+ const dir = getPendingDir();+ try {+ await unlink(join(dir, filename));+ return true;+ } catch {+ return false;+ }+}++/**+ * Increment retry count on a pending entry. Returns false if max retries exceeded.+ */+export async function incrementRetry(filename, entry) {+ const dir = getPendingDir();+ const maxRetries = getMaxRetries();+ entry.retries = (entry.retries || 0) + 1;++ if (entry.retries > maxRetries) {+ try {+ await unlink(join(dir, filename));+ } catch {+ // Best effort.+ }+ return false;+ }++ const newFilename = retryFilename(filename, entry.retries);+ // Atomic write: write to a unique temp file in the same directory, then+ // rename into place. Avoids leaving a half-written JSON if the process+ // crashes mid-write.+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ await rename(join(dir, tmpFilename), join(dir, newFilename));+ await unlink(join(dir, filename)).catch(() => {});+ return true;+ } catch {+ await unlink(join(dir, tmpFilename)).catch(() => {});+ return false;+ }+}++/**+ * Clean up stale entries older than TTL.+ */+export async function cleanStale() {+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;+ const now = Date.now();+ const pending = await listPending();+ let cleaned = 0;++ for (const { filename, entry } of pending) {+ const age = now - (entry.createdAt || 0);+ if (age > ttlMs) {+ await dequeue(filename);+ cleaned++;+ }+ }+ return cleaned;+}++/**+ * Replay pending entries. Call this during session-start when the server is+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so+ * a just-recovered server is not hit with an unbounded replay burst.+ *+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON+ * @param {Function} log - logger function+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}+ */+export async function replayPending(fetchJSON, log) {+ const pending = await listPending();++ if (pending.length === 0) {+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };+ }++ const replayLimit = getReplayLimit();+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });++ let replayed = 0;+ let failed = 0;+ let skipped = 0;+ let deferred = 0;+ let processed = 0;++ for (const { filename, entry } of pending) {+ if (processed >= replayLimit) {+ deferred++;+ continue;+ }++ if ((entry.retries || 0) >= getMaxRetries()) {+ await dequeue(filename);+ skipped++;+ continue;+ }++ const claimedFilename = await claimForReplay(filename);+ if (!claimedFilename) {+ skipped++;+ continue;+ }+ processed++;++ let res;+ try {+ const encodedSid = encodeURIComponent(entry.sessionId);+ if (entry.type === "addMessage") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {+ method: "POST",+ body: JSON.stringify(entry.payload),+ });+ } else if (entry.type === "commitSession") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {+ method: "POST",+ body: JSON.stringify(entry.payload || {}),+ });+ } else {+ await dequeue(claimedFilename);+ skipped++;+ continue;+ }+ } catch {+ res = { ok: false };+ }++ if (res?.ok) {+ await dequeue(claimedFilename);+ replayed++;+ } else if (!isRetryableReplayFailure(res)) {+ await dequeue(claimedFilename);+ skipped++;+ } else {+ await incrementRetry(claimedFilename, entry);+ failed++;+ if (entry.type === "addMessage") {+ deferred += Math.max(0, pending.length - processed);+ break;+ }+ }+ }++ const cleaned = await cleanStale();++ log("pending-queue", {+ action: "replay-done",+ replayed,+ failed,+ skipped,+ deferred,+ cleaned,+ });++ return { replayed, failed, skipped, deferred };+}diff --git a/examples/opencode-plugin/lib/shared/profile-inject.mjs b/examples/opencode-plugin/lib/shared/profile-inject.mjsnew file mode 100644index 000000000..3f601844a--- /dev/null+++ b/examples/opencode-plugin/lib/shared/profile-inject.mjs@@ -0,0 +1,294 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url, {}, { actorPeerId });+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/opencode-plugin/lib/shared/recall-core.mjs b/examples/opencode-plugin/lib/shared/recall-core.mjsnew file mode 100644index 000000000..445f00b1a--- /dev/null+++ b/examples/opencode-plugin/lib/shared/recall-core.mjs@@ -0,0 +1,282 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },+];++let userSpaceCache = "";++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);+ return {+ query: "",+ quotas: {+ events: limit,+ entities: limit,+ preferences: Math.max(1, Math.min(limit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (userSpaceCache) return userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ if (items.length === 0) return null;++ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),+ });++ return lines.join("\n");+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}++export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return null;++ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);+ if (endpointBlock !== null) return endpointBlock || null;++ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return null;++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return null;+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}diff --git a/examples/opencode-plugin/lib/shared/session-model.mjs b/examples/opencode-plugin/lib/shared/session-model.mjsnew file mode 100644index 000000000..b6496a113--- /dev/null+++ b/examples/opencode-plugin/lib/shared/session-model.mjs@@ -0,0 +1,57 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared OpenViking session-id helpers for memory plugin harnesses.+ */++/**+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.+ */+function globToRe(glob) {+ let re = "^";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i];+ if (c === "*") {+ if (glob[i + 1] === "*") { re += ".*"; i++; }+ else re += "[^/]*";+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {+ re += "\\" + c;+ } else {+ re += c;+ }+ }+ re += "$";+ return new RegExp(re);+}++export function isBypassed(cfg, { sessionId, cwd } = {}) {+ if (cfg.bypassSession) return true;+ const patterns = cfg.bypassSessionPatterns || [];+ if (patterns.length === 0) return false;+ const haystacks = [sessionId, cwd].filter(Boolean);+ for (const pat of patterns) {+ const re = globToRe(pat);+ if (haystacks.some((h) => re.test(h))) return true;+ }+ return false;+}++function safeId(value, replacement = "_") {+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);+}++export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {+ if (!prefix || typeof prefix !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");+ }+ if (!sessionId || typeof sessionId !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");+ }+ const base = `${prefix}${sessionId}`;+ if (!suffix) return base;+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");+ return `${base}__${normalized}`;+}++export function deriveCodexSessionId(codexSessionId) {+ return `cx-${safeId(codexSessionId, "_")}`;+}diff --git a/examples/opencode-plugin/lib/shared/setup-wizard.mjs b/examples/opencode-plugin/lib/shared/setup-wizard.mjsnew file mode 100644index 000000000..5108f5f2b--- /dev/null+++ b/examples/opencode-plugin/lib/shared/setup-wizard.mjs@@ -0,0 +1,111 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.+ *+ * Lets a pure-marketplace install (no installer script) configure the server+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:+ *+ * node <plugin>/scripts/setup.mjs+ *+ * Conventions: show current values, keep existing secrets on empty input,+ * merge-write (never drop unknown fields), back up the previous file, 0600.+ */++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline/promises";+import { loadCredentialFiles } from "./credentials.mjs";++const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";+const LOCAL_URL = "http://127.0.0.1:1933";++function maskSecret(value) {+ const s = String(value || "");+ if (!s) return "(not set)";+ if (s.length <= 8) return "****";+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;+}++function readJsonSafe(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return {};+ }+}++export async function runSetupWizard({+ input = process.stdin,+ output = process.stdout,+ env = process.env,+} = {}) {+ const { cliPath } = loadCredentialFiles(env);+ const current = readJsonSafe(cliPath);+ const rl = createInterface({ input, output });+ const say = (line = "") => output.write(`${line}\n`);++ try {+ say("OpenViking memory plugin setup");+ say(`Config file: ${cliPath}`);+ say("");+ say("Current values:");+ say(` url: ${current.url || "(not set)"}`);+ say(` api_key: ${maskSecret(current.api_key)}`);+ if (current.account) say(` account: ${current.account}`);+ if (current.user) say(` user: ${current.user}`);+ say("");++ const defaultUrl = current.url || LOCAL_URL;+ say("Where do you connect to OpenViking?");+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);+ say(` 3) Custom URL / keep current [${defaultUrl}]`);+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();+ let url = defaultUrl;+ if (mode === "1") {+ url = LOCAL_URL;+ } else if (mode === "2") {+ url = CLOUD_URL;+ } else {+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();+ if (answer) url = answer;+ }++ const keyPrompt = current.api_key+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `+ : "API key (leave empty for unauthenticated local mode): ";+ const keyAnswer = await rl.question(keyPrompt);+ let apiKey = current.api_key || "";+ if (keyAnswer === "-") apiKey = "";+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();+ else if (!current.api_key) apiKey = "";++ const next = { ...current, url, api_key: apiKey };++ say("");+ say("Changes:");+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();+ if (confirm === "n" || confirm === "no") {+ say("Aborted; nothing written.");+ return { written: false, path: cliPath };+ }++ mkdirSync(dirname(cliPath), { recursive: true });+ if (existsSync(cliPath)) {+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);+ }+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(cliPath, 0o600);+ } catch {+ /* best effort on platforms without chmod semantics */+ }+ say(`Written: ${cliPath}`);+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");+ return { written: true, path: cliPath };+ } finally {+ rl.close();+ }+}diff --git a/examples/opencode-plugin/lib/shared/uri-guard.mjs b/examples/opencode-plugin/lib/shared/uri-guard.mjsnew file mode 100644index 000000000..9505ddb5e--- /dev/null+++ b/examples/opencode-plugin/lib/shared/uri-guard.mjs@@ -0,0 +1,56 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+ "pattern",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args);+}++export function findVikingUriInValue(value) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex e451f6b59..8ad5202ff 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -1,123 +1,8 @@import fs from "fs"import path from "path"-import { homedir } from "os"--export const DEFAULT_CONFIG = {- endpoint: "http://localhost:1933",- apiKey: "",- account: "",- user: "",- peerId: "",- enabled: true,- timeoutMs: 30000,- runtime: {- dataDir: "",- },- repoContext: {- enabled: true,- cacheTtlMs: 60000,- },- autoRecall: {- enabled: true,- limit: 6,- scoreThreshold: 0.15,- maxContentChars: 500,- preferAbstract: true,- tokenBudget: 2000,- },-}let logFilePath = null-function cloneDefaultConfig() {- return JSON.parse(JSON.stringify(DEFAULT_CONFIG))-}--function mergeConfig(fileConfig = {}) {- const config = cloneDefaultConfig()- for (const key of ["endpoint", "apiKey", "account", "user", "peerId", "enabled", "timeoutMs"]) {- if (fileConfig[key] !== undefined) config[key] = fileConfig[key]- }- config.runtime = {- ...DEFAULT_CONFIG.runtime,- dataDir: fileConfig.runtime?.dataDir ?? DEFAULT_CONFIG.runtime.dataDir,- }- config.repoContext = { ...DEFAULT_CONFIG.repoContext, ...(fileConfig.repoContext ?? {}) }- config.autoRecall = { ...DEFAULT_CONFIG.autoRecall, ...(fileConfig.autoRecall ?? {}) }-- if (process.env.OPENVIKING_API_KEY) {- config.apiKey = process.env.OPENVIKING_API_KEY- }- if (process.env.OPENVIKING_ACCOUNT) {- config.account = process.env.OPENVIKING_ACCOUNT- }- if (process.env.OPENVIKING_USER) {- config.user = process.env.OPENVIKING_USER- }- if (process.env.OPENVIKING_PEER_ID) {- config.peerId = process.env.OPENVIKING_PEER_ID- }-- config.timeoutMs = normalizeNumber(config.timeoutMs, DEFAULT_CONFIG.timeoutMs, 1000, 300000)- config.repoContext.cacheTtlMs = normalizeNumber(- config.repoContext.cacheTtlMs,- DEFAULT_CONFIG.repoContext.cacheTtlMs,- 1000,- 60 * 60 * 1000,- )- clampRecallConfig(config.autoRecall)- return config-}--function normalizeNumber(value, fallback, min, max) {- const next = Number(value)- if (!Number.isFinite(next)) return fallback- return Math.max(min, Math.min(max, next))-}--function clampRecallConfig(recall) {- recall.limit = Math.max(1, Math.min(50, Math.round(Number(recall.limit) || 6)))- recall.scoreThreshold = Math.max(0, Math.min(1, Number(recall.scoreThreshold) || 0))- recall.maxContentChars = Math.max(100, Math.min(5000, Math.round(Number(recall.maxContentChars) || 500)))- recall.tokenBudget = Math.max(100, Math.min(10000, Math.round(Number(recall.tokenBudget) || 2000)))-}--export function loadConfig(pluginRoot, projectDirectory) {- for (const configPath of getConfigPaths(pluginRoot, projectDirectory)) {- try {- if (fs.existsSync(configPath)) {- const fileConfig = JSON.parse(fs.readFileSync(configPath, "utf8"))- return mergeConfig(fileConfig)- }- } catch (error) {- console.warn(`Failed to load OpenViking config from ${configPath}:`, error)- }- }- return mergeConfig()-}--function getConfigPaths(pluginRoot, projectDirectory) {- const paths = []- if (process.env.OPENVIKING_PLUGIN_CONFIG) paths.push(expandHome(process.env.OPENVIKING_PLUGIN_CONFIG))- if (projectDirectory) paths.push(path.join(projectDirectory, ".opencode", "openviking-config.json"))- paths.push(path.join(homedir(), ".config", "opencode", "openviking-config.json"))- paths.push(path.join(pluginRoot, "openviking-config.json"))- return paths-}--export function resolveDataDir(pluginRoot, config) {- const configured = config.runtime?.dataDir- if (configured) return expandHome(configured)- return path.join(homedir(), ".config", "opencode", "openviking")-}--function expandHome(value) {- if (!value || typeof value !== "string") return value- if (value === "~") return homedir()- if (value.startsWith("~/") || value.startsWith("~\\")) return path.join(homedir(), value.slice(2))- return value-}-export function initLogger(dataDir) {fs.mkdirSync(dataDir, { recursive: true })logFilePath = path.join(dataDir, "openviking-memory.log")@@ -183,6 +68,38 @@ export function effectivePeerId(config) {return String(config.peerId || "").trim() || null}+export async function fetchJSON(config, endpoint, init = {}, options = {}) {+ const url = `${normalizeEndpoint(config.endpoint)}${endpoint}`+ const headers = makeAuthHeaders(+ config,+ { "Content-Type": "application/json", ...(init.headers ?? {}) },+ options.actorPeerId,+ )+ const controller = new AbortController()+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)+ try {+ const response = await fetch(url, {+ ...init,+ headers,+ signal: controller.signal,+ })+ const text = await response.text()+ const payload = text ? parseJsonOrText(text) : {}+ if (!response.ok || payload?.status === "error") {+ return {+ ok: false,+ status: response.status,+ error: payload?.error || payload?.message || { message: `HTTP ${response.status}` },+ }+ }+ return { ok: true, status: response.status, result: payload?.result ?? payload }+ } catch (error) {+ return { ok: false, status: 0, error: { message: error?.message ?? String(error) } }+ } finally {+ clearTimeout(timeout)+ }+}+export async function makeRequest(config, options) {const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`const headers = makeAuthHeaders(@@ -291,7 +208,7 @@ export async function makeMultipartRequest(config, options) {function makeAuthHeaders(config, headers = {}, actorPeerId = "") {const result = { ...headers }- if (config.apiKey) result["X-API-Key"] = config.apiKey+ if (config.apiKey) result["Authorization"] = `Bearer ${config.apiKey}`if (config.account) result["X-OpenViking-Account"] = config.accountif (config.user) result["X-OpenViking-User"] = config.userconst peerId = String(actorPeerId || "").trim()diff --git a/examples/opencode-plugin/lib/viking-uri-guard.mjs b/examples/opencode-plugin/lib/viking-uri-guard.mjsindex fa5f4cebe..3f428df4c 100644--- a/examples/opencode-plugin/lib/viking-uri-guard.mjs+++ b/examples/opencode-plugin/lib/viking-uri-guard.mjs@@ -1,17 +1,18 @@import { log } from "./utils.mjs"+import { buildGuardMessage, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs"const FILESYSTEM_TOOL_HINTS = {read: {- replacement: "memread",- example: (uri) => `memread(uri="${uri}", level="auto")`,+ tool: "openviking_read",+ example: (uri) => `openviking_read(uri="${uri}")`,},glob: {- replacement: "membrowse",- example: (uri) => `membrowse(uri="${uri}", view="list", recursive=true)`,+ tool: "openviking_glob",+ example: (uri) => `openviking_glob(uri="${uri}", pattern="**/*")`,},grep: {- replacement: "memsearch",- example: (uri, args) => `memsearch(query="${String(args.pattern ?? "").replaceAll('"', '\\"')}", target_uri="${uri}")`,+ tool: "openviking_search",+ example: (uri, args = {}) => `openviking_search(query="${String(args.pattern ?? "").replaceAll('"', '\\"')}", target_uri="${uri}")`,},}@@ -29,24 +30,8 @@ export function createVikingUriGuard() {tool: toolName,uri,})- throw new Error(- [- "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",- `Use ${hint.replacement} instead.`,- `Example: ${hint.example(uri, args)}`,- ].join("\n"),- )+ throw new Error(buildGuardMessage(uri, { ...hint, example: hint.example(uri, args) }))}}-export function findVikingUri(args = {}) {- for (const key of ["filePath", "path", "uri"]) {- const value = args[key]- if (typeof value === "string" && value.startsWith("viking://")) return value- }- return null-}--function normalizeToolName(value) {- return String(value || "").trim().toLowerCase()-}+export { findVikingUri, normalizeToolName }diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.jsonindex 2aaf13080..84b130066 100644--- a/examples/opencode-plugin/package.json+++ b/examples/opencode-plugin/package.json@@ -1,6 +1,6 @@{"name": "@openviking/opencode-plugin",- "version": "0.1.6",+ "version": "0.2.0","author": "@openviking","description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory","type": "module",@@ -10,22 +10,23 @@"tui"],"exports": {- ".": "./index.mjs"+ ".": "./index.mjs",+ "./servers/mcp-proxy.mjs": "./servers/mcp-proxy.mjs"},"files": ["index.mjs","lib/",+ "servers/",+ "scripts/","README.md","INSTALL.md","INSTALL-ZH.md"],"scripts": {- "check": "node --check index.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memadd-local.mjs && node --check lib/memory-tools.mjs && node --check lib/code-tools.mjs && node --check lib/memory-recall.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check tests/*.test.mjs",- "test": "node --test tests/*.test.mjs"- },- "dependencies": {- "@opencode-ai/plugin": "^1.14.37"+ "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs",+ "test": "node --test tests/*.test.mjs servers/*.test.mjs"},+ "dependencies": {},"publishConfig": {"access": "public"},diff --git a/examples/opencode-plugin/scripts/setup.mjs b/examples/opencode-plugin/scripts/setup.mjsnew file mode 100644index 000000000..31f96a5da--- /dev/null+++ b/examples/opencode-plugin/scripts/setup.mjs@@ -0,0 +1,8 @@+#!/usr/bin/env node++import { runSetupWizard } from "../lib/shared/setup-wizard.mjs"++runSetupWizard().catch((err) => {+ process.stderr.write(`${err?.stack || err}\n`)+ process.exit(1)+})diff --git a/examples/opencode-plugin/servers/mcp-proxy.mjs b/examples/opencode-plugin/servers/mcp-proxy.mjsnew file mode 100644index 000000000..9fae6d0f0--- /dev/null+++ b/examples/opencode-plugin/servers/mcp-proxy.mjs@@ -0,0 +1,67 @@+#!/usr/bin/env node++/**+ * stdio -> streamable-HTTP MCP proxy for the OpenViking OpenCode plugin.+ *+ * OpenCode starts this process as a local MCP server. The proxy reads the same+ * OpenViking credential sources as the lifecycle hooks, forwards JSON-RPC+ * requests to the server's /mcp endpoint, and keeps stdout protocol-clean.+ */++import { homedir } from "node:os"+import { join, resolve as resolvePath } from "node:path"+import { fileURLToPath } from "node:url"+import { loadConfig } from "../lib/config.mjs"+import { createLogger } from "../lib/shared/debug-log.mjs"+import { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"++export { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"++const DEFAULT_TIMEOUT_MS = 15000++function trimSlash(value) {+ return String(value || "").replace(/\/+$/, "")+}++function normalizePath(value) {+ const raw = String(value || "").trim()+ if (!raw) return ""+ if (raw === "~") return homedir()+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)))+ return resolvePath(raw)+}++function uniq(values) {+ return [...new Set(values.filter(Boolean))]+}++function readProxyConfig() {+ const cfg = loadConfig(resolvePath(fileURLToPath(import.meta.url), "..", ".."))+ const mcpUrl = cfg.mcpUrl || `${trimSlash(cfg.endpoint)}/mcp`+ return {+ mcpUrl,+ apiKey: cfg.apiKey || "",+ account: cfg.account || "",+ user: cfg.user || "",+ peerId: cfg.peerId || "",+ timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),+ debug: cfg.debug === true,+ debugLogPath: cfg.debugLogPath,+ credentialSource: cfg.credentialSource || "auto",+ credentialPath: cfg.credentialPath || cfg.configPath || "",+ watchedPaths: uniq([+ cfg.credentialPath,+ cfg.configPath,+ normalizePath(process.env.OPENVIKING_CLI_CONFIG_FILE),+ normalizePath(process.env.OPENVIKING_CONFIG_FILE),+ normalizePath(process.env.OPENVIKING_PLUGIN_CONFIG),+ join(homedir(), ".openviking", "ovcli.conf"),+ join(homedir(), ".openviking", "ov.conf"),+ join(homedir(), ".config", "opencode", "openviking-config.json"),+ ]),+ }+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {+ createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start()+}diff --git a/examples/opencode-plugin/servers/mcp-proxy.test.mjs b/examples/opencode-plugin/servers/mcp-proxy.test.mjsnew file mode 100644index 000000000..5a1c7c8ca--- /dev/null+++ b/examples/opencode-plugin/servers/mcp-proxy.test.mjs@@ -0,0 +1,100 @@+import test from "node:test"+import assert from "node:assert/strict"+import { createServer } from "node:http"+import { Writable } from "node:stream"+import { createOpenVikingMcpProxy } from "./mcp-proxy.mjs"++function jsonRpc(id, result = {}) {+ return { jsonrpc: "2.0", id, result }+}++function sseMessage(obj) {+ return `event: message\r\ndata: ${JSON.stringify(obj)}\r\n\r\n`+}++async function readBody(req) {+ const chunks = []+ for await (const chunk of req) chunks.push(chunk)+ return Buffer.concat(chunks).toString("utf-8")+}++async function withServer(handler, fn) {+ const requests = []+ const server = createServer(async (req, res) => {+ const body = await readBody(req)+ const entry = {+ method: req.method,+ url: req.url,+ headers: req.headers,+ body: body ? JSON.parse(body) : null,+ }+ requests.push(entry)+ await handler(req, res, entry)+ })+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))+ try {+ const { port } = server.address()+ return await fn({ url: `http://127.0.0.1:${port}/mcp`, requests })+ } finally {+ await new Promise((resolve) => server.close(resolve))+ }+}++function makeProxy(url) {+ const out = []+ const stdout = new Writable({+ write(chunk, _encoding, callback) {+ out.push(chunk.toString("utf-8"))+ callback()+ },+ })+ const proxy = createOpenVikingMcpProxy({+ stdout,+ readConfig: () => ({+ mcpUrl: url,+ apiKey: "test-key",+ account: "acct",+ user: "user",+ peerId: "peer",+ timeoutMs: 5000,+ debug: false,+ debugLogPath: "",+ credentialSource: "test",+ credentialPath: "",+ watchedPaths: [],+ }),+ loggerFactory: () => ({ log() {}, logError() {} }),+ })+ return {+ proxy,+ async messages() {+ await new Promise((resolve) => setImmediate(resolve))+ return out.join("").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line))+ },+ }+}++test("OpenCode MCP proxy forwards initialize with auth and identity headers", async () => {+ await withServer((_req, res, entry) => {+ assert.equal(entry.method, "POST")+ assert.equal(entry.headers.authorization, "Bearer test-key")+ assert.equal(entry.headers["x-openviking-account"], "acct")+ assert.equal(entry.headers["x-openviking-user"], "user")+ assert.equal(entry.headers["x-openviking-actor-peer"], "peer")+ res.writeHead(200, {+ "content-type": "text/event-stream",+ "mcp-session-id": "sid-oc",+ })+ res.end(sseMessage(jsonRpc(1, { protocolVersion: "2025-06-18" })))+ }, async ({ url, requests }) => {+ const { proxy, messages } = makeProxy(url)+ await proxy.handleMessage({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: "2025-06-18" },+ })+ assert.deepEqual(await messages(), [jsonRpc(1, { protocolVersion: "2025-06-18" })])+ assert.equal(requests.length, 1)+ })+})diff --git a/examples/opencode-plugin/tests/code-tools-request-options.test.mjs b/examples/opencode-plugin/tests/code-tools-request-options.test.mjsdeleted file mode 100644index 785e0d0d6..000000000--- a/examples/opencode-plugin/tests/code-tools-request-options.test.mjs+++ /dev/null@@ -1,35 +0,0 @@-import test from "node:test"-import assert from "node:assert/strict"-import { readFile } from "node:fs/promises"-import { fileURLToPath } from "node:url"-import { dirname, join } from "node:path"--const testDir = dirname(fileURLToPath(import.meta.url))-const codeToolsPath = join(testDir, "../lib/code-tools.mjs")-const memoryRecallPath = join(testDir, "../lib/memory-recall.mjs")--test("code tools propagate actorPeerId to every code request", async () => {- const source = await readFile(codeToolsPath, "utf8")-- assert.match(source, /import \{ effectivePeerId,/)- assert.match(source, /const actorPeerId = effectivePeerId\(config\)/)- assert.equal((source.match(/actorPeerId,\n\s+abortSignal: context\.abort/g) ?? []).length, 3)-})--test("code tool descriptions restrict use to confirmed viking code repositories", async () => {- const source = await readFile(codeToolsPath, "utf8")-- assert.match(source, /confirmed viking:\/\/ code repository or source subtree/)- assert.match(source, /evidence that the uri contains supported source files/)- assert.match(source, /Do not use for general memory search/)- assert.match(source, /documentation-only resources/)- assert.match(source, /chat\/session history/)- assert.match(source, /local filesystem paths/)-})--test("memory recall search payload matches strict server schema", async () => {- const source = await readFile(memoryRecallPath, "utf8")-- assert.match(source, /const body = \{ query: query\.slice\(0, 4000\), limit: 20 \}/)- assert.doesNotMatch(source, /mode:\s*"auto"/)-})diff --git a/examples/opencode-plugin/tests/config.test.mjs b/examples/opencode-plugin/tests/config.test.mjsnew file mode 100644index 000000000..373b7683c--- /dev/null+++ b/examples/opencode-plugin/tests/config.test.mjs@@ -0,0 +1,100 @@+import test from "node:test"+import assert from "node:assert/strict"+import { mkdtemp, rm, writeFile, mkdir } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { loadConfig } from "../lib/config.mjs"++async function withTempDir(prefix, fn) {+ const dir = await mkdtemp(join(tmpdir(), prefix))+ try {+ return await fn(dir)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+}++function restoreOpenVikingEnv(snapshot) {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith("OPENVIKING_")) delete process.env[key]+ }+ for (const [key, value] of Object.entries(snapshot)) {+ if (key.startsWith("OPENVIKING_")) process.env[key] = value+ }+}++test("loadConfig prefers env credentials over ovcli and legacy config", async () => {+ const snapshot = { ...process.env }+ await withTempDir("ov-oc-config-", async (dir) => {+ try {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith("OPENVIKING_")) delete process.env[key]+ }+ const ovcli = join(dir, "ovcli.conf")+ const project = join(dir, "project")+ await mkdir(join(project, ".opencode"), { recursive: true })+ await writeFile(ovcli, JSON.stringify({+ url: "https://cli.example.com",+ api_key: "cli-key",+ account: "cli-account",+ user: "cli-user",+ actor_peer_id: "cli-peer",+ }))+ await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({+ endpoint: "https://legacy.example.com",+ apiKey: "legacy-key",+ account: "legacy-account",+ user: "legacy-user",+ peerId: "legacy-peer",+ }))+ process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli+ process.env.OPENVIKING_URL = "https://env.example.com"+ process.env.OPENVIKING_API_KEY = "env-key"+ process.env.OPENVIKING_ACCOUNT = "env-account"+ process.env.OPENVIKING_USER = "env-user"+ process.env.OPENVIKING_PEER_ID = "env-peer"++ const cfg = loadConfig(dir, project)+ assert.equal(cfg.endpoint, "https://env.example.com")+ assert.equal(cfg.apiKey, "env-key")+ assert.equal(cfg.account, "env-account")+ assert.equal(cfg.user, "env-user")+ assert.equal(cfg.peerId, "env-peer")+ assert.equal(cfg.legacyCredentialsUsed, false)+ } finally {+ restoreOpenVikingEnv(snapshot)+ }+ })+})++test("loadConfig reads legacy credentials as fallback and marks deprecation", async () => {+ const snapshot = { ...process.env }+ await withTempDir("ov-oc-legacy-", async (dir) => {+ try {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith("OPENVIKING_")) delete process.env[key]+ }+ const project = join(dir, "project")+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "missing-ovcli.conf")+ process.env.OPENVIKING_CONFIG_FILE = join(dir, "missing-ov.conf")+ await mkdir(join(project, ".opencode"), { recursive: true })+ await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({+ endpoint: "https://legacy.example.com",+ apiKey: "legacy-key",+ account: "legacy-account",+ user: "legacy-user",+ peerId: "legacy-peer",+ }))++ const cfg = loadConfig(dir, project)+ assert.equal(cfg.endpoint, "https://legacy.example.com")+ assert.equal(cfg.apiKey, "legacy-key")+ assert.equal(cfg.account, "legacy-account")+ assert.equal(cfg.user, "legacy-user")+ assert.equal(cfg.peerId, "legacy-peer")+ assert.equal(cfg.legacyCredentialsUsed, true)+ } finally {+ restoreOpenVikingEnv(snapshot)+ }+ })+})diff --git a/examples/opencode-plugin/tests/mcp-config.test.mjs b/examples/opencode-plugin/tests/mcp-config.test.mjsnew file mode 100644index 000000000..a227e940e--- /dev/null+++ b/examples/opencode-plugin/tests/mcp-config.test.mjs@@ -0,0 +1,52 @@+import test from "node:test"+import assert from "node:assert/strict"+import { readFile } from "node:fs/promises"+import { fileURLToPath } from "node:url"+import { dirname, join } from "node:path"+import { createOpenVikingMcpConfig, injectOpenVikingMcpConfig } from "../lib/mcp-config.mjs"++const testDir = dirname(fileURLToPath(import.meta.url))++test("injectOpenVikingMcpConfig registers a local stdio MCP server", () => {+ const config = {}++ assert.equal(injectOpenVikingMcpConfig(config, "/tmp/openviking-plugin"), true)+ assert.deepEqual(config.mcp.openviking, {+ type: "local",+ command: ["node", "/tmp/openviking-plugin/servers/mcp-proxy.mjs"],+ enabled: true,+ timeout: 15000,+ })+})++test("injectOpenVikingMcpConfig respects explicit disabled MCP server", () => {+ const config = { mcp: { openviking: { enabled: false } } }++ assert.equal(injectOpenVikingMcpConfig(config, "/tmp/openviking-plugin"), false)+ assert.deepEqual(config.mcp.openviking, { enabled: false })+})++test("OpenCode plugin keeps tools on MCP rather than native tool hook", async () => {+ const source = await readFile(join(testDir, "../index.mjs"), "utf8")++ assert.match(source, /injectOpenVikingMcpConfig/)+ assert.doesNotMatch(source, /createMemoryTools/)+ assert.doesNotMatch(source, /createCodeTools/)+ assert.doesNotMatch(source, /\btool:\s*\{/)+})++test("OpenCode plugin uses real lifecycle hooks for capture flushing", async () => {+ const source = await readFile(join(testDir, "../index.mjs"), "utf8")++ assert.doesNotMatch(source, /"session\.idle":/)+ assert.doesNotMatch(source, /\bstop:\s*async/)+ assert.match(source, /\bdispose:\s*async/)+})++test("OpenCode MCP config points to the proxy entrypoint", () => {+ const entry = createOpenVikingMcpConfig("/tmp/ov")++ assert.equal(entry.type, "local")+ assert.equal(entry.command[0], "node")+ assert.match(entry.command[1], /servers\/mcp-proxy\.mjs$/)+})diff --git a/examples/opencode-plugin/tests/memory-session.test.mjs b/examples/opencode-plugin/tests/memory-session.test.mjsnew file mode 100644index 000000000..e271a51f0--- /dev/null+++ b/examples/opencode-plugin/tests/memory-session.test.mjs@@ -0,0 +1,147 @@+import test from "node:test"+import assert from "node:assert/strict"+import { createServer } from "node:http"+import { mkdtemp, rm } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { createMemorySessionManager } from "../lib/memory-session.mjs"++async function withTempDir(prefix, fn) {+ const dir = await mkdtemp(join(tmpdir(), prefix))+ try {+ return await fn(dir)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+}++async function withCaptureServer(fn) {+ const requests = []+ const server = createServer(async (req, res) => {+ let body = ""+ req.setEncoding("utf8")+ for await (const chunk of req) body += chunk+ requests.push({ method: req.method, url: req.url, body })++ res.setHeader("Content-Type", "application/json")+ if (req.url === "/health") {+ res.end(JSON.stringify({ status: "ok" }))+ } else if (req.url?.startsWith("/api/v1/sessions/") && req.url.endsWith("/messages")) {+ res.end(JSON.stringify({ status: "ok", result: { accepted: true } }))+ } else if (req.url?.startsWith("/api/v1/sessions/")) {+ res.end(JSON.stringify({ status: "ok", result: { pending_tokens: 0 } }))+ } else {+ res.statusCode = 404+ res.end(JSON.stringify({ status: "error", error: { message: "not found" } }))+ }+ })++ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))+ try {+ const { port } = server.address()+ return await fn({ endpoint: `http://127.0.0.1:${port}`, requests })+ } finally {+ await new Promise((resolve) => server.close(resolve))+ }+}++function baseConfig(endpoint) {+ return {+ endpoint,+ apiKey: "",+ account: "",+ user: "",+ peerId: "",+ timeoutMs: 5000,+ captureAssistantTurns: true,+ captureToolMaxChars: 2000,+ captureMode: "semantic",+ captureMaxLength: 24000,+ commitTokenThreshold: 20000,+ commitKeepRecentCount: 10,+ }+}++test("session.idle event flushes pending OpenCode capture", async () => {+ await withCaptureServer(async ({ endpoint, requests }) => {+ await withTempDir("ov-oc-session-", async (dir) => {+ const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })++ await manager.init()+ await manager.handleEvent({ type: "session.created", properties: { info: { id: "oc-session-1" } } })+ await manager.handleEvent({+ type: "message.updated",+ properties: {+ info: {+ id: "msg-user-1",+ sessionID: "oc-session-1",+ role: "user",+ },+ },+ })+ await manager.handleEvent({+ type: "message.part.updated",+ properties: {+ part: {+ id: "part-user-1",+ messageID: "msg-user-1",+ sessionID: "oc-session-1",+ type: "text",+ text: "Remember that OpenCode idle events must flush captures.",+ },+ },+ })++ await manager.handleEvent({ type: "session.idle", sessionID: "oc-session-1" })++ const addMessage = requests.find((request) => request.url === "/api/v1/sessions/oc-oc-session-1/messages")+ assert.ok(addMessage, "session.idle should POST pending messages")+ const body = JSON.parse(addMessage.body)+ assert.equal(body.role, "user")+ assert.match(body.content, /idle events must flush captures/)+ await manager.flushAll({ commit: false })+ })+ })+})++test("assistant messages are captured even when finish is not stop", async () => {+ await withCaptureServer(async ({ endpoint, requests }) => {+ await withTempDir("ov-oc-session-", async (dir) => {+ const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })++ await manager.init()+ await manager.handleEvent({+ type: "message.updated",+ properties: {+ info: {+ id: "msg-assistant-1",+ sessionID: "oc-session-2",+ role: "assistant",+ finish: "length",+ },+ },+ })+ await manager.handleEvent({+ type: "message.part.updated",+ properties: {+ part: {+ id: "part-assistant-1",+ messageID: "msg-assistant-1",+ sessionID: "oc-session-2",+ type: "text",+ text: "Partial assistant output still belongs in capture.",+ },+ },+ })++ await manager.handleEvent({ type: "session.idle", properties: { sessionID: "oc-session-2" } })++ const addMessage = requests.find((request) => request.url === "/api/v1/sessions/oc-oc-session-2/messages")+ assert.ok(addMessage, "session.idle should capture non-stop assistant messages")+ const body = JSON.parse(addMessage.body)+ assert.equal(body.role, "assistant")+ assert.match(body.content, /Partial assistant output/)+ await manager.flushAll({ commit: false })+ })+ })+})diff --git a/examples/opencode-plugin/tests/memory-tools-write.test.mjs b/examples/opencode-plugin/tests/memory-tools-write.test.mjsdeleted file mode 100644index 987e7d7f5..000000000--- a/examples/opencode-plugin/tests/memory-tools-write.test.mjs+++ /dev/null@@ -1,18 +0,0 @@-import test from "node:test"-import assert from "node:assert/strict"-import { readFile } from "node:fs/promises"-import { fileURLToPath } from "node:url"-import { dirname, join } from "node:path"--const testDir = dirname(fileURLToPath(import.meta.url))-const memoryToolsPath = join(testDir, "../lib/memory-tools.mjs")--test("memwrite uses content/write with safe defaults and peer propagation", async () => {- const source = await readFile(memoryToolsPath, "utf8")-- assert.match(source, /memwrite: tool\(/)- assert.match(source, /endpoint: "\/api\/v1\/content\/write"/)- assert.match(source, /mode: args\.mode \?\? "create"/)- assert.match(source, /actorPeerId,/)- assert.match(source, /mode: z\.enum\(\["create", "append", "replace"\]\)/)-})diff --git a/examples/opencode-plugin/tests/utils-logger.test.mjs b/examples/opencode-plugin/tests/utils-logger.test.mjsnew file mode 100644index 000000000..f57c0288c--- /dev/null+++ b/examples/opencode-plugin/tests/utils-logger.test.mjs@@ -0,0 +1,19 @@+import test from "node:test"+import assert from "node:assert/strict"+import { mkdtemp, readFile, rm } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { initLogger, log } from "../lib/utils.mjs"++test("initLogger creates the OpenViking log file path and log writes JSONL", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ov-oc-log-"))+ try {+ initLogger(dir)+ log("INFO", "test", "hello", { ok: true })+ const raw = await readFile(join(dir, "openviking-memory.log"), "utf8")+ assert.match(raw, /"tool":"test"/)+ assert.match(raw, /"message":"hello"/)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+})diff --git a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs b/examples/opencode-plugin/tests/viking-uri-guard.test.mjsindex 84d3bb612..d76f00267 100644--- a/examples/opencode-plugin/tests/viking-uri-guard.test.mjs+++ b/examples/opencode-plugin/tests/viking-uri-guard.test.mjs@@ -10,15 +10,15 @@ test("viking uri guard blocks filesystem tools on virtual URIs", async () => {await assert.rejects(() => guard({ tool: "read" }, { args: { filePath: "viking://resources/project/file.md" } }),- /Use memread instead/,+ /Use openviking_read instead/,)await assert.rejects(() => guard({ tool: "glob" }, { args: { path: "viking://resources/project/" } }),- /Use membrowse instead/,+ /Use openviking_glob instead/,)await assert.rejects(() => guard({ tool: "grep" }, { args: { path: "viking://resources/project/", pattern: "SessionManager" } }),- /Use memsearch instead/,+ /Use openviking_search instead/,)await assert.doesNotReject(() => guard({ tool: "read" }, { args: { filePath: "/tmp/file.md" } }))diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.mdindex c1708030a..742213390 100644--- a/examples/pi-coding-agent-extension/DESIGN.md+++ b/examples/pi-coding-agent-extension/DESIGN.md@@ -1,5 +1,7 @@# Pi OpenViking Extension — Implementation Spec+> Current implementation note: this historical design has been superseded by the Claude Code/Codex-aligned SPEC retrofit. Legacy sections below are retained as background, not as current behavior.+## Design Philosophy**Informed by all three existing OV plugins** — OpenClaw, Claude Code, and Hermes. The Claude Code plugin is the most mature and production-hardened; its patterns take precedence where they differ from OpenClaw. Key design ancestors:diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.mdindex 745e352d2..0b829b5f3 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -1,6 +1,6 @@# OpenViking Memory Extension for Pi Coding Agent-Long-term semantic memory for [Pi](https://github.com/mariozechner/pi-coding-agent) sessions, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens after every turn, and sessions are committed for persistent memory extraction — all via pi's native extension API.+Long-term semantic memory for [pi](https://github.com/earendil-works/pi) sessions, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens after every turn, and sessions are committed for persistent memory extraction — all via pi's native extension API.> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the full design spec with comparison tables and event flow diagrams.@@ -8,7 +8,7 @@ Long-term semantic memory for [Pi](https://github.com/mariozechner/pi-coding-age### Prerequisites-- **Pi coding agent** installed (`npm i -g @mariozechner/pi-coding-agent`)+- **pi coding agent** installed (`npm i -g @earendil-works/pi-coding-agent`)- **Node.js 18+** (for the extension's TypeScript runtime)- **An OpenViking server** reachable — local or remote@@ -24,41 +24,48 @@ curl http://localhost:1933/health # or your remote URL### 2. Install the extension-Copy the extension directory into pi's extension folder:+Use the shared installer:```bash-mkdir -p ~/.pi/agent/extensions-cp -r examples/pi-coding-agent-extension ~/.pi/agent/extensions/openviking+bash examples/memory-plugin-shared/install.sh --harness pi```-Pi auto-discovers extensions in `~/.pi/agent/extensions/` — no explicit registration needed. The extension loads on next `pi` invocation.+The installer copies the extension to `~/.pi/agent/extensions/openviking` and registers it with `pi install`. The extension loads on next `pi` invocation.### 3. Configure (optional)-The extension ships with defaults that work out-of-the-box for a local OpenViking server (`http://127.0.0.1:1933`, no auth). To connect to a remote server or tune behavior, edit `~/.pi/agent/extensions/openviking/config.json`:+Credentials are resolved from `OPENVIKING_*` environment variables, `~/.openviking/ovcli.conf`, then `~/.openviking/ov.conf`. Run the setup wizard when you need to configure a remote server:++```bash+node ~/.pi/agent/extensions/openviking/scripts/setup.mjs+```++`~/.pi/agent/extensions/openviking/config.json` is for behavior knobs only:```json{"enabled": true,- "endpoint": "https://your-openviking-server.example.com",- "apiKey": "<your-api-key>",- "account": "my-team",- "user": "alice",- "agentId": "pi"+ "syncTurns": true,+ "recallTokenBudget": 2000,+ "scoreThreshold": 0.35,+ "minQueryLength": 3,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000,+ "commitTokenThreshold": 20000}```-All config fields can also be overridden via environment variables:+Credential environment variables:-| Env Var | Config field | Default |-|--------------------------|------------------|-------------------------------|-| `OPENVIKING_URL` | `endpoint` | `http://127.0.0.1:1933` |-| `OPENVIKING_API_KEY` | `apiKey` | `""` (no auth) |-| `OPENVIKING_ACCOUNT` | `account` | `""` |-| `OPENVIKING_USER` | `user` | `""` |-| `OPENVIKING_AGENT_ID` | `agentId` | `"pi"` |+| Env Var | Meaning |+|---------|---------|+| `OPENVIKING_URL` | OpenViking server URL |+| `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN` | Bearer token |+| `OPENVIKING_ACCOUNT` | Trusted-mode account |+| `OPENVIKING_USER` | Trusted-mode user |+| `OPENVIKING_PEER_ID` | Actor peer id |-Env vars take priority over `config.json`.+API keys are sent as `Authorization: Bearer ...`. `OPENVIKING_PEER_ID` is sent as `X-OpenViking-Actor-Peer` and stored as `peer_id` on captured session messages.### 4. Start Pi@@ -77,50 +84,42 @@ All fields below live in `config.json`. Defaults are shown.| Field | Default | Description ||--------------------------|------------|--------------------------------------------------------------------------|| `enabled` | `true` | Set `false` to disable the extension entirely |-| `endpoint` | (local) | OpenViking server URL |-| `apiKey` | `""` | API key for remote servers |-| `account` | `""` | Multi-tenant account (`X-OpenViking-Account`) |-| `user` | `""` | Multi-tenant user (`X-OpenViking-User`) |-| `agentId` | `"pi"` | Agent identity (`X-OpenViking-Agent`) |+| `syncTurns` | `true` | Enable auto-capture of conversation turns |### Recall tuning| Field | Default | Description ||--------------------------|------------|--------------------------------------------------------------------------|-| `recallBudget` | `2000` | Token budget for inline recall content |+| `recallTokenBudget` | `2000` | Token budget for inline recall content || `recallMaxContentChars` | `500` | Per-item content cap for search results || `recallPreferAbstract` | `true` | Prefer L0 abstract over L2 full body when available || `recallLimit` | `6` | Max memories to inject per prompt |-| `recallScoreThreshold` | `0.35` | Min relevance score (0–1) |-| `recallMinQueryLength` | `3` | Skip recall for queries shorter than N characters |+| `scoreThreshold` | `0.35` | Min relevance score (0–1) |+| `minQueryLength` | `3` | Skip recall for queries shorter than N characters |### Capture tuning| Field | Default | Description ||--------------------------|------------|--------------------------------------------------------------------------|-| `syncTurns` | `true` | Enable auto-capture of conversation turns || `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) |+| `captureToolMaxChars` | `2000` | Max captured output chars for one tool part || `commitTokenThreshold` | `20000` | Pending-token threshold for client-driven commit |-| `commitOnShutdown` | `true` | Auto-commit session on exit |+| `commitKeepRecentCount` | `10` | Live tail kept after commit |### Injection tuning| Field | Default | Description ||--------------------------|------------|--------------------------------------------------------------------------|-| `profileBudget` | `10000` | Token budget for user profile block |-| `resumeContextBudget` | `2000` | Token budget for archive overview on session resume |-| `indexBudget` | `2000` | Token budget for the knowledge index (map of what OV knows) |+| `profileTokenBudget` | `10000` | Token budget for user profile block |+| `resumeContextBudget` | `32000` | Token budget for archive overview on session resume |### Misc| Field | Default | Description ||--------------------------|------------|--------------------------------------------------------------------------|-| `mirrorMemoryWrites` | `true` | Mirror built-in memory writes into the OV session |-| `writeQueueFlushInterval`| `5000` | Write queue flush interval (ms) |-| `writeQueueFlushThreshold`| `5` | Write queue flush after N turns || `bypassPatterns` | `[]` | Glob patterns to skip extension processing || `logLevel` | `"error"` | `"silent"`, `"error"`, or `"info"` |@@ -151,16 +150,16 @@ The extension is a single directory of TypeScript files loaded by pi's `jiti` tr| Pi Event | Extension Action ||------------------------|----------------------------------------------------------------------------------|-| `session_start` | Health check → create/find OV session → build profile block → build memory index → register tools |-| `before_agent_start` | Fallback tool registration (for `pi -c` resume) + inject archive overview |-| `context` | Search OV with current prompt → inject `<relevant-memories>` block |-| `turn_end` | Extract user + assistant turns → queue writes to OV session |+| `session_start` | Health check → derive OV session → build profile/archive context → register tools |+| `before_agent_start` | Fallback tool registration (for `pi -c` resume) + inject session context |+| `context` | Search OV with current prompt → inject `<openviking-context>` block |+| `turn_end` | Extract branch entries → write or pending-queue OV session messages || `session_before_compact`| Commit pending messages before pi rewrites the transcript || `session_shutdown` | Final commit so the last window is archived |### Recall: Synchronous, Not Stale-Unlike Hermes's stale prefetch (recall from previous turn's query, injected one turn late), this extension searches OpenViking with the **current** user prompt via pi's `context` event. Results are injected into the same turn as `<relevant-memories>` blocks. This means:+Unlike Hermes's stale prefetch (recall from previous turn's query, injected one turn late), this extension searches OpenViking with the **current** user prompt via pi's `context` event. Results are injected into the same turn as `<openviking-context>` blocks. This means:- **First turn** of a session gets relevant context immediately- **Topic switches** within a session get correct recall@@ -168,11 +167,11 @@ Unlike Hermes's stale prefetch (recall from previous turn's query, injected one### Memory Pollution Prevention-Before pushing turns to OpenViking, the extension strips injected context blocks (`<openviking-context>`, `<relevant-memories>`, `<system-reminder>`) to prevent a self-referential pollution loop where recall context is captured back as user messages.+Before pushing turns to OpenViking, shared capture sanitization strips injected context blocks such as `<openviking-context>` to prevent a self-referential pollution loop where recall context is captured back as user messages.### Tool Use Preservation-Tool capture preserves agent-authored inputs (`[tool: read]\n<path>`) and drops raw tool results by default. The memory extractor sees what the agent *did*, not megabytes of raw output.+Tool capture preserves structured tool parts with bounded inputs and outputs. The memory extractor sees what the agent did without indexing unbounded raw output.## LLM Toolsdiff --git a/examples/pi-coding-agent-extension/client.ts b/examples/pi-coding-agent-extension/client.tsindex 158fa8387..1bbe14147 100644--- a/examples/pi-coding-agent-extension/client.ts+++ b/examples/pi-coding-agent-extension/client.ts@@ -66,7 +66,7 @@ export class OVClient {private apiKey: string;private account: string;private user: string;- private agent: string;+ private peerId: string;connected: boolean = false;private resolvedSpaces: Map<string, string> = new Map();@@ -83,7 +83,7 @@ export class OVClient {this.apiKey = config.apiKey;this.account = config.account;this.user = config.user;- this.agent = config.agentId;+ this.peerId = config.peerId;}private headers(): Record<string, string> {@@ -91,12 +91,12 @@ export class OVClient {if (this.apiKey) h["Authorization"] = `Bearer ${this.apiKey}`;if (this.account) h["X-OpenViking-Account"] = this.account;if (this.user) h["X-OpenViking-User"] = this.user;- if (this.agent) h["X-OpenViking-Agent"] = this.agent;+ if (this.peerId) h["X-OpenViking-Actor-Peer"] = this.peerId;return h;}/** Core fetch wrapper. Returns { ok, result } after parsing OV's { status, result } envelope. */- private async fetchJSON<T>(path: string, init?: RequestInit, timeoutMs = 10000): Promise<{ ok: boolean; result: T | null; error?: any }> {+ async fetchJSON<T>(path: string, init?: RequestInit, timeoutMs = 10000): Promise<{ ok: boolean; result: T | null; error?: any; status?: number }> {try {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);@@ -108,11 +108,11 @@ export class OVClient {clearTimeout(timer);const body = await resp.json().catch(() => ({}));if (!resp.ok || body.status === "error") {- return { ok: false, result: null, error: body.error || { message: `HTTP ${resp.status}` } };+ return { ok: false, result: null, status: resp.status, error: body.error || { message: `HTTP ${resp.status}` } };}return { ok: true, result: (body.result ?? body) as T };} catch (err: any) {- return { ok: false, result: null, error: { message: err?.message || String(err) } };+ return { ok: false, result: null, status: 0, error: { message: err?.message || String(err) } };}}@@ -174,11 +174,20 @@ export class OVClient {return res.ok;}+ async addMessagePayload(sessionId: string, payload: any): Promise<boolean> {+ const res = await this.fetchJSON<any>(+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,+ { method: "POST", body: JSON.stringify(payload) },+ 10000,+ );+ return res.ok;+ }+/** POST /api/v1/sessions/{id}/commit — commit session for archiving + extraction */async commitSession(sessionId: string): Promise<{ task_id: string; archive_uri: string } | null> {const res = await this.fetchJSON<{ task_id: string; archive_uri: string }>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,- { method: "POST", body: JSON.stringify({}) },+ { method: "POST", body: JSON.stringify({ keep_recent_count: this.cfg.commitKeepRecentCount }) },30000,);return res.ok ? res.result : null;@@ -219,7 +228,7 @@ export class OVClient {for (const m of items) {all.push({uri: m.uri ?? "",- context_type: m.context_type ?? bucket === "memories" ? "memory" : bucket === "skills" ? "skill" : "resource",+ context_type: m.context_type ?? (bucket === "memories" ? "memory" : bucket === "skills" ? "skill" : "resource"),score: m.score ?? 0,abstract: m.abstract ?? "",overview: m.overview ?? null,diff --git a/examples/pi-coding-agent-extension/config.json b/examples/pi-coding-agent-extension/config.jsonindex 7c388eed3..315194b53 100644--- a/examples/pi-coding-agent-extension/config.json+++ b/examples/pi-coding-agent-extension/config.json@@ -1,29 +1,21 @@{"enabled": true,- "endpoint": "http://127.0.0.1:1933",- "apiKey": "",- "account": "",- "user": "",- "agentId": "pi","syncTurns": true,- "recallBudget": 2000,+ "recallTokenBudget": 2000,"recallMaxContentChars": 500,"recallPreferAbstract": true,"recallLimit": 6,- "recallScoreThreshold": 0.35,- "recallMinQueryLength": 3,- "profileBudget": 10000,- "resumeContextBudget": 2000,- "indexBudget": 2000,+ "scoreThreshold": 0.35,+ "minQueryLength": 3,+ "profileTokenBudget": 10000,+ "resumeContextBudget": 32000,"commitTokenThreshold": 20000,- "commitOnShutdown": true,+ "commitKeepRecentCount": 10,"captureToolResults": false,"captureMode": "semantic","captureMaxLength": 24000,+ "captureToolMaxChars": 2000,"captureAssistantTurns": true,- "mirrorMemoryWrites": true,- "writeQueueFlushInterval": 5000,- "writeQueueFlushThreshold": 5,"bypassPatterns": [],"logLevel": "error"}diff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.tsindex ec55de51a..60b570daa 100644--- a/examples/pi-coding-agent-extension/config.ts+++ b/examples/pi-coding-agent-extension/config.ts@@ -1,5 +1,6 @@import { readFileSync, existsSync } from "node:fs";import { join, dirname } from "node:path";+import { resolveOpenVikingCredentials } from "./shared/credentials.mjs";export interface OVConfig {enabled: boolean;@@ -7,26 +8,23 @@ export interface OVConfig {apiKey: string;account: string;user: string;- agentId: string;+ peerId: string;syncTurns: boolean;- recallBudget: number;+ recallTokenBudget: number;recallMaxContentChars: number;recallPreferAbstract: boolean;recallLimit: number;- recallScoreThreshold: number;- recallMinQueryLength: number;- profileBudget: number;+ scoreThreshold: number;+ minQueryLength: number;+ profileTokenBudget: number;resumeContextBudget: number;- indexBudget: number;commitTokenThreshold: number;- commitOnShutdown: boolean;+ commitKeepRecentCount: number;captureToolResults: boolean;captureMode: "semantic" | "keyword";captureMaxLength: number;+ captureToolMaxChars: number;captureAssistantTurns: boolean;- mirrorMemoryWrites: boolean;- writeQueueFlushInterval: number;- writeQueueFlushThreshold: number;bypassPatterns: string[];logLevel: "silent" | "error" | "info";}@@ -37,38 +35,81 @@ const DEFAULT_CONFIG: OVConfig = {apiKey: "",account: "",user: "",- agentId: "pi",+ peerId: "",syncTurns: true,- recallBudget: 2000,+ recallTokenBudget: 2000,recallMaxContentChars: 500,recallPreferAbstract: true,recallLimit: 6,- recallScoreThreshold: 0.35,- recallMinQueryLength: 3,- profileBudget: 10000,- resumeContextBudget: 2000,- indexBudget: 2000,+ scoreThreshold: 0.35,+ minQueryLength: 3,+ profileTokenBudget: 10000,+ resumeContextBudget: 32000,commitTokenThreshold: 20000,- commitOnShutdown: true,+ commitKeepRecentCount: 10,captureToolResults: false,captureMode: "semantic",captureMaxLength: 24000,+ captureToolMaxChars: 2000,captureAssistantTurns: true,- mirrorMemoryWrites: true,- writeQueueFlushInterval: 5000,- writeQueueFlushThreshold: 5,bypassPatterns: [],logLevel: "error",};export function loadConfig(extensionDir: string): OVConfig {const configPath = join(extensionDir, "config.json");- if (!existsSync(configPath)) return { ...DEFAULT_CONFIG };-+ let file: any = {};try {- const file = JSON.parse(readFileSync(configPath, "utf8"));- return { ...DEFAULT_CONFIG, ...file };+ if (existsSync(configPath)) file = JSON.parse(readFileSync(configPath, "utf8"));} catch {- return { ...DEFAULT_CONFIG };+ file = {};}++ const creds = resolveOpenVikingCredentials();+ const config: OVConfig = {+ ...DEFAULT_CONFIG,+ ...file,+ endpoint: creds.baseUrl,+ apiKey: creds.apiKey,+ account: creds.account,+ user: creds.user,+ peerId: creds.peerId,+ recallTokenBudget: file.recallTokenBudget ?? file.recallBudget ?? DEFAULT_CONFIG.recallTokenBudget,+ scoreThreshold: file.scoreThreshold ?? file.recallScoreThreshold ?? DEFAULT_CONFIG.scoreThreshold,+ minQueryLength: file.minQueryLength ?? file.recallMinQueryLength ?? DEFAULT_CONFIG.minQueryLength,+ profileTokenBudget: file.profileTokenBudget ?? file.profileBudget ?? DEFAULT_CONFIG.profileTokenBudget,+ };++ if (process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL) config.endpoint = creds.baseUrl;+ if (process.env.OPENVIKING_API_KEY || process.env.OPENVIKING_BEARER_TOKEN) config.apiKey = creds.apiKey;+ if (process.env.OPENVIKING_ACCOUNT) config.account = creds.account;+ if (process.env.OPENVIKING_USER) config.user = creds.user;+ if (process.env.OPENVIKING_PEER_ID) config.peerId = creds.peerId;++ config.recallLimit = clampInt(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);+ config.recallMaxContentChars = clampInt(config.recallMaxContentChars, 100, 5000, DEFAULT_CONFIG.recallMaxContentChars);+ config.recallTokenBudget = clampInt(config.recallTokenBudget, 200, 50000, DEFAULT_CONFIG.recallTokenBudget);+ config.scoreThreshold = clampNumber(config.scoreThreshold, 0, 1, DEFAULT_CONFIG.scoreThreshold);+ config.minQueryLength = clampInt(config.minQueryLength, 1, 64, DEFAULT_CONFIG.minQueryLength);+ config.profileTokenBudget = clampInt(config.profileTokenBudget, 500, 50000, DEFAULT_CONFIG.profileTokenBudget);+ config.resumeContextBudget = clampInt(config.resumeContextBudget, 1024, 128000, DEFAULT_CONFIG.resumeContextBudget);+ config.commitTokenThreshold = clampInt(config.commitTokenThreshold, 1000, 1000000, DEFAULT_CONFIG.commitTokenThreshold);+ config.commitKeepRecentCount = clampInt(config.commitKeepRecentCount, 0, 1000, DEFAULT_CONFIG.commitKeepRecentCount);+ config.captureMaxLength = clampInt(config.captureMaxLength, 200, 100000, DEFAULT_CONFIG.captureMaxLength);+ config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 20000, DEFAULT_CONFIG.captureToolMaxChars);+ config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";+ if (!Array.isArray(config.bypassPatterns)) config.bypassPatterns = [];+ return config;+}++function clampInt(value: unknown, min: number, max: number, fallback: number): number {+ const next = Math.round(Number(value));+ if (!Number.isFinite(next)) return fallback;+ return Math.max(min, Math.min(max, next));+}++function clampNumber(value: unknown, min: number, max: number, fallback: number): number {+ const next = Number(value);+ if (!Number.isFinite(next)) return fallback;+ return Math.max(min, Math.min(max, next));}diff --git a/examples/pi-coding-agent-extension/index-builder.ts b/examples/pi-coding-agent-extension/index-builder.tsdeleted file mode 100644index f18d028bf..000000000--- a/examples/pi-coding-agent-extension/index-builder.ts+++ /dev/null@@ -1,80 +0,0 @@-import type { OVClient } from "./client.js";-import type { OVConfig } from "./config.js";--export class IndexBuilder {- private client: OVClient;- private config: OVConfig;- private cachedIndex = "";-- constructor(client: OVClient, config: OVConfig) {- this.client = client;- this.config = config;- }-- async buildIndex(): Promise<string> {- if (!this.client.connected) return "";-- const sections: string[] = ["## OpenViking Knowledge Index"];-- try {- // 1. User memories- const memUri = await this.client.resolveTargetUri("viking://user/memories");- const memEntries = await this.client.ls(memUri);- const memAbstracts: string[] = [];- for (const entry of memEntries.slice(0, 20)) {- if (!entry.isDir) {- const abs = await this.client.abstract(- `${memUri}/${entry.name}`,- );- if (abs) memAbstracts.push(abs);- }- }- sections.push(`### ${memUri} (${memEntries.length} entries)`);- for (const a of memAbstracts.slice(0, 10)) {- sections.push(`- ${a}`);- }- if (memAbstracts.length > 10) {- sections.push(`- (${memAbstracts.length - 10} more — use viking_search)`);- }-- // 2. Resources- const resEntries = await this.client.ls("viking://resources/");- if (resEntries.length > 0) {- sections.push(`### viking://resources/ (${resEntries.length} resources)`);- for (const e of resEntries.slice(0, 5)) {- sections.push(`- ${e.name}`);- }- }- } catch {- // Graceful degradation — return what we have- }-- // 3. Tools advertisement- sections.push(- "Tools: viking_search | viking_read | viking_browse | viking_remember | viking_forget | viking_add_resource | viking_archive_expand",- );-- const index = sections.join("\n");-- // Token budget enforcement- let tokens = 0;- let cjk = 0;- for (let i = 0; i < index.length; i++) {- if (index.charCodeAt(i) >= 0x3000) cjk++;- }- tokens = Math.ceil(cjk * 1.5 + (index.length - cjk) / 4);-- if (tokens > this.config.indexBudget) {- // Truncate to fit- this.cachedIndex = index.slice(0, this.config.indexBudget * 3);- } else {- this.cachedIndex = index;- }-- return this.cachedIndex;- }-- getIndex(): string {- return this.cachedIndex;- }-}diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex a438210f7..408b99686 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -9,14 +9,14 @@* Design informed by: OpenClaw (synchronous recall), Claude Code plugin* (most mature, production-hardened), Hermes (anti-pattern: stale prefetch).*/-import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import { dirname } from "node:path";-import { readFileSync, existsSync } from "node:fs";import { loadConfig, type OVConfig } from "./config.js";import { OVClient } from "./client.js";import { RecallManager } from "./recall.js";-import { SyncManager, estimateTokens } from "./sync.js";-import { IndexBuilder } from "./index-builder.js";+import { SyncManager } from "./sync.js";+import { buildProfileBlock } from "./shared/profile-inject.mjs";+import { guardVikingUriToolCall } from "./lib/uri-guard-adapter.mjs";import { registerTools } from "./tools.js";export default async function (pi: ExtensionAPI) {@@ -25,17 +25,11 @@ export default async function (pi: ExtensionAPI) {if (!config.enabled) return;// Env overrides- if (process.env.OPENVIKING_URL) config.endpoint = process.env.OPENVIKING_URL;- if (process.env.OPENVIKING_API_KEY) config.apiKey = process.env.OPENVIKING_API_KEY;- if (process.env.OPENVIKING_ACCOUNT) config.account = process.env.OPENVIKING_ACCOUNT;- if (process.env.OPENVIKING_USER) config.user = process.env.OPENVIKING_USER;- if (process.env.OPENVIKING_AGENT_ID) config.agentId = process.env.OPENVIKING_AGENT_ID;// --- Initialize modules ---const client = new OVClient(config);const recall = new RecallManager(client, config);const sync = new SyncManager(client, config);- const indexBuilder = new IndexBuilder(client, config);// Session statelet connected = false;@@ -43,6 +37,7 @@ export default async function (pi: ExtensionAPI) {let profileBlock = "";let archiveOverview = "";let toolsRegistered = false;+ let compacted = false;// ================================================================// Event Handlers@@ -77,21 +72,20 @@ export default async function (pi: ExtensionAPI) {}return;}+ await sync.replayPending();// Profile injection- profileBlock = await buildProfileBlock(client, config);+ profileBlock = await buildSessionProfileBlock(client, config);// Resume rehydration — fetch archive overview if session was previously committedif (sync.sessionId) {archiveOverview = await fetchArchiveOverview(client, sync.sessionId, config);}- // Build memory index- await indexBuilder.buildIndex();-// Register tools (also re-registered in before_agent_start for pi -c continuations)registerTools(pi, client, sync);toolsRegistered = true;+ updateStatus(ctx, connected, 0, sync.sessionId, config);if (config.logLevel === "info") {ctx.ui.notify(`OpenViking connected (${piSessionId.slice(0, 8)}...)`, "info");@@ -114,10 +108,8 @@ export default async function (pi: ExtensionAPI) {// Compose system prompt additionsconst parts: string[] = [];if (profileBlock) parts.push(profileBlock);- if (archiveOverview) parts.push(archiveOverview);-- const idx = indexBuilder.getIndex();- if (idx) parts.push(idx);+ if (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.");const additions = parts.join("\n\n");if (!additions) return;@@ -134,65 +126,28 @@ export default async function (pi: ExtensionAPI) {return { messages };});+ // --- tool_call ---+ pi.on("tool_call", async (event, _ctx) => {+ const decision = guardVikingUriToolCall(event);+ if (!decision) return;+ return decision;+ });+// --- turn_end ---pi.on("turn_end", async (event, ctx) => {if (!connected || bypassed || !config.syncTurns) return;- // Extract user message from session entriesconst branch = ctx.sessionManager.getBranch();- let userText = "";- for (let i = branch.length - 1; i >= 0; i--) {- const entry = branch[i];- if (entry.type === "message" && (entry as any).message?.role === "user") {- const msg = (entry as any).message;- userText = typeof msg.content === "string"- ? msg.content- : Array.isArray(msg.content)- ? msg.content- .filter((b: any) => b.type === "text")- .map((b: any) => b.text)- .join("")- : "";- break;- }- }-- // Extract assistant text- const assistantMsg = event.message as any;- let assistantText = "";- const toolLines: string[] = [];- const toolNames: string[] = [];-- if (assistantMsg?.content && Array.isArray(assistantMsg.content)) {- for (const block of assistantMsg.content) {- if (block.type === "text") {- assistantText += block.text + "\n";- } else if (block.type === "toolCall") {- toolNames.push(block.name);- toolLines.push(- `[tool: ${block.name}]\n${JSON.stringify(block.arguments)}`,- );- }- }- }-- // Add tool summary line- if (toolNames.length > 0) {- assistantText = `[assistant used tools: ${toolNames.join(", ")}]\n` + assistantText;- }-- await sync.syncTurn(- userText, assistantText, toolLines, event.turnIndex,- );+ const added = await sync.syncBranch(branch);+ updateStatus(ctx, connected, added, sync.sessionId, config);});// --- session_before_compact ---pi.on("session_before_compact", async (_event, _ctx) => {if (!connected || bypassed) return;- // Flush write queue + synchronous commit- await sync.shutdown();- const archiveId = await sync.commit(true);+ const archiveId = await sync.commit();+ compacted = true;// Cache archive overview for rehydration after compactionif (archiveId && sync.sessionId) {@@ -208,29 +163,7 @@ export default async function (pi: ExtensionAPI) {if (!connected || bypassed) return;await sync.shutdown();-- // Mirror MEMORY.md- if (config.mirrorMemoryWrites && sync.sessionId) {- const memoryPath = `${ctx.cwd}/.memory/MEMORY.md`;- if (existsSync(memoryPath)) {- try {- const content = readFileSync(memoryPath, "utf8");- if (content.trim()) {- await client.addMessage(- sync.sessionId, "user",- `[Memory mirror]\n${content.slice(0, 50000)}`,- );- }- } catch {- // Best effort- }- }- }-- // Final commit- if (config.commitOnShutdown) {- await sync.commit(true);- }+ await sync.commit();});// --- agent_end ---@@ -252,9 +185,8 @@ export default async function (pi: ExtensionAPI) {if (args?.trim() === "commit") {await sync.shutdown();- const result = await sync.commit(true);+ const result = await sync.commit();if (result) {- await indexBuilder.buildIndex();ctx.ui.notify("OpenViking: committed successfully", "info");} else {ctx.ui.notify("OpenViking: commit failed", "error");@@ -288,63 +220,21 @@ function matchBypass(cwd: string, pattern: string): boolean {}/** Build the <openviking-context> profile block. */-async function buildProfileBlock(+async function buildSessionProfileBlock(client: OVClient, config: OVConfig,): Promise<string> {try {- const memUri = await client.resolveTargetUri("viking://user/memories");- const entries = await client.ls(memUri);-- // Look for profile.md- const profileEntry = entries.find(e => e.name === "profile.md");- let profileText = "";- if (profileEntry) {- const content = await client.readContent(`${memUri}/profile.md`);- if (content) {- // Profile elision: keep head (8 lines) + tail (fits budget)- const lines = content.split("\n");- if (lines.length > 20) {- const head = lines.slice(0, 8).join("\n");- const tailBudget = config.profileBudget - 200;- const tail = lines.slice(-Math.max(10, tailBudget)).join("\n");- profileText = head + "\n...\n" + tail;- } else {- profileText = content;- }- }- }-- // List preferences and entities directories- const prefUri = `${memUri}/preferences`;- const entUri = `${memUri}/entities`;- const [prefs, ents] = await Promise.all([- client.ls(prefUri),- client.ls(entUri),- ]);-- const sections: string[] = ["<openviking-context>"];- if (profileText) {- sections.push(`<user-profile>${profileText}</user-profile>`);- }- if (prefs.length > 0 || ents.length > 0) {- sections.push("<available-memories>");- if (prefs.length > 0) {- sections.push(` ${prefUri}/ (${prefs.length} entries)`);- }- if (ents.length > 0) {- sections.push(` ${entUri}/ (${ents.length} entries)`);- }- sections.push("</available-memories>");- }- sections.push("</openviking-context>");-- const block = sections.join("\n");- // Budget check- const tokens = estimateTokens(block);- if (tokens > config.profileBudget) {- return block.slice(0, config.profileBudget * 3);- }- return block;+ const profile = await buildProfileBlock(+ (path: string, init?: any, options?: any) => client.fetchJSON(path, init, 10000),+ config.profileTokenBudget,+ config.peerId,+ );+ if (!profile?.block) return "";+ return [+ '<openviking-context source="session-start">',+ profile.block,+ "</openviking-context>",+ ].join("\n");} catch {return "";}@@ -358,13 +248,25 @@ async function fetchArchiveOverview(const ctx = await client.getSessionContext(sessionId, config.resumeContextBudget);if (!ctx || !ctx.latest_archive_overview) return "";- const result = `[Session History Summary]\n${ctx.latest_archive_overview}`;- const tokens = estimateTokens(result);- if (tokens > config.resumeContextBudget) {- return result.slice(0, config.resumeContextBudget * 3);- }- return result;+ return [+ '<openviking-context source="session-archive">',+ "<session-archive>",+ ctx.latest_archive_overview,+ "</session-archive>",+ "</openviking-context>",+ ].join("\n");} catch {return "";}}++function updateStatus(ctx: any, connected: boolean, added: number, sessionId: string | null, config: OVConfig): void {+ const setter = ctx?.ui?.setStatus;+ if (typeof setter !== "function") return;+ const status = `${connected ? "OV ✓" : "OV ✗"} · ↩${added} · ✎ ${config.commitTokenThreshold} · ${sessionId ? sessionId.slice(0, 12) : "none"}`;+ try {+ setter(status);+ } catch {+ // Best effort; pi API shape may vary across fast-moving versions.+ }+}diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts b/examples/pi-coding-agent-extension/lib/capture-adapter.d.mtsnew file mode 100644index 000000000..b502604de--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts@@ -0,0 +1,10 @@+export function extractBranchCapturePayloads(+ branch: any[],+ syncedEntryCount?: number,+ cfg?: Record<string, any>,+): {+ payloads: any[];+ nextEntryCount: number;+ observedEntryCount: number;+ resetWatermark: boolean;+};diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs b/examples/pi-coding-agent-extension/lib/capture-adapter.mjsnew file mode 100644index 000000000..9abea11b5--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs@@ -0,0 +1,58 @@+import {+ extractPartsFromPayload,+ extractTextFromPayload,+ shouldCaptureText,+} from "../shared/capture-utils.mjs";++function normalizeRole(role) {+ const value = String(role || "").toLowerCase();+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result") return "user";+ if (value === "tool_call" || value === "toolcall") return "assistant";+ return "";+}++function entryPayload(entry) {+ if (!entry || typeof entry !== "object") return null;+ if (entry.type === "message" && entry.message && typeof entry.message === "object") {+ return entry.message;+ }+ if (entry.message && typeof entry.message === "object") return entry.message;+ return entry;+}++export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg = {}) {+ const entries = Array.isArray(branch) ? branch : [];+ const previousCount = Math.max(0, Number(syncedEntryCount) || 0);+ const resetWatermark = entries.length < previousCount;+ const start = resetWatermark ? 0 : Math.min(previousCount, entries.length);+ const payloads = [];++ for (const entry of entries.slice(start)) {+ const payload = entryPayload(entry);+ if (!payload) continue;++ const role = normalizeRole(payload.role || payload.type || payload.kind);+ if (!role) continue;+ if (role === "assistant" && cfg.captureAssistantTurns === false) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;++ const body = parts.length > 0+ ? { role, parts }+ : { role, content: decision.text };+ if (cfg.peerId) body.peer_id = cfg.peerId;+ payloads.push(body);+ }++ return {+ payloads,+ nextEntryCount: entries.length,+ observedEntryCount: entries.length,+ resetWatermark,+ };+}diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mts b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mtsnew file mode 100644index 000000000..f19a7b460--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.d.mts@@ -0,0 +1 @@+export function guardVikingUriToolCall(event: any): { block: true; reason: string } | null;diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjsnew file mode 100644index 000000000..e1bd58c36--- /dev/null+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs@@ -0,0 +1,42 @@+import { buildGuardMessage, findVikingUri, normalizeToolName } from "../shared/uri-guard.mjs";++const VIKING_URI_TOOL_HINTS = {+ read: {+ tool: "viking_read",+ example: (uri) => `viking_read(uri="${uri}", level="overview")`,+ },+ grep: {+ tool: "viking_search",+ example: (uri, input = {}) => `viking_search(query="${String(input.pattern ?? "").replaceAll('"', '\\"')}", scope="${uri}")`,+ },+ find: {+ tool: "viking_browse",+ example: (uri) => `viking_browse(action="list", uri="${uri}")`,+ },+ ls: {+ tool: "viking_browse",+ example: (uri) => `viking_browse(action="list", uri="${uri}")`,+ },+ bash: {+ tool: "viking_read or viking_search",+ example: (uri) => `viking_read(uri="${uri}", level="overview")`,+ },+};++export function guardVikingUriToolCall(event) {+ const toolName = normalizeToolName(event?.toolName ?? event?.tool_name ?? event?.name);+ const hint = VIKING_URI_TOOL_HINTS[toolName];+ if (!hint) return null;++ const input = event?.input ?? event?.args ?? event?.params ?? {};+ const uri = findVikingUri(input);+ if (!uri) return null;++ return {+ block: true,+ reason: buildGuardMessage(uri, {+ tool: hint.tool,+ example: hint.example(uri, input),+ }),+ };+}diff --git a/examples/pi-coding-agent-extension/recall.ts b/examples/pi-coding-agent-extension/recall.tsindex b7ff185bf..bf76fc99e 100644--- a/examples/pi-coding-agent-extension/recall.ts+++ b/examples/pi-coding-agent-extension/recall.ts@@ -1,42 +1,12 @@-import type { OVClient, OVSearchResult } from "./client.js";+import type { OVClient } from "./client.js";import type { OVConfig } from "./config.js";--export interface QueryProfile {- tokens: string[]; // content words minus stopwords- wantsPreference: boolean;- wantsTemporal: boolean;-}--export interface RankedResult {- uri: string;- score: number; // base + boosts- abstract: string;- content: string | null; // resolved content, capped- category: string;- level: number;-}+import { buildRecallBlock } from "./shared/recall-core.mjs";export interface RecallCache {- block: string | null; // formatted <relevant-memories> text+ block: string | null;promptText: string; // the query this cache is for}-// Stopwords for query profiling-const STOPWORDS = new Set([- "the", "a", "an", "is", "are", "was", "were", "be", "been", "being",- "have", "has", "had", "do", "does", "did", "will", "would", "could",- "should", "may", "might", "can", "shall", "to", "of", "in", "for",- "on", "with", "at", "by", "from", "as", "into", "through", "during",- "before", "after", "above", "below", "between", "out", "off", "over",- "under", "again", "further", "then", "once", "and", "but", "or",- "nor", "not", "so", "yet", "both", "either", "neither", "each",- "every", "all", "any", "few", "more", "most", "other", "some",- "such", "no", "only", "own", "same", "than", "too", "very",- "just", "because", "if", "when", "where", "how", "what", "which",- "who", "whom", "this", "that", "these", "those", "i", "me", "my",- "it", "its", "we", "you", "they", "them", "there", "here",-]);-export class RecallManager {private client: OVClient;private config: OVConfig;@@ -47,87 +17,17 @@ export class RecallManager {this.config = config;}- // --- CJK-aware Token Estimation ----- estimateTokens(text: string): number {- if (!text) return 0;- let cjk = 0;- for (let i = 0; i < text.length; i++) {- if (text.charCodeAt(i) >= 0x3000) cjk++;- }- const other = text.length - cjk;- return Math.ceil(cjk * 1.5 + other / 4);- }-- // --- Query Profiling ----- private profileQuery(query: string): QueryProfile {- const words = query.toLowerCase()- .replace(/[^\w\s]/g, " ")- .split(/\s+/)- .filter(w => w.length > 1 && !STOPWORDS.has(w));-- return {- tokens: words,- wantsPreference: /prefer|favorite|like|want|usually|always|never|hate|love/i.test(query),- wantsTemporal: /when|yesterday|last |recent|ago|last week|earlier|before/i.test(query),- };- }-- // --- Triple-Scope Search ----async searchAndCache(userQuery: string): Promise<string | null> {- // Short-circuit on short queries- if (userQuery.trim().length < this.config.recallMinQueryLength) {+ if (userQuery.trim().length < this.config.minQueryLength) {return null;}- const profile = this.profileQuery(userQuery);- const perSourceLimit = Math.max(this.config.recallLimit * 2, 8);-- // Resolve URIs dynamically- const [userMemUri, agentMemUri, agentSkillsUri] = await Promise.all([- this.client.resolveTargetUri("viking://user/memories"),- this.client.resolveTargetUri("viking://agent/memories"),- this.client.resolveTargetUri("viking://agent/skills"),- ]);-- // Triple-scope parallel search- const [userResults, agentResults, skillResults] = await Promise.all([- this.client.find(userQuery, {- targetUri: userMemUri, topK: perSourceLimit,- scoreThreshold: this.config.recallScoreThreshold,- }),- this.client.find(userQuery, {- targetUri: agentMemUri, topK: perSourceLimit,- scoreThreshold: this.config.recallScoreThreshold,- }),- this.client.find(userQuery, {- targetUri: agentSkillsUri, topK: perSourceLimit,- scoreThreshold: this.config.recallScoreThreshold,- }),- ]);-- // Merge all results- const all = [...userResults, ...agentResults, ...skillResults];-- // Score filter (client-side, in case server doesn't enforce)- const filtered = all.filter(- r => r.score >= this.config.recallScoreThreshold+ const block = await buildRecallBlock(+ (path: string, init?: any, options?: any) => this.client.fetchJSON(path, init, 10000),+ this.config as any,+ userQuery,+ { actorPeerId: this.config.peerId },);- if (filtered.length === 0) return null;-- // Dedup- const deduped = this.dedup(filtered);-- // Rerank with query profile- const ranked = this.rerank(deduped, profile);-- // Content resolution with per-item cap- const resolved = await this.resolveContent(ranked);-- // Token-budgeted formatting with graceful degradation- const block = this.formatResults(resolved);this.cache = { block, promptText: userQuery };return block;}@@ -148,7 +48,7 @@ export class RecallManager {? msg.content.filter((b: any) => b.type === "text").map((b: any) => b.text).join(""): "";- if (content.includes("<relevant-memories>")) break;+ if (content.includes("<openviking-context")) break;// Prepend block to user messageconst block = this.cache.block;@@ -169,127 +69,4 @@ export class RecallManager {invalidate(): void {this.cache = { block: null, promptText: "" };}-- // --- Dedup ----- private dedup(results: OVSearchResult[]): OVSearchResult[] {- const seen = new Map<string, OVSearchResult>();-- for (const r of results) {- // Events/cases dedupe by URI; others by abstract text- const isEvent = r.category === "event" || r.category === "case";- const key = isEvent- ? r.uri- : (r.abstract?.toLowerCase().trim() || r.uri);-- if (!seen.has(key)) {- seen.set(key, r);- } else {- // Keep higher score- const existing = seen.get(key)!;- if (r.score > existing.score) seen.set(key, r);- }- }- return [...seen.values()];- }-- // --- Reranking ----- private rerank(- results: OVSearchResult[], profile: QueryProfile,- ): OVSearchResult[] {- return results.map(r => {- let score = r.score;-- // Leaf preference boost- if ((r.level === 2) || r.uri.endsWith(".md")) {- score += 0.12;- }-- // Event boost (gated by temporal intent)- if (profile.wantsTemporal &&- (r.category === "event" || r.category === "case")) {- score += 0.10;- }-- // Preference boost (gated by preference intent)- if (profile.wantsPreference && r.category === "preference") {- score += 0.08;- }-- // Lexical overlap boost- const text = `${r.uri} ${r.abstract}`.toLowerCase();- const matchCount = profile.tokens- .slice(0, 4)- .filter(t => text.includes(t)).length;- score += 0.20 * (matchCount / Math.max(profile.tokens.length, 1));-- return { ...r, score };- }).sort((a, b) => b.score - a.score)- .slice(0, this.config.recallLimit);- }-- // --- Content Resolution ----- private async resolveContent(- results: OVSearchResult[],- ): Promise<RankedResult[]> {- const resolved: RankedResult[] = [];-- for (const r of results) {- let content: string | null = r.abstract ?? null;-- if (!this.config.recallPreferAbstract && r.level === 2) {- // Fetch full content for level-2 items when abstracts not preferred- const full = await this.client.readContent(r.uri);- if (full) content = full;- }-- // Per-item content cap- if (content && content.length > this.config.recallMaxContentChars) {- content = content.slice(0, this.config.recallMaxContentChars) + "...";- }-- resolved.push({- uri: r.uri,- score: r.score,- abstract: r.abstract ?? "",- content,- category: r.category ?? "unknown",- level: r.level ?? 0,- });- }- return resolved;- }-- // --- Formatting with Graceful Degradation ----- private formatResults(results: RankedResult[]): string {- const lines: string[] = [- "<relevant-memories>",- "[System note: Recalled memory from OpenViking. Informational background data, NOT new user input.]",- ];-- let budget = this.config.recallBudget;- let first = true;-- for (const r of results) {- const tokens = this.estimateTokens(r.content ?? r.abstract);-- if (first || tokens <= budget) {- // Full content line- const source = r.uri.includes("/skills/") ? "skill" : "memory";- const text = r.content ?? r.abstract;- lines.push(`- [${source} ${r.score.toFixed(2)}] ${text}`);- budget -= tokens;- } else {- // Degraded hint — model can expand with viking_read- lines.push(`- [hint ${r.score.toFixed(2)}] Use viking_read to expand: ${r.uri}`);- }- first = false;- }-- lines.push("</relevant-memories>");- return lines.join("\n");- }}diff --git a/examples/pi-coding-agent-extension/scripts/setup.mjs b/examples/pi-coding-agent-extension/scripts/setup.mjsnew file mode 100644index 000000000..dcd93a30e--- /dev/null+++ b/examples/pi-coding-agent-extension/scripts/setup.mjs@@ -0,0 +1,8 @@+#!/usr/bin/env node++import { runSetupWizard } from "../shared/setup-wizard.mjs";++runSetupWizard().catch((err) => {+ process.stderr.write(`${err?.stack || err}\n`);+ process.exit(1);+});diff --git a/examples/pi-coding-agent-extension/shared/capture-utils.d.mts b/examples/pi-coding-agent-extension/shared/capture-utils.d.mtsnew file mode 100644index 000000000..70c40abd3--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/capture-utils.d.mts@@ -0,0 +1,9 @@+export function extractPartsFromPayload(payload: any, options?: Record<string, any>): any[];+export function extractTextFromPayload(payload: any, options?: Record<string, any>): string;+export function shouldCaptureText(text: string, role: string, cfg?: Record<string, any>): {+ shouldCapture: boolean;+ reason: string;+ text: string;+};+export function sanitizeCapturedText(text: string): string;+export function truncateCaptureText(text: string, maxChars?: number): string;diff --git a/examples/pi-coding-agent-extension/shared/capture-utils.mjs b/examples/pi-coding-agent-extension/shared/capture-utils.mjsnew file mode 100644index 000000000..3a1fb1fec--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/capture-utils.mjs@@ -0,0 +1,500 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function parseMaybeJson(value) {+ if (value == null || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function toolId(block) {+ return oneLine(+ block?.id ||+ block?.call_id ||+ block?.callId ||+ block?.tool_call_id ||+ block?.toolCallId ||+ block?.tool_use_id ||+ block?.toolUseId ||+ block?.function_call_id ||+ block?.functionCallId ||+ "",+ );+}++function toolStatus(block, kind) {+ if (kind === "call") return "running";+ if (block?.is_error || block?.error) return "error";+ const status = oneLine(block?.status || "");+ return status || "completed";+}++function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {+ const id = toolId(block);+ const name = toolName(block) || (id ? toolNameById[id] : "");+ const payload = toolPayload(block, kind);+ const part = {+ type: "tool",+ tool_id: id || undefined,+ tool_name: name || undefined,+ tool_status: toolStatus(block, kind),+ };+ if (kind === "call") {+ const input = parseMaybeJson(payload);+ if (input !== "" && input != null) {+ part.tool_input = typeof input === "object" && !Array.isArray(input)+ ? input+ : { value: input };+ }+ } else {+ part.tool_output = stringifyCompact(payload, toolMaxChars);+ }+ return part;+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++function collectToolNamesByIdFromEntries(entries) {+ const map = {};+ for (const entry of entries || []) {+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;+ collectToolNamesByIdFromPayload(payload, map);+ }+ return map;+}++function collectToolNamesByIdFromPayload(payload, out) {+ if (!payload || typeof payload !== "object") return;+ if (payload.message && typeof payload.message === "object") {+ collectToolNamesByIdFromPayload(payload.message, out);+ }+ const candidates = [];+ if (Array.isArray(payload.content)) candidates.push(...payload.content);+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) candidates.push(...value);+ else candidates.push(value);+ }+ if (isToolCallBlock(payload)) candidates.push(payload);+ for (const block of candidates) {+ if (!block || typeof block !== "object") continue;+ if (!isToolCallBlock(block)) continue;+ const id = toolId(block);+ const name = toolName(block);+ if (id && name) out[id] = name;+ }+}++function extractPartsFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ const parts = [];+ if (!content) return parts;+ if (typeof content === "string") {+ if (content.trim()) parts.push({ type: "text", text: content });+ return parts;+ }+ if (!Array.isArray(content)) {+ const text = blockToText(content, opts);+ if (text.trim()) parts.push({ type: "text", text });+ return parts;+ }+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ if (isToolCallBlock(block)) {+ parts.push(buildToolPart(block, "call", opts));+ } else if (isToolResultBlock(block)) {+ parts.push(buildToolPart(block, "result", opts));+ } else {+ const text = blockToText(block, opts);+ if (text.trim()) parts.push({ type: "text", text });+ }+ }+ return parts;+}++export function extractPartsFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return [];+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };+ if (payload.message && typeof payload.message === "object") {+ return extractPartsFromPayload(payload.message, opts);+ }++ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {+ return [buildToolPart(payload, "call", opts)];+ }+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {+ return [buildToolPart(payload, "result", opts)];+ }++ const parts = [];+ if (payload.content !== undefined) {+ parts.push(...extractPartsFromContent(payload.content, opts));+ }+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ if (Array.isArray(value)) {+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));+ } else {+ parts.push(...extractPartsFromPayload(value, opts));+ }+ }+ return parts;+}++export function extractCaptureTurns(rolloutEntries, cfg = {}) {+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);+ const turns = [];+ for (const entry of rolloutEntries || []) {+ if (!entry || typeof entry !== "object") continue;+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const parts = extractPartsFromPayload(payload, {+ toolMaxChars: cfg.captureToolMaxChars,+ toolNameById,+ });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture && parts.length === 0) continue;+ const text = decision.shouldCapture ? decision.text : "";+ turns.push({ role, text, parts });+ }+ return turns;+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/pi-coding-agent-extension/shared/credentials.d.mts b/examples/pi-coding-agent-extension/shared/credentials.d.mtsnew file mode 100644index 000000000..de6225f42--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/credentials.d.mts@@ -0,0 +1,10 @@+export function resolveOpenVikingCredentials(env?: Record<string, string | undefined>): {+ credentialSource: string;+ baseUrl: string;+ mcpUrl: string;+ apiKey: string;+ account: string;+ user: string;+ peerId: string;+ hasApiKey: boolean;+};diff --git a/examples/pi-coding-agent-extension/shared/credentials.mjs b/examples/pi-coding-agent-extension/shared/credentials.mjsnew file mode 100644index 000000000..76b30fb8e--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/credentials.mjs@@ -0,0 +1,207 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";++const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";++function str(val, fallback = "") {+ if (typeof val === "string" && val.trim()) return val.trim();+ return fallback;+}++function normalizePath(value) {+ const raw = str(value, "");+ if (!raw) return "";+ if (raw === "~") return homedir();+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));+ return resolvePath(raw);+}++function tryLoadJson(path) {+ if (!path) return null;+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return null;+ }+}++function looksLikeOvcli(obj) {+ if (!obj || typeof obj !== "object") return false;+ if (obj.server && typeof obj.server === "object") return false;+ return Boolean(+ typeof obj.url === "string" ||+ typeof obj.api_key === "string" ||+ typeof obj.account === "string" ||+ typeof obj.account_id === "string" ||+ typeof obj.user === "string" ||+ typeof obj.user_id === "string" ||+ typeof obj.actor_peer_id === "string",+ );+}++function hasCredentialFields(obj) {+ if (!obj || typeof obj !== "object") return false;+ return [+ "url",+ "api_key",+ "account",+ "account_id",+ "user",+ "user_id",+ "actor_peer_id",+ "peer_id",+ ].some((key) => typeof obj[key] === "string");+}++export function loadCredentialFiles(env = process.env) {+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));++ let cliFile = tryLoadJson(cliPathCandidate);+ let cliPath = cliFile ? cliPathCandidate : "";+ let ovFile = tryLoadJson(ovPathCandidate);+ let ovPath = ovFile ? ovPathCandidate : "";++ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {+ cliFile = ovFile;+ cliPath = ovPath;+ ovFile = null;+ ovPath = "";+ }++ return {+ cliFile: cliFile || {},+ cliPath,+ cliPathCandidate,+ ovFile: ovFile || {},+ ovPath,+ };+}++function sourceMode(env) {+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))+ .toLowerCase();+ if (raw === "env" || raw === "environment") return "env";+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";+ return "auto";+}++function hasEnvCredentialFields(env) {+ return Boolean(+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||+ str(env.OPENVIKING_MCP_URL, "") ||+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(env.OPENVIKING_USER, "") ||+ str(env.OPENVIKING_PEER_ID, ""),+ );+}++function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");+ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");++ const server = ovFile.server || {};+ const ovUrl = str(server.url, "");+ if (ovUrl) return ovUrl.replace(/\/+$/, "");++ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;+ return `http://${host}:${port}`;+}++export function resolveOpenVikingCredentials(env = process.env) {+ const files = loadCredentialFiles(env);+ const mode = sourceMode(env);+ const envHasCredentials = hasEnvCredentialFields(env);+ const useCli = mode === "cli" ||+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });++ const apiKey = useCli+ ? str(files.cliFile.api_key, "")+ : (+ str(env.OPENVIKING_BEARER_TOKEN, "") ||+ str(env.OPENVIKING_API_KEY, "") ||+ str(files.cliFile.api_key, "") ||+ str(cx.apiKey, "") ||+ str(server.root_api_key, "")+ );++ const account = useCli+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))+ : (+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||+ str(cx.accountId, "")+ );++ const user = useCli+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))+ : (+ str(env.OPENVIKING_USER, "") ||+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||+ str(cx.userId, "")+ );++ const peerId = useCli+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))+ : (+ str(env.OPENVIKING_PEER_ID, "") ||+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||+ str(cx.peerId, str(cx.peer_id, ""))+ );++ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),+ baseUrl,+ mcpUrl,+ apiKey,+ account,+ user,+ peerId,+ hasApiKey: Boolean(apiKey),+ };+}++function main() {+ const cmd = process.argv[2] || "";+ if (cmd === "mcp-url") {+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);+ return;+ }+ if (cmd === "has-api-key") {+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");+ return;+ }+ if (cmd === "has-peer-id") {+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");+ return;+ }+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");+ process.exitCode = 2;+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {+ main();+}diff --git a/examples/pi-coding-agent-extension/shared/debug-log.mjs b/examples/pi-coding-agent-extension/shared/debug-log.mjsnew file mode 100644index 000000000..73855cf6d--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/debug-log.mjs@@ -0,0 +1,58 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared structured debug logger for OpenViking memory plugin hook scripts.+ *+ * Harness-specific wrappers load config and pass {debug, debugLogPath}. This+ * module stays path-agnostic so it can be vendored into each plugin snapshot.+ */++import { appendFileSync, mkdirSync } from "node:fs";+import { dirname } from "node:path";++function ensureDir(filePath) {+ try {+ mkdirSync(dirname(filePath), { recursive: true });+ } catch { /* best effort */ }+}++function writeLine(filePath, obj) {+ try {+ appendFileSync(filePath, JSON.stringify(obj) + "\n");+ } catch { /* best effort */ }+}++function localISO() {+ const d = new Date();+ const off = d.getTimezoneOffset();+ const sign = off <= 0 ? "+" : "-";+ const abs = Math.abs(off);+ const local = new Date(d.getTime() - off * 60000);+ return local.toISOString().replace(+ "Z",+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`,+ );+}++const noop = () => {};++export function createLogger(hookName, overrideCfg) {+ const c = overrideCfg || {};+ if (!c.debug) return { log: noop, logError: noop };++ const logPath = c.debugLogPath;+ if (!logPath) return { log: noop, logError: noop };+ ensureDir(logPath);++ function log(stage, data) {+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });+ }++ function logError(stage, err) {+ const error = err instanceof Error+ ? { message: err.message, stack: err.stack }+ : String(err);+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });+ }++ return { log, logError };+}diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.d.mts b/examples/pi-coding-agent-extension/shared/pending-queue.d.mtsnew file mode 100644index 000000000..031886190--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/pending-queue.d.mts@@ -0,0 +1,6 @@+export function enqueue(type: string, sessionId: string, payload: Record<string, any>): Promise<{ ok: boolean; path?: string; error?: string }>;+export function replayPending(+ fetchJSON: (path: string, init?: any) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>,+ log: (stage: string, data?: any) => void,+): Promise<{ replayed: number; failed: number; skipped: number; deferred: number }>;+export function cleanStale(): Promise<number>;diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.mjs b/examples/pi-coding-agent-extension/shared/pending-queue.mjsnew file mode 100644index 000000000..cbf6d445f--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/pending-queue.mjs@@ -0,0 +1,439 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Local pending queue for offline resilience.+ *+ * When the OpenViking server is temporarily unreachable, write operations+ * (addMessage, commitSession) serialize their payloads to+ * `~/.openviking/pending/` as JSON files. On the next session-start, the+ * queue is replayed in small batches. This is a session-start-triggered retry+ * path with maxRetries/TTL, not a long-running background worker.+ *+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }+ *+ * Config (env vars):+ * OPENVIKING_PENDING_DIR pending queue directory+ * (default: ~/.openviking/pending)+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup+ * (default: 7)+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start+ * (default: 50)+ */++import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join } from "node:path";+import { homedir } from "node:os";++const DEFAULT_MAX_RETRIES = 3;+const DEFAULT_TTL_DAYS = 7;+const DEFAULT_REPLAY_LIMIT = 50;+const PROCESSING_STALE_MS = 10 * 60 * 1000;+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");++// Pending queue files may contain raw memory payload / transcript content.+// Use restrictive permissions explicitly so we don't depend on umask.+// - dir: 0o700 (owner: rwx; group/other: none)+// - file: 0o600 (owner: rw; group/other: none)+const PENDING_DIR_MODE = 0o700;+const PENDING_FILE_MODE = 0o600;++/**+ * Ensure the pending directory exists with 0o700 permissions. If the+ * directory was created by a previous version of this code (or by hand)+ * with looser permissions, best-effort chmod it on first use.+ */+async function ensurePendingDir(dir) {+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });+ try {+ await chmod(dir, PENDING_DIR_MODE);+ } catch {+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.+ }+}++function getPendingDir() {+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();+}++function getMaxRetries() {+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;+}++function getTTLDays() {+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;+}++function getReplayLimit() {+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;+}++function stableStringify(value) {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;+}++function makeDedupKey(type, sessionId, payload) {+ return createHash("sha256")+ .update(type)+ .update("\n")+ .update(sessionId)+ .update("\n")+ .update(stableStringify(payload))+ .digest("hex");+}++function pendingFilename(dedupKey, retries = 0) {+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;+}++function retryFilename(filename, retries) {+ const bare = filename.replace(/\.(json|processing)$/, "");+ const nextBare = /_\d+$/.test(bare)+ ? bare.replace(/_\d+$/, `_${retries}`)+ : `${bare}_${retries}`;+ return `${nextBare}.json`;+}++function processingFilename(filename) {+ return filename.replace(/\.json$/, ".processing");+}++function pendingFromProcessingFilename(filename) {+ return filename.replace(/\.processing$/, ".json");+}++function isRetryableReplayFailure(res) {+ if (!res || res.ok) return false;+ const status = Number(res.status || 0);+ return !status || status >= 500 || status === 408 || status === 429;+}++async function readEntry(dir, filename) {+ const raw = await readFile(join(dir, filename), "utf-8");+ return JSON.parse(raw);+}++async function findExistingByDedupKey(dir, dedupKey) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return null;+ }++ // Fast path: filenames are `${dedupKey}_${retries}.json` (or+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.+ // Filter on prefix BEFORE opening the file to avoid readFile ++ // JSON.parse on every entry in the directory on every enqueue call —+ // the previous implementation was O(n²) in queue size. Worst case here+ // is O(n) readdir entries, but only the (typically single) prefix+ // match actually gets opened and parsed.+ const prefix = `${dedupKey}_`;++ for (const f of files) {+ if (!f.startsWith(prefix)) continue;+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;+ try {+ const entry = await readEntry(dir, f);+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };+ } catch {+ // Corrupted file - ignore for dedup lookup.+ }+ }+ return null;+}++async function recoverStaleProcessing(dir) {+ let files;+ try {+ files = await readdir(dir);+ } catch {+ return 0;+ }++ const now = Date.now();+ let recovered = 0;+ for (const f of files) {+ if (!f.endsWith(".processing")) continue;+ const from = join(dir, f);+ try {+ const s = await stat(from);+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;+ const to = join(dir, pendingFromProcessingFilename(f));+ await rename(from, to);+ recovered++;+ } catch {+ // Best effort. A concurrent process may have already handled it.+ }+ }+ return recovered;+}++/**+ * Enqueue a failed operation to local disk.+ *+ * @param {string} type - "addMessage" or "commitSession"+ * @param {string} sessionId - OV session ID+ * @param {object} payload - the data that failed to send+ */+export async function enqueue(type, sessionId, payload) {+ const dir = getPendingDir();+ const now = Date.now();+ const dedupKey = makeDedupKey(type, sessionId, payload);+ const filename = pendingFilename(dedupKey, 0);+ const entry = {+ type,+ sessionId,+ payload,+ createdAt: now,+ retries: 0,+ dedupKey,+ };++ try {+ await ensurePendingDir(dir);+ } catch (err) {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }++ const existing = await findExistingByDedupKey(dir, dedupKey);+ if (existing) {+ return { ok: true, path: existing.filename, deduped: true, dedupKey };+ }++ try {+ await writeFile(join(dir, filename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ return { ok: true, path: filename, dedupKey };+ } catch (err) {+ if (err?.code !== "EEXIST") {+ return { ok: false, error: err?.message || String(err), dedupKey };+ }+ }++ const duplicate = await findExistingByDedupKey(dir, dedupKey);+ if (duplicate) {+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };+ }+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };+}++/**+ * List all pending queue entries.+ * Returns array of { filename, entry } sorted by createdAt ascending.+ */+export async function listPending() {+ const dir = getPendingDir();+ let files;+ try {+ await recoverStaleProcessing(dir);+ files = await readdir(dir);+ } catch {+ return [];+ }++ const entries = [];+ for (const f of files) {+ if (!f.endsWith(".json")) continue;+ try {+ const entry = await readEntry(dir, f);+ entries.push({ filename: f, entry });+ } catch {+ // Corrupted file - skip.+ }+ }++ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));+ return entries;+}++/**+ * Atomically claim a pending file for replay. Only the process that successfully+ * renames the file may send the HTTP replay.+ */+export async function claimForReplay(filename) {+ if (!filename.endsWith(".json")) return null;+ const dir = getPendingDir();+ const claimed = processingFilename(filename);+ try {+ await rename(join(dir, filename), join(dir, claimed));+ return claimed;+ } catch {+ return null;+ }+}++/**+ * Remove a pending entry after successful replay.+ */+export async function dequeue(filename) {+ const dir = getPendingDir();+ try {+ await unlink(join(dir, filename));+ return true;+ } catch {+ return false;+ }+}++/**+ * Increment retry count on a pending entry. Returns false if max retries exceeded.+ */+export async function incrementRetry(filename, entry) {+ const dir = getPendingDir();+ const maxRetries = getMaxRetries();+ entry.retries = (entry.retries || 0) + 1;++ if (entry.retries > maxRetries) {+ try {+ await unlink(join(dir, filename));+ } catch {+ // Best effort.+ }+ return false;+ }++ const newFilename = retryFilename(filename, entry.retries);+ // Atomic write: write to a unique temp file in the same directory, then+ // rename into place. Avoids leaving a half-written JSON if the process+ // crashes mid-write.+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {+ encoding: "utf-8",+ flag: "wx",+ mode: PENDING_FILE_MODE,+ });+ await rename(join(dir, tmpFilename), join(dir, newFilename));+ await unlink(join(dir, filename)).catch(() => {});+ return true;+ } catch {+ await unlink(join(dir, tmpFilename)).catch(() => {});+ return false;+ }+}++/**+ * Clean up stale entries older than TTL.+ */+export async function cleanStale() {+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;+ const now = Date.now();+ const pending = await listPending();+ let cleaned = 0;++ for (const { filename, entry } of pending) {+ const age = now - (entry.createdAt || 0);+ if (age > ttlMs) {+ await dequeue(filename);+ cleaned++;+ }+ }+ return cleaned;+}++/**+ * Replay pending entries. Call this during session-start when the server is+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so+ * a just-recovered server is not hit with an unbounded replay burst.+ *+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON+ * @param {Function} log - logger function+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}+ */+export async function replayPending(fetchJSON, log) {+ const pending = await listPending();++ if (pending.length === 0) {+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };+ }++ const replayLimit = getReplayLimit();+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });++ let replayed = 0;+ let failed = 0;+ let skipped = 0;+ let deferred = 0;+ let processed = 0;++ for (const { filename, entry } of pending) {+ if (processed >= replayLimit) {+ deferred++;+ continue;+ }++ if ((entry.retries || 0) >= getMaxRetries()) {+ await dequeue(filename);+ skipped++;+ continue;+ }++ const claimedFilename = await claimForReplay(filename);+ if (!claimedFilename) {+ skipped++;+ continue;+ }+ processed++;++ let res;+ try {+ const encodedSid = encodeURIComponent(entry.sessionId);+ if (entry.type === "addMessage") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {+ method: "POST",+ body: JSON.stringify(entry.payload),+ });+ } else if (entry.type === "commitSession") {+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {+ method: "POST",+ body: JSON.stringify(entry.payload || {}),+ });+ } else {+ await dequeue(claimedFilename);+ skipped++;+ continue;+ }+ } catch {+ res = { ok: false };+ }++ if (res?.ok) {+ await dequeue(claimedFilename);+ replayed++;+ } else if (!isRetryableReplayFailure(res)) {+ await dequeue(claimedFilename);+ skipped++;+ } else {+ await incrementRetry(claimedFilename, entry);+ failed++;+ if (entry.type === "addMessage") {+ deferred += Math.max(0, pending.length - processed);+ break;+ }+ }+ }++ const cleaned = await cleanStale();++ log("pending-queue", {+ action: "replay-done",+ replayed,+ failed,+ skipped,+ deferred,+ cleaned,+ });++ return { replayed, failed, skipped, deferred };+}diff --git a/examples/pi-coding-agent-extension/shared/profile-inject.d.mts b/examples/pi-coding-agent-extension/shared/profile-inject.d.mtsnew file mode 100644index 000000000..e8c95ef0c--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/profile-inject.d.mts@@ -0,0 +1,17 @@+export function buildProfileBlock(+ fetchJSON: (path: string, init?: any, options?: any) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>,+ totalBudgetTokens: number,+ actorPeerId?: string,+): Promise<null | {+ block: string;+ chars: number;+ tokens: number;+ profileUri: string;+ profileChars: number;+ prefCount: number;+ entCount: number;+ droppedPref: number;+ droppedEnt: number;+}>;++export function estimateTokens(text: string): number;diff --git a/examples/pi-coding-agent-extension/shared/profile-inject.mjs b/examples/pi-coding-agent-extension/shared/profile-inject.mjsnew file mode 100644index 000000000..3f601844a--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/profile-inject.mjs@@ -0,0 +1,294 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url, {}, { actorPeerId });+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/pi-coding-agent-extension/shared/recall-core.d.mts b/examples/pi-coding-agent-extension/shared/recall-core.d.mtsnew file mode 100644index 000000000..ceaa6a496--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/recall-core.d.mts@@ -0,0 +1,9 @@+export function buildRecallBlock(+ fetchJSON: (path: string, init?: any, options?: any) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>,+ cfg: Record<string, any>,+ query: string,+ options?: { actorPeerId?: string; log?: (stage: string, data?: any) => void },+): Promise<string | null>;++export function buildRecallEndpointBody(cfg?: Record<string, any>): Record<string, any>;+export function estimateTokens(text: string): number;diff --git a/examples/pi-coding-agent-extension/shared/recall-core.mjs b/examples/pi-coding-agent-extension/shared/recall-core.mjsnew file mode 100644index 000000000..445f00b1a--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/recall-core.mjs@@ -0,0 +1,282 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },+];++let userSpaceCache = "";++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);+ return {+ query: "",+ quotas: {+ events: limit,+ entities: limit,+ preferences: Math.max(1, Math.min(limit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ if (userSpaceCache) return userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ if (items.length === 0) return null;++ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),+ });++ return lines.join("\n");+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",+ rendered,+ "</openviking-context>",+ ].join("\n");+}++export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return null;++ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);+ if (endpointBlock !== null) return endpointBlock || null;++ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return null;++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return null;+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}diff --git a/examples/pi-coding-agent-extension/shared/session-model.d.mts b/examples/pi-coding-agent-extension/shared/session-model.d.mtsnew file mode 100644index 000000000..82a340dbb--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/session-model.d.mts@@ -0,0 +1,3 @@+export function deriveHarnessSessionId(prefix: string, sessionId: string, suffix?: string): string;+export function deriveCodexSessionId(codexSessionId: string): string;+export function isBypassed(cfg: Record<string, any>, options?: { sessionId?: string; cwd?: string }): boolean;diff --git a/examples/pi-coding-agent-extension/shared/session-model.mjs b/examples/pi-coding-agent-extension/shared/session-model.mjsnew file mode 100644index 000000000..b6496a113--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/session-model.mjs@@ -0,0 +1,57 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Shared OpenViking session-id helpers for memory plugin harnesses.+ */++/**+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.+ */+function globToRe(glob) {+ let re = "^";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i];+ if (c === "*") {+ if (glob[i + 1] === "*") { re += ".*"; i++; }+ else re += "[^/]*";+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {+ re += "\\" + c;+ } else {+ re += c;+ }+ }+ re += "$";+ return new RegExp(re);+}++export function isBypassed(cfg, { sessionId, cwd } = {}) {+ if (cfg.bypassSession) return true;+ const patterns = cfg.bypassSessionPatterns || [];+ if (patterns.length === 0) return false;+ const haystacks = [sessionId, cwd].filter(Boolean);+ for (const pat of patterns) {+ const re = globToRe(pat);+ if (haystacks.some((h) => re.test(h))) return true;+ }+ return false;+}++function safeId(value, replacement = "_") {+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);+}++export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {+ if (!prefix || typeof prefix !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");+ }+ if (!sessionId || typeof sessionId !== "string") {+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");+ }+ const base = `${prefix}${sessionId}`;+ if (!suffix) return base;+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");+ return `${base}__${normalized}`;+}++export function deriveCodexSessionId(codexSessionId) {+ return `cx-${safeId(codexSessionId, "_")}`;+}diff --git a/examples/pi-coding-agent-extension/shared/setup-wizard.mjs b/examples/pi-coding-agent-extension/shared/setup-wizard.mjsnew file mode 100644index 000000000..5108f5f2b--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/setup-wizard.mjs@@ -0,0 +1,111 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.+ *+ * Lets a pure-marketplace install (no installer script) configure the server+ * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:+ *+ * node <plugin>/scripts/setup.mjs+ *+ * Conventions: show current values, keep existing secrets on empty input,+ * merge-write (never drop unknown fields), back up the previous file, 0600.+ */++import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";+import { dirname } from "node:path";+import { createInterface } from "node:readline/promises";+import { loadCredentialFiles } from "./credentials.mjs";++const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";+const LOCAL_URL = "http://127.0.0.1:1933";++function maskSecret(value) {+ const s = String(value || "");+ if (!s) return "(not set)";+ if (s.length <= 8) return "****";+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;+}++function readJsonSafe(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return {};+ }+}++export async function runSetupWizard({+ input = process.stdin,+ output = process.stdout,+ env = process.env,+} = {}) {+ const { cliPath } = loadCredentialFiles(env);+ const current = readJsonSafe(cliPath);+ const rl = createInterface({ input, output });+ const say = (line = "") => output.write(`${line}\n`);++ try {+ say("OpenViking memory plugin setup");+ say(`Config file: ${cliPath}`);+ say("");+ say("Current values:");+ say(` url: ${current.url || "(not set)"}`);+ say(` api_key: ${maskSecret(current.api_key)}`);+ if (current.account) say(` account: ${current.account}`);+ if (current.user) say(` user: ${current.user}`);+ say("");++ const defaultUrl = current.url || LOCAL_URL;+ say("Where do you connect to OpenViking?");+ say(` 1) Self-hosted / local [${LOCAL_URL}]`);+ say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);+ say(` 3) Custom URL / keep current [${defaultUrl}]`);+ const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();+ let url = defaultUrl;+ if (mode === "1") {+ url = LOCAL_URL;+ } else if (mode === "2") {+ url = CLOUD_URL;+ } else {+ const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();+ if (answer) url = answer;+ }++ const keyPrompt = current.api_key+ ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `+ : "API key (leave empty for unauthenticated local mode): ";+ const keyAnswer = await rl.question(keyPrompt);+ let apiKey = current.api_key || "";+ if (keyAnswer === "-") apiKey = "";+ else if (keyAnswer.trim()) apiKey = keyAnswer.trim();+ else if (!current.api_key) apiKey = "";++ const next = { ...current, url, api_key: apiKey };++ say("");+ say("Changes:");+ say(` url: ${current.url || "(not set)"} -> ${next.url}`);+ say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);+ const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();+ if (confirm === "n" || confirm === "no") {+ say("Aborted; nothing written.");+ return { written: false, path: cliPath };+ }++ mkdirSync(dirname(cliPath), { recursive: true });+ if (existsSync(cliPath)) {+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);+ }+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ try {+ chmodSync(cliPath, 0o600);+ } catch {+ /* best effort on platforms without chmod semantics */+ }+ say(`Written: ${cliPath}`);+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");+ return { written: true, path: cliPath };+ } finally {+ rl.close();+ }+}diff --git a/examples/pi-coding-agent-extension/shared/uri-guard.mjs b/examples/pi-coding-agent-extension/shared/uri-guard.mjsnew file mode 100644index 000000000..9505ddb5e--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/uri-guard.mjs@@ -0,0 +1,56 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+const DEFAULT_URI_KEYS = [+ "filePath",+ "file_path",+ "filepath",+ "path",+ "uri",+ "target_uri",+ "targetUri",+ "pattern",+];++export function normalizeToolName(value) {+ return String(value || "").trim().toLowerCase();+}++export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {+ if (!args || typeof args !== "object") return null;+ for (const key of keys) {+ const uri = findVikingUriInValue(args[key]);+ if (uri) return uri;+ }+ return findVikingUriInValue(args);+}++export function findVikingUriInValue(value) {+ if (typeof value === "string") {+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);+ return match?.[0] || null;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const uri = findVikingUriInValue(item);+ if (uri) return uri;+ }+ }+ return null;+}++export function buildGuardMessage(uri, hint = {}) {+ const tool = hint.tool || "the OpenViking MCP tools";+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;+ const lines = [+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",+ `Use ${tool} instead.`,+ ];+ if (example) lines.push(`Example: ${example}`);+ return lines.join("\n");+}diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.tsindex fa884efcf..90be89058 100644--- a/examples/pi-coding-agent-extension/sync.ts+++ b/examples/pi-coding-agent-extension/sync.ts@@ -1,151 +1,8 @@import type { OVClient } from "./client.js";import type { OVConfig } from "./config.js";--// --- Memory Stripping -----/**- * Strip all injected/synthetic blocks before syncing to OV.- * Prevents feedback loop where OV indexes injected context as conversation.- */-export function stripInjectedBlocks(text: string): string {- // 1. <relevant-memories>...</relevant-memories>- text = text.replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/g, "");- // 2. <system-reminder>...</system-reminder>- text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");- // 3. <openviking-context>...</openviking-context>- text = text.replace(/<openviking-context[\s\S]*?<\/openviking-context>/g, "");- // 4. [Subagent Context]... (until double newline or end)- text = text.replace(/\[Subagent Context\][\s\S]*?(?=\n\n|$)/g, "");- // 5. Null bytes- text = text.replace(/\x00/g, "");- return text.trim();-}--// --- CJK-aware Token Estimation -----export function estimateTokens(text: string): number {- if (!text) return 0;- let cjk = 0;- for (let i = 0; i < text.length; i++) {- if (text.charCodeAt(i) >= 0x3000) cjk++;- }- const other = text.length - cjk;- return Math.ceil(cjk * 1.5 + other / 4);-}--// --- Capture Filtering -----const MEMORY_TRIGGERS = [- /remember|preference|prefer|important|decision|decided|always|never/i,- /[\w.-]+@[\w.-]+\.\w+/, // email- /(?:my)\s*(?:name|live|from|birthday|phone|email)/i, // identity- /(?:i)\s*(?:like|hate|love|want|need|think|believe)/i, // preference- /(?:favorite|favourite|love|hate|enjoy|dislike)/i,-];--export function shouldCapture(- text: string, mode: "semantic" | "keyword",-): { capture: boolean; reason: string } {- const normalized = text.trim();- if (!normalized) return { capture: false, reason: "empty" };-- const compact = normalized.replace(/\s+/g, "");- const isCJK = /[-ヿ㐀-鿿豈-가-]/.test(compact);-- // Length bounds- const minLen = isCJK ? 4 : 10;- if (compact.length < minLen) return { capture: false, reason: "too_short" };- if (normalized.length > 24000) return { capture: false, reason: "too_long" };-- // Command detection- if (/^\/[a-z0-9_-]{1,64}\b/i.test(normalized)) {- return { capture: false, reason: "command" };- }-- // Non-content (punctuation/symbols only)- if (/^[\p{P}\p{S}\s]+$/u.test(normalized)) {- return { capture: false, reason: "non_content" };- }-- // Question-only- if (/^(who|what|when|where|why|how|is|are|does|did|can|could|would|should)\b.{0,200}[??]$/i.test(normalized)) {- return { capture: false, reason: "question_only" };- }-- // Keyword mode gate- if (mode === "keyword") {- const hasTrigger = MEMORY_TRIGGERS.some(re => re.test(normalized));- return { capture: hasTrigger, reason: hasTrigger ? "trigger_matched" : "no_trigger" };- }-- // Semantic mode — always capture- return { capture: true, reason: "semantic" };-}--// --- Write Queue -----interface QueuedTurn {- role: string;- content: string;-}--export class WriteQueue {- private client: OVClient;- private sessionId: string;- private queue: QueuedTurn[] = [];- private flushTimer: ReturnType<typeof setInterval> | null = null;- private flushing = false;- private intervalMs: number;- private threshold: number;-- constructor(- client: OVClient, sessionId: string,- intervalMs: number, threshold: number,- ) {- this.client = client;- this.sessionId = sessionId;- this.intervalMs = intervalMs;- this.threshold = threshold;- }-- start(): void {- if (this.intervalMs > 0) {- this.flushTimer = setInterval(() => this.flush(), this.intervalMs);- }- }-- enqueue(role: string, content: string): void {- this.queue.push({ role, content });- if (this.queue.length >= this.threshold) {- this.flush(); // fire-and-forget- }- }-- async flush(): Promise<void> {- if (this.flushing || this.queue.length === 0) return;- this.flushing = true;-- const batch = this.queue.splice(0);- for (const turn of batch) {- const ok = await this.client.addMessage(- this.sessionId, turn.role, turn.content,- );- if (!ok) {- // Re-queue failed turns at the front for retry- this.queue.unshift(turn);- break;- }- }- this.flushing = false;- }-- cancelPending(): void {- if (this.flushTimer) {- clearInterval(this.flushTimer);- this.flushTimer = null;- }- }-}+import { deriveHarnessSessionId } from "./shared/session-model.mjs";+import { enqueue, replayPending } from "./shared/pending-queue.mjs";+import { extractBranchCapturePayloads } from "./lib/capture-adapter.mjs";// --- SyncManager ---@@ -153,9 +10,7 @@ export class SyncManager {private client: OVClient;private config: OVConfig;private ovSessionId: string | null = null;- private pendingTokens = 0;- private syncedTurnCount = 0;- private writeQueue: WriteQueue | null = null;+ private syncedEntryCount = 0;constructor(client: OVClient, config: OVConfig) {this.client = client;@@ -167,80 +22,69 @@ export class SyncManager {async ensureSession(piSessionId: string): Promise<boolean> {if (this.ovSessionId) return true;- const id = `pi-${piSessionId}`;- const created = await this.client.createSession(id);- if (!created) return false;-+ const id = deriveHarnessSessionId("pi-", piSessionId);this.ovSessionId = id;- this.writeQueue = new WriteQueue(- this.client, id,- this.config.writeQueueFlushInterval,- this.config.writeQueueFlushThreshold,- );- this.writeQueue.start();return true;}- async syncTurn(- userText: string, assistantText: string, toolLines: string[],- turnIndex: number,- ): Promise<void> {- if (!this.ovSessionId || !this.writeQueue) return;+ async replayPending(): Promise<void> {+ if (!this.client.connected) return;+ await replayPending(+ (path: string, init?: any) => this.client.fetchJSON(path, init, 10000),+ () => {},+ );+ }- // Dedup guard- if (turnIndex <= this.syncedTurnCount) return;+ async syncBranch(branch: any[]): Promise<number> {+ if (!this.ovSessionId) return 0;- // Capture filter on user text- const filterResult = shouldCapture(userText, this.config.captureMode);- if (!filterResult.capture) {- this.syncedTurnCount = turnIndex;- return;+ const extracted = extractBranchCapturePayloads(branch, this.syncedEntryCount, this.config);+ if (extracted.resetWatermark) this.syncedEntryCount = 0;+ let added = 0;+ for (const payload of extracted.payloads) {+ const ok = await this.addPayload(payload);+ if (!ok) break;+ added++;}-- // Strip injected blocks- const cleanUser = stripInjectedBlocks(userText);- if (!cleanUser) {- this.syncedTurnCount = turnIndex;- return;+ if (added === extracted.payloads.length) {+ this.syncedEntryCount = extracted.nextEntryCount;}-- // Enqueue user message- this.writeQueue.enqueue("user", cleanUser);-- // Enqueue assistant message (if configured)- if (this.config.captureAssistantTurns) {- const cleanAssistant = stripInjectedBlocks(assistantText);- const combined = toolLines.length > 0- ? `${toolLines.join("\n")}\n${cleanAssistant}`- : cleanAssistant;- if (combined.trim()) {- this.writeQueue.enqueue("assistant", combined);- }+ if (added > 0) {+ await this.commitIfNeeded();}+ return added;+ }- // Track tokens- const totalText = cleanUser + assistantText + toolLines.join("");- this.pendingTokens += estimateTokens(totalText);- this.syncedTurnCount = turnIndex;+ async addPayload(payload: any): Promise<boolean> {+ if (!this.ovSessionId) return false;+ const ok = await this.client.addMessagePayload(this.ovSessionId, payload);+ if (ok) return true;+ await enqueue("addMessage", this.ovSessionId, payload);+ return true;+ }- // Check commit threshold- if (this.config.commitTokenThreshold > 0 &&- this.pendingTokens >= this.config.commitTokenThreshold) {- await this.writeQueue.flush();- await this.commit(false);+ async commitIfNeeded(): Promise<void> {+ if (!this.ovSessionId) return;+ const meta = await this.client.getSession(this.ovSessionId);+ const pending = Number(meta?.pending_tokens || 0);+ if (pending >= this.config.commitTokenThreshold) {+ await this.commit();}}- async commit(wait: boolean = false): Promise<string | null> {+ async commit(): Promise<any | null> {if (!this.ovSessionId) return null;- const result = await this.client.commitSession(this.ovSessionId, wait);- if (result) this.pendingTokens = 0;+ const result = await this.client.commitSession(this.ovSessionId);+ if (!result) {+ await enqueue("commitSession", this.ovSessionId, {+ keep_recent_count: this.config.commitKeepRecentCount,+ });+ return null;+ }return result;}async shutdown(): Promise<void> {- if (!this.writeQueue) return;- this.writeQueue.cancelPending();- await this.writeQueue.flush();+ return;}}diff --git a/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjsnew file mode 100644index 000000000..10e04ba92--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs@@ -0,0 +1,51 @@+import test from "node:test";+import assert from "node:assert/strict";+import { extractBranchCapturePayloads } from "../lib/capture-adapter.mjs";++test("extractBranchCapturePayloads converts user text to message payload", () => {+ const branch = [+ { type: "message", message: { role: "user", content: "Remember this decision for later." } },+ ];++ const result = extractBranchCapturePayloads(branch, 0, { peerId: "peer-a" });+ assert.equal(result.nextEntryCount, 1);+ assert.equal(result.payloads.length, 1);+ assert.equal(result.payloads[0].role, "user");+ assert.equal(result.payloads[0].parts[0].type, "text");+ assert.match(result.payloads[0].parts[0].text, /Remember this decision/);+ assert.equal(result.payloads[0].peer_id, "peer-a");+});++test("extractBranchCapturePayloads emits structured tool parts", () => {+ const branch = [+ {+ type: "message",+ message: {+ role: "assistant",+ content: [+ { type: "text", text: "I will inspect it." },+ { type: "tool_call", id: "call-1", name: "read", input: { path: "a.txt" } },+ ],+ },+ },+ ];++ const result = extractBranchCapturePayloads(branch, 0, {+ captureAssistantTurns: true,+ captureToolMaxChars: 2000,+ });+ assert.equal(result.payloads.length, 1);+ assert.equal(result.payloads[0].role, "assistant");+ assert.ok(Array.isArray(result.payloads[0].parts));+ assert.equal(result.payloads[0].parts.some((part) => part.type === "tool" && part.tool_name === "read"), true);+});++test("extractBranchCapturePayloads resets watermark when branch shrinks", () => {+ const result = extractBranchCapturePayloads([+ { type: "message", message: { role: "user", content: "New compacted branch content." } },+ ], 5, {});++ assert.equal(result.resetWatermark, true);+ assert.equal(result.nextEntryCount, 1);+ assert.equal(result.payloads.length, 1);+});diff --git a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjsnew file mode 100644index 000000000..0338dcc5f--- /dev/null+++ b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs@@ -0,0 +1,31 @@+import test from "node:test"+import assert from "node:assert/strict"+import { guardVikingUriToolCall } from "../lib/uri-guard-adapter.mjs"++test("pi URI guard blocks builtin file tools on viking URIs", () => {+ const decision = guardVikingUriToolCall({+ type: "tool_call",+ toolName: "read",+ input: { path: "viking://resources/project/file.md" },+ })++ assert.equal(decision?.block, true)+ assert.match(decision?.reason ?? "", /viking:\/\/ URIs are OpenViking virtual paths/)+ assert.match(decision?.reason ?? "", /Use viking_read instead/)+})++test("pi URI guard blocks bash commands containing viking URI", () => {+ const decision = guardVikingUriToolCall({+ type: "tool_call",+ toolName: "bash",+ input: { command: "cat viking://resources/project/file.md" },+ })++ assert.equal(decision?.block, true)+ assert.match(decision?.reason ?? "", /Use viking_read or viking_search instead/)+})++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)+})diff --git a/examples/pi-coding-agent-extension/tools.ts b/examples/pi-coding-agent-extension/tools.tsindex bf7f6f828..6228174f1 100644--- a/examples/pi-coding-agent-extension/tools.ts+++ b/examples/pi-coding-agent-extension/tools.ts@@ -1,5 +1,5 @@import { Type } from "typebox";-import { StringEnum } from "@mariozechner/pi-ai";+import { StringEnum } from "@earendil-works/pi-ai";import type { OVClient } from "./client.js";import type { SyncManager } from "./sync.js";