diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md new file mode 100644 index 000000000..30b735917 --- /dev/null +++ b/examples/codex-memory-plugin/README.md @@ -0,0 +1,109 @@ +# OpenViking Memory Plugin for Codex + +Codex MCP server example that exposes OpenViking memories as explicit tools. + +This example is repo-only. It does not edit `~/.codex/config.toml` for you. + +## What It Does + +- Exposes four MCP tools for Codex: + - `memory_recall` + - `memory_store` + - `memory_forget` + - `memory_health` +- Reads OpenViking connection details from `~/.openviking/ov.conf` +- Marks recalled memory URIs as `used()` before a fire-and-forget `commit()` +- Contributes retrieval feedback to OpenViking's hotness ranking without blocking Codex + +## Prerequisites + +- Codex CLI installed +- OpenViking HTTP server running +- Node.js 22+ + +Start OpenViking first if needed: + +```bash +openviking-server --config ~/.openviking/ov.conf +``` + +## Build + +From this directory: + +```bash +npm ci +npm run build +``` + +That produces `servers/memory-server.js`, the MCP entrypoint Codex will launch. + +## Add To Codex + +Add the MCP server with the verified Codex CLI shape: + +```bash +codex mcp add openviking-memory -- \ + node /ABS/PATH/TO/OpenViking/examples/codex-memory-plugin/servers/memory-server.js +``` + +Example using your local repository checkout: + +```bash +codex mcp add openviking-memory -- \ + node /path/to/OpenViking/examples/codex-memory-plugin/servers/memory-server.js +``` + +List configured MCP servers: + +```bash +codex mcp list +``` + +Remove it later if needed: + +```bash +codex mcp remove openviking-memory +``` + +## Optional Environment Overrides + +The server defaults to `~/.openviking/ov.conf`. You can override behavior with env vars when adding the MCP server: + +```bash +codex mcp add openviking-memory \ + --env OPENVIKING_AGENT_ID=codex-local \ + --env OPENVIKING_TIMEOUT_MS=20000 \ + -- node /ABS/PATH/TO/OpenViking/examples/codex-memory-plugin/servers/memory-server.js +``` + +Supported overrides: + +- `OPENVIKING_CONFIG_FILE` +- `OPENVIKING_AGENT_ID` +- `OPENVIKING_TIMEOUT_MS` +- `OPENVIKING_RECALL_LIMIT` +- `OPENVIKING_SCORE_THRESHOLD` + +## How Recall Feedback Works + +`memory_recall` searches OpenViking, returns the selected memories to Codex, and also starts a background sequence: + +1. `POST /api/v1/sessions` +2. `POST /api/v1/sessions/{id}/used` with recalled `viking://` URIs +3. `POST /api/v1/sessions/{id}/commit` +4. `DELETE /api/v1/sessions/{id}` + +This is fire-and-forget. Tool responses do not wait on the feedback loop. + +## Notes + +- This example gives Codex explicit tools only. It does not implement transparent auto-recall hooks. +- `memory_recall` only marks the memories it actually returns as used, which is higher-signal than broad auto-recall marking. +- If your OpenViking server requires auth, the MCP server reads `root_api_key` from `ov.conf`. + +## Troubleshooting + +- MCP server not starting: run `npm ci && npm run build` in this directory first +- OpenViking request failures: verify `openviking-server` is reachable at the host and port in `ov.conf` +- No memories returned: confirm you have indexed data under `viking://user/memories` or `viking://agent/memories` diff --git a/examples/codex-memory-plugin/package-lock.json b/examples/codex-memory-plugin/package-lock.json new file mode 100644 index 000000000..75ce986d8 --- /dev/null +++ b/examples/codex-memory-plugin/package-lock.json @@ -0,0 +1,1174 @@ +{ + "name": "codex-openviking-memory", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-openviking-memory", + "version": "0.1.0", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.12.1", + "zod": "^4.3.6" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^5.7.0" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.11", + "resolved": "https://registry.npmmirror.com/@hono/node-server/-/node-server-1.19.11.tgz", + "integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.27.1", + "resolved": "https://registry.npmmirror.com/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz", + "integrity": "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@types/node": { + "version": "22.19.15", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.19.15.tgz", + "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmmirror.com/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmmirror.com/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmmirror.com/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmmirror.com/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmmirror.com/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmmirror.com/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.3.1", + "resolved": "https://registry.npmmirror.com/express-rate-limit/-/express-rate-limit-8.3.1.tgz", + "integrity": "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==", + "license": "MIT", + "dependencies": { + "ip-address": "10.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.8", + "resolved": "https://registry.npmmirror.com/hono/-/hono-4.12.8.tgz", + "integrity": "sha512-VJCEvtrezO1IAR+kqEYnxUOoStaQPGrCmX3j4wDTNOcD1uRPFpGlwQUIW8niPuvHXaTUxeOUl5MMDGrl+tmO9A==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.1.0", + "resolved": "https://registry.npmmirror.com/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmmirror.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.2", + "resolved": "https://registry.npmmirror.com/jose/-/jose-6.2.2.tgz", + "integrity": "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmmirror.com/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmmirror.com/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmmirror.com/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmmirror.com/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmmirror.com/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmmirror.com/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + } + } +} diff --git a/examples/codex-memory-plugin/package.json b/examples/codex-memory-plugin/package.json new file mode 100644 index 000000000..563f7f8c0 --- /dev/null +++ b/examples/codex-memory-plugin/package.json @@ -0,0 +1,18 @@ +{ + "name": "codex-openviking-memory", + "version": "0.1.0", + "description": "OpenViking memory plugin for Codex — semantic long-term memory via MCP", + "type": "module", + "scripts": { + "build": "tsc", + "dev": "tsc --watch" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.12.1", + "zod": "^4.3.6" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^5.7.0" + } +} diff --git a/examples/codex-memory-plugin/servers/memory-server.js b/examples/codex-memory-plugin/servers/memory-server.js new file mode 100644 index 000000000..f5efba39f --- /dev/null +++ b/examples/codex-memory-plugin/servers/memory-server.js @@ -0,0 +1,556 @@ +/** + * OpenViking Memory MCP Server for Codex + * + * Exposes OpenViking long-term memory as MCP tools: + * - memory_recall : semantic search across memories + * - memory_store : extract and persist new memories + * - memory_forget : delete memories by URI or query + * - memory_health : connectivity and config checks + * + * Ported from the OpenClaw context-engine plugin (openclaw-plugin/). + * Adapted for Codex's MCP server interface (stdio transport). + */ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { z } from "zod"; +import { createHash } from "node:crypto"; +// --------------------------------------------------------------------------- +// Configuration — loaded from ov.conf. +// Env var: OPENVIKING_CONFIG_FILE (default: ~/.openviking/ov.conf) +// Optional runtime overrides can be supplied via environment variables. +// --------------------------------------------------------------------------- +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join, resolve as resolvePath } from "node:path"; +function loadOvConf() { + const defaultPath = join(homedir(), ".openviking", "ov.conf"); + const configPath = resolvePath((process.env.OPENVIKING_CONFIG_FILE || defaultPath).replace(/^~/, homedir())); + try { + return JSON.parse(readFileSync(configPath, "utf-8")); + } + catch (err) { + const code = err?.code; + const msg = code === "ENOENT" + ? `Config file not found: ${configPath}` + : `Failed to read config: ${configPath}`; + process.stderr.write(`[openviking-memory] ${msg}\n`); + process.exit(1); + } +} +function num(val, fallback) { + if (typeof val === "number" && Number.isFinite(val)) + return val; + if (typeof val === "string" && val.trim()) { + const n = Number(val); + if (Number.isFinite(n)) + return n; + } + return fallback; +} +function str(val, fallback) { + if (typeof val === "string" && val.trim()) + return val.trim(); + return fallback; +} +const file = loadOvConf(); +const serverCfg = (file.server ?? {}); +const host = str(serverCfg.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1"); +const port = Math.floor(num(serverCfg.port, 1933)); +const config = { + baseUrl: `http://${host}:${port}`, + apiKey: str(serverCfg.root_api_key, ""), + agentId: str(process.env.OPENVIKING_AGENT_ID, "codex"), + timeoutMs: Math.max(1000, Math.floor(num(process.env.OPENVIKING_TIMEOUT_MS, 15000))), + recallLimit: Math.max(1, Math.floor(num(process.env.OPENVIKING_RECALL_LIMIT, 6))), + scoreThreshold: Math.min(1, Math.max(0, num(process.env.OPENVIKING_SCORE_THRESHOLD, 0.01))), +}; +// --------------------------------------------------------------------------- +// OpenViking HTTP Client (ported from openclaw-plugin/client.ts) +// --------------------------------------------------------------------------- +const MEMORY_URI_PATTERNS = [ + /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/, + /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/, +]; +const USER_STRUCTURE_DIRS = new Set(["memories"]); +const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]); +function md5Short(input) { + return createHash("md5").update(input).digest("hex").slice(0, 12); +} +function isMemoryUri(uri) { + return MEMORY_URI_PATTERNS.some((p) => p.test(uri)); +} +class OpenVikingClient { + baseUrl; + apiKey; + agentId; + timeoutMs; + resolvedSpaceByScope = {}; + runtimeIdentity = null; + constructor(baseUrl, apiKey, agentId, timeoutMs) { + this.baseUrl = baseUrl; + this.apiKey = apiKey; + this.agentId = agentId; + this.timeoutMs = timeoutMs; + } + async request(path, init = {}) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), this.timeoutMs); + try { + const headers = new Headers(init.headers ?? {}); + if (this.apiKey) + headers.set("X-API-Key", this.apiKey); + if (this.agentId) + headers.set("X-OpenViking-Agent", this.agentId); + if (init.body && !headers.has("Content-Type")) + headers.set("Content-Type", "application/json"); + const response = await fetch(`${this.baseUrl}${path}`, { + ...init, + headers, + signal: controller.signal, + }); + const payload = (await response.json().catch(() => ({}))); + if (!response.ok || payload.status === "error") { + const code = payload.error?.code ? ` [${payload.error.code}]` : ""; + const message = payload.error?.message ?? `HTTP ${response.status}`; + throw new Error(`OpenViking request failed${code}: ${message}`); + } + return (payload.result ?? payload); + } + finally { + clearTimeout(timer); + } + } + async healthCheck() { + try { + await this.request("/health"); + return true; + } + catch { + return false; + } + } + async ls(uri) { + return this.request(`/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`); + } + async getRuntimeIdentity() { + if (this.runtimeIdentity) + return this.runtimeIdentity; + const fallback = { userId: "default", agentId: this.agentId || "default" }; + try { + const status = await this.request("/api/v1/system/status"); + const userId = typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default"; + this.runtimeIdentity = { userId, agentId: this.agentId || "default" }; + return this.runtimeIdentity; + } + catch { + this.runtimeIdentity = fallback; + return fallback; + } + } + async resolveScopeSpace(scope) { + const cached = this.resolvedSpaceByScope[scope]; + if (cached) + return cached; + const identity = await this.getRuntimeIdentity(); + const fallbackSpace = scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`); + const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS; + try { + const entries = await this.ls(`viking://${scope}`); + const spaces = entries + .filter((e) => e?.isDir === true) + .map((e) => (typeof e.name === "string" ? e.name.trim() : "")) + .filter((n) => n && !n.startsWith(".") && !reservedDirs.has(n)); + if (spaces.length > 0) { + if (spaces.includes(fallbackSpace)) { + this.resolvedSpaceByScope[scope] = fallbackSpace; + return fallbackSpace; + } + if (scope === "user" && spaces.includes("default")) { + this.resolvedSpaceByScope[scope] = "default"; + return "default"; + } + if (spaces.length === 1) { + this.resolvedSpaceByScope[scope] = spaces[0]; + return spaces[0]; + } + } + } + catch { /* fall through */ } + this.resolvedSpaceByScope[scope] = fallbackSpace; + return fallbackSpace; + } + async normalizeTargetUri(targetUri) { + const trimmed = targetUri.trim().replace(/\/+$/, ""); + const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/); + if (!match) + return trimmed; + const scope = match[1]; + const rawRest = (match[2] ?? "").trim(); + if (!rawRest) + return trimmed; + const parts = rawRest.split("/").filter(Boolean); + if (parts.length === 0) + return trimmed; + const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS; + if (!reservedDirs.has(parts[0])) + return trimmed; + const space = await this.resolveScopeSpace(scope); + return `viking://${scope}/${space}/${parts.join("/")}`; + } + async find(query, options) { + const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri); + return this.request("/api/v1/search/find", { + method: "POST", + body: JSON.stringify({ + query, + target_uri: normalizedTargetUri, + limit: options.limit, + score_threshold: options.scoreThreshold, + }), + }); + } + async read(uri) { + return this.request(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`); + } + async createSession() { + const result = await this.request("/api/v1/sessions", { + method: "POST", + body: JSON.stringify({}), + }); + return result.session_id; + } + async addSessionMessage(sessionId, role, content) { + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, { + method: "POST", + body: JSON.stringify({ role, content }), + }); + } + async extractSessionMemories(sessionId) { + return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`, { method: "POST", body: JSON.stringify({}) }); + } + async sessionUsed(sessionId, contexts) { + if (contexts.length === 0) + return; + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/used`, { + method: "POST", + body: JSON.stringify({ contexts }), + }); + } + async commitSession(sessionId) { + return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, { method: "POST", body: JSON.stringify({}) }); + } + async deleteSession(sessionId) { + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" }); + } + async deleteUri(uri) { + await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, { + method: "DELETE", + }); + } +} +// --------------------------------------------------------------------------- +// Memory ranking helpers (ported from openclaw-plugin/memory-ranking.ts) +// --------------------------------------------------------------------------- +function clampScore(value) { + if (typeof value !== "number" || Number.isNaN(value)) + return 0; + return Math.max(0, Math.min(1, value)); +} +function normalizeDedupeText(text) { + return text.toLowerCase().replace(/\s+/g, " ").trim(); +} +function getMemoryDedupeKey(item) { + const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? ""); + const category = (item.category ?? "").toLowerCase() || "unknown"; + if (abstract) + return `abstract:${category}:${abstract}`; + return `uri:${item.uri}`; +} +function postProcessMemories(items, options) { + const deduped = []; + const seen = new Set(); + const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score)); + for (const item of sorted) { + if (options.leafOnly && item.level !== 2) + continue; + if (clampScore(item.score) < options.scoreThreshold) + continue; + const key = getMemoryDedupeKey(item); + if (seen.has(key)) + continue; + seen.add(key); + deduped.push(item); + if (deduped.length >= options.limit) + break; + } + return deduped; +} +function formatMemoryLines(items) { + return items + .map((item, i) => { + const score = clampScore(item.score); + const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri; + const category = item.category ?? "memory"; + return `${i + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`; + }) + .join("\n"); +} +// Query-aware ranking (ported from openclaw-plugin/memory-ranking.ts) +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 QUERY_TOKEN_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", +]); +function buildQueryProfile(query) { + const text = query.trim(); + const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? []; + const tokens = allTokens.filter((t) => !QUERY_TOKEN_STOPWORDS.has(t)); + return { + tokens, + 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 rankForInjection(item, query) { + const baseScore = clampScore(item.score); + const abstract = (item.abstract ?? item.overview ?? "").trim(); + const leafBoost = item.level === 2 ? 0.12 : 0; + const cat = (item.category ?? "").toLowerCase(); + const eventBoost = query.wantsTemporal && (cat === "events" || item.uri.includes("/events/")) ? 0.1 : 0; + const prefBoost = query.wantsPreference && (cat === "preferences" || item.uri.includes("/preferences/")) ? 0.08 : 0; + const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`); + return baseScore + leafBoost + eventBoost + prefBoost + overlapBoost; +} +function pickMemoriesForInjection(items, limit, queryText) { + if (items.length === 0 || limit <= 0) + return []; + const query = buildQueryProfile(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 = (item.abstract ?? item.overview ?? "").trim().toLowerCase() || item.uri; + if (seen.has(key)) + continue; + seen.add(key); + deduped.push(item); + } + const leaves = deduped.filter((item) => item.level === 2); + 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; + picked.push(item); + } + return picked; +} +// --------------------------------------------------------------------------- +// Shared search helpers +// --------------------------------------------------------------------------- +async function searchBothScopes(client, query, limit) { + const [userSettled, agentSettled] = await Promise.allSettled([ + client.find(query, { targetUri: "viking://user/memories", limit, scoreThreshold: 0 }), + client.find(query, { targetUri: "viking://agent/memories", limit, scoreThreshold: 0 }), + ]); + const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] }; + const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] }; + const all = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])]; + // Deduplicate by URI and keep only leaf memories + const unique = all.filter((m, i, self) => i === self.findIndex((o) => o.uri === m.uri)); + return unique.filter((m) => m.level === 2); +} +function markRecalledMemoriesUsed(client, contexts) { + const uniqueContexts = [...new Set(contexts.filter((uri) => typeof uri === "string" && uri.length > 0))]; + if (uniqueContexts.length === 0) + return; + void (async () => { + let sessionId; + try { + sessionId = await client.createSession(); + await client.sessionUsed(sessionId, uniqueContexts); + await client.commitSession(sessionId); + } + catch { + // Fire-and-forget usage tracking must never block or fail the caller. + } + finally { + if (sessionId) { + await client.deleteSession(sessionId).catch(() => { }); + } + } + })(); +} +// --------------------------------------------------------------------------- +// MCP Server +// --------------------------------------------------------------------------- +const client = new OpenVikingClient(config.baseUrl, config.apiKey, config.agentId, config.timeoutMs); +const server = new McpServer({ + name: "openviking-memory-codex", + version: "0.1.0", +}); +// -- Tool: memory_recall -------------------------------------------------- +server.tool("memory_recall", "Search long-term memories from OpenViking. Use when you need past user preferences, facts, decisions, or any previously stored information.", { + query: z.string().describe("Search query — describe what you want to recall"), + limit: z.number().optional().describe("Max results to return (default: 6)"), + score_threshold: z.number().optional().describe("Min relevance score 0-1 (default: 0.01)"), + target_uri: z.string().optional().describe("Search scope URI, e.g. viking://user/memories"), +}, async ({ query, limit, score_threshold, target_uri }) => { + const recallLimit = limit ?? config.recallLimit; + const threshold = score_threshold ?? config.scoreThreshold; + const candidateLimit = Math.max(recallLimit * 4, 20); + let leafMemories; + if (target_uri) { + const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 }); + leafMemories = (result.memories ?? []).filter((m) => m.level === 2); + } + else { + leafMemories = await searchBothScopes(client, query, candidateLimit); + } + const processed = postProcessMemories(leafMemories, { limit: candidateLimit, scoreThreshold: threshold }); + const memories = pickMemoriesForInjection(processed, recallLimit, query); + if (memories.length === 0) { + return { content: [{ type: "text", text: "No relevant memories found in OpenViking." }] }; + } + markRecalledMemoriesUsed(client, memories.map((memory) => memory.uri)); + // Read full content for leaf memories + const lines = await Promise.all(memories.map(async (item) => { + if (item.level === 2) { + try { + const content = await client.read(item.uri); + if (content?.trim()) + return `- [${item.category ?? "memory"}] ${content.trim()}`; + } + catch { /* fallback */ } + } + return `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`; + })); + return { + content: [{ + type: "text", + text: `Found ${memories.length} relevant memories:\n\n${lines.join("\n")}\n\n---\n${formatMemoryLines(memories)}`, + }], + }; +}); +// -- Tool: memory_store --------------------------------------------------- +server.tool("memory_store", "Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, decisions, or any information worth persisting across sessions.", { + text: z.string().describe("The information to store as memory"), + role: z.string().optional().describe("Message role: 'user' (default) or 'assistant'"), +}, async ({ text, role }) => { + const msgRole = role || "user"; + let sessionId; + try { + sessionId = await client.createSession(); + await client.addSessionMessage(sessionId, msgRole, text); + const extracted = await client.extractSessionMemories(sessionId); + if (extracted.length === 0) { + return { + content: [{ + type: "text", + text: "Memory stored but extraction returned 0 memories. The text may be too short or not contain extractable information. Check OpenViking server logs for details.", + }], + }; + } + return { + content: [{ + type: "text", + text: `Successfully extracted ${extracted.length} memory/memories from the provided text and stored them in OpenViking.`, + }], + }; + } + finally { + if (sessionId) { + await client.deleteSession(sessionId).catch(() => { }); + } + } +}); +// -- Tool: memory_forget -------------------------------------------------- +server.tool("memory_forget", "Delete a memory from OpenViking. Provide an exact URI for direct deletion, or a search query to find and delete matching memories.", { + uri: z.string().optional().describe("Exact viking:// memory URI to delete"), + query: z.string().optional().describe("Search query to find the memory to delete"), + target_uri: z.string().optional().describe("Search scope URI (default: viking://user/memories)"), +}, async ({ uri, query, target_uri }) => { + // Direct URI deletion + if (uri) { + if (!isMemoryUri(uri)) { + return { content: [{ type: "text", text: `Refusing to delete non-memory URI: ${uri}` }] }; + } + await client.deleteUri(uri); + return { content: [{ type: "text", text: `Deleted memory: ${uri}` }] }; + } + if (!query) { + return { content: [{ type: "text", text: "Please provide either a uri or query parameter." }] }; + } + // Search then delete + const candidateLimit = 20; + let candidates; + if (target_uri) { + const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 }); + candidates = postProcessMemories(result.memories ?? [], { + limit: candidateLimit, + scoreThreshold: config.scoreThreshold, + leafOnly: true, + }).filter((item) => isMemoryUri(item.uri)); + } + else { + const leafMemories = await searchBothScopes(client, query, candidateLimit); + candidates = postProcessMemories(leafMemories, { + limit: candidateLimit, + scoreThreshold: config.scoreThreshold, + leafOnly: true, + }).filter((item) => isMemoryUri(item.uri)); + } + if (candidates.length === 0) { + return { content: [{ type: "text", text: "No matching memories found. Try a more specific query." }] }; + } + // Auto-delete if single strong match + const top = candidates[0]; + if (candidates.length === 1 && clampScore(top.score) >= 0.85) { + await client.deleteUri(top.uri); + return { content: [{ type: "text", text: `Deleted memory: ${top.uri}` }] }; + } + // List candidates for confirmation + const list = candidates + .map((item) => `- ${item.uri} — ${item.abstract?.trim() || "?"} (${(clampScore(item.score) * 100).toFixed(0)}%)`) + .join("\n"); + return { + content: [{ + type: "text", + text: `Found ${candidates.length} candidate memories. Please specify the exact URI to delete:\n\n${list}`, + }], + }; +}); +// -- Tool: memory_health -------------------------------------------------- +server.tool("memory_health", "Check whether the OpenViking memory server is reachable and healthy.", {}, async () => { + const ok = await client.healthCheck(); + return { + content: [{ + type: "text", + text: ok + ? `OpenViking is healthy (${config.baseUrl})` + : `OpenViking is unreachable at ${config.baseUrl}. Please check if the server is running.`, + }], + }; +}); +// --------------------------------------------------------------------------- +// Start +// --------------------------------------------------------------------------- +const transport = new StdioServerTransport(); +await server.connect(transport); diff --git a/examples/codex-memory-plugin/src/memory-server.ts b/examples/codex-memory-plugin/src/memory-server.ts new file mode 100644 index 000000000..2dd1b9cbe --- /dev/null +++ b/examples/codex-memory-plugin/src/memory-server.ts @@ -0,0 +1,682 @@ +/** + * OpenViking Memory MCP Server for Codex + * + * Exposes OpenViking long-term memory as MCP tools: + * - memory_recall : semantic search across memories + * - memory_store : extract and persist new memories + * - memory_forget : delete memories by URI or query + * - memory_health : connectivity and config checks + * + * Ported from the OpenClaw context-engine plugin (openclaw-plugin/). + * Adapted for Codex's MCP server interface (stdio transport). + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { z } from "zod"; +import { createHash } from "node:crypto"; + +// --------------------------------------------------------------------------- +// Types (ported from openclaw-plugin/client.ts) +// --------------------------------------------------------------------------- + +type FindResultItem = { + uri: string; + level?: number; + abstract?: string; + overview?: string; + category?: string; + score?: number; + match_reason?: string; +}; + +type FindResult = { + memories?: FindResultItem[]; + resources?: FindResultItem[]; + skills?: FindResultItem[]; + total?: number; +}; + +type CommitSessionResult = { + task_id?: string; + status?: string; + memories_extracted?: Record; + active_count_updated?: number; + error?: unknown; +}; + +type ScopeName = "user" | "agent"; + +// --------------------------------------------------------------------------- +// Configuration — loaded from ov.conf. +// Env var: OPENVIKING_CONFIG_FILE (default: ~/.openviking/ov.conf) +// Optional runtime overrides can be supplied via environment variables. +// --------------------------------------------------------------------------- + +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join, resolve as resolvePath } from "node:path"; + +function loadOvConf(): Record { + const defaultPath = join(homedir(), ".openviking", "ov.conf"); + const configPath = resolvePath( + (process.env.OPENVIKING_CONFIG_FILE || defaultPath).replace(/^~/, homedir()), + ); + try { + return JSON.parse(readFileSync(configPath, "utf-8")); + } catch (err: unknown) { + const code = (err as { code?: string })?.code; + const msg = code === "ENOENT" + ? `Config file not found: ${configPath}` + : `Failed to read config: ${configPath}`; + process.stderr.write(`[openviking-memory] ${msg}\n`); + process.exit(1); + } +} + +function num(val: unknown, fallback: number): number { + if (typeof val === "number" && Number.isFinite(val)) return val; + if (typeof val === "string" && val.trim()) { + const n = Number(val); + if (Number.isFinite(n)) return n; + } + return fallback; +} + +function str(val: unknown, fallback: string): string { + if (typeof val === "string" && val.trim()) return val.trim(); + return fallback; +} + +const file = loadOvConf(); +const serverCfg = (file.server ?? {}) as Record; + +const host = str(serverCfg.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1"); +const port = Math.floor(num(serverCfg.port, 1933)); + +const config = { + baseUrl: `http://${host}:${port}`, + apiKey: str(serverCfg.root_api_key, ""), + agentId: str(process.env.OPENVIKING_AGENT_ID, "codex"), + timeoutMs: Math.max(1000, Math.floor(num(process.env.OPENVIKING_TIMEOUT_MS, 15000))), + recallLimit: Math.max(1, Math.floor(num(process.env.OPENVIKING_RECALL_LIMIT, 6))), + scoreThreshold: Math.min(1, Math.max(0, num(process.env.OPENVIKING_SCORE_THRESHOLD, 0.01))), +}; + +// --------------------------------------------------------------------------- +// OpenViking HTTP Client (ported from openclaw-plugin/client.ts) +// --------------------------------------------------------------------------- + +const MEMORY_URI_PATTERNS = [ + /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/, + /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/, +]; +const USER_STRUCTURE_DIRS = new Set(["memories"]); +const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]); + +function md5Short(input: string): string { + return createHash("md5").update(input).digest("hex").slice(0, 12); +} + +function isMemoryUri(uri: string): boolean { + return MEMORY_URI_PATTERNS.some((p) => p.test(uri)); +} + +class OpenVikingClient { + private resolvedSpaceByScope: Partial> = {}; + private runtimeIdentity: { userId: string; agentId: string } | null = null; + + constructor( + private readonly baseUrl: string, + private readonly apiKey: string, + private readonly agentId: string, + private readonly timeoutMs: number, + ) {} + + private async request(path: string, init: RequestInit = {}): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), this.timeoutMs); + try { + const headers = new Headers(init.headers ?? {}); + if (this.apiKey) headers.set("X-API-Key", this.apiKey); + if (this.agentId) headers.set("X-OpenViking-Agent", this.agentId); + if (init.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json"); + + const response = await fetch(`${this.baseUrl}${path}`, { + ...init, + headers, + signal: controller.signal, + }); + + const payload = (await response.json().catch(() => ({}))) as { + status?: string; + result?: T; + error?: { code?: string; message?: string }; + }; + + if (!response.ok || payload.status === "error") { + const code = payload.error?.code ? ` [${payload.error.code}]` : ""; + const message = payload.error?.message ?? `HTTP ${response.status}`; + throw new Error(`OpenViking request failed${code}: ${message}`); + } + return (payload.result ?? payload) as T; + } finally { + clearTimeout(timer); + } + } + + async healthCheck(): Promise { + try { + await this.request<{ status: string }>("/health"); + return true; + } catch { + return false; + } + } + + private async ls(uri: string): Promise>> { + return this.request>>( + `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`, + ); + } + + private async getRuntimeIdentity(): Promise<{ userId: string; agentId: string }> { + if (this.runtimeIdentity) return this.runtimeIdentity; + const fallback = { userId: "default", agentId: this.agentId || "default" }; + try { + const status = await this.request<{ user?: unknown }>("/api/v1/system/status"); + const userId = + typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default"; + this.runtimeIdentity = { userId, agentId: this.agentId || "default" }; + return this.runtimeIdentity; + } catch { + this.runtimeIdentity = fallback; + return fallback; + } + } + + private async resolveScopeSpace(scope: ScopeName): Promise { + const cached = this.resolvedSpaceByScope[scope]; + if (cached) return cached; + + const identity = await this.getRuntimeIdentity(); + const fallbackSpace = + scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`); + const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS; + + try { + const entries = await this.ls(`viking://${scope}`); + const spaces = entries + .filter((e) => e?.isDir === true) + .map((e) => (typeof e.name === "string" ? e.name.trim() : "")) + .filter((n) => n && !n.startsWith(".") && !reservedDirs.has(n)); + + if (spaces.length > 0) { + if (spaces.includes(fallbackSpace)) { + this.resolvedSpaceByScope[scope] = fallbackSpace; + return fallbackSpace; + } + if (scope === "user" && spaces.includes("default")) { + this.resolvedSpaceByScope[scope] = "default"; + return "default"; + } + if (spaces.length === 1) { + this.resolvedSpaceByScope[scope] = spaces[0]!; + return spaces[0]!; + } + } + } catch { /* fall through */ } + + this.resolvedSpaceByScope[scope] = fallbackSpace; + return fallbackSpace; + } + + private async normalizeTargetUri(targetUri: string): Promise { + const trimmed = targetUri.trim().replace(/\/+$/, ""); + const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/); + if (!match) return trimmed; + + const scope = match[1] as ScopeName; + const rawRest = (match[2] ?? "").trim(); + if (!rawRest) return trimmed; + + const parts = rawRest.split("/").filter(Boolean); + if (parts.length === 0) return trimmed; + + const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS; + if (!reservedDirs.has(parts[0]!)) return trimmed; + + const space = await this.resolveScopeSpace(scope); + return `viking://${scope}/${space}/${parts.join("/")}`; + } + + async find( + query: string, + options: { targetUri: string; limit: number; scoreThreshold?: number }, + ): Promise { + const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri); + return this.request("/api/v1/search/find", { + method: "POST", + body: JSON.stringify({ + query, + target_uri: normalizedTargetUri, + limit: options.limit, + score_threshold: options.scoreThreshold, + }), + }); + } + + async read(uri: string): Promise { + return this.request(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`); + } + + async createSession(): Promise { + const result = await this.request<{ session_id: string }>("/api/v1/sessions", { + method: "POST", + body: JSON.stringify({}), + }); + return result.session_id; + } + + async addSessionMessage(sessionId: string, role: string, content: string): Promise { + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, { + method: "POST", + body: JSON.stringify({ role, content }), + }); + } + + async extractSessionMemories(sessionId: string): Promise>> { + return this.request>>( + `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`, + { method: "POST", body: JSON.stringify({}) }, + ); + } + + async sessionUsed(sessionId: string, contexts: string[]): Promise { + if (contexts.length === 0) return; + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/used`, { + method: "POST", + body: JSON.stringify({ contexts }), + }); + } + + async commitSession(sessionId: string): Promise { + return this.request( + `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, + { method: "POST", body: JSON.stringify({}) }, + ); + } + + async deleteSession(sessionId: string): Promise { + await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" }); + } + + async deleteUri(uri: string): Promise { + await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, { + method: "DELETE", + }); + } +} + +// --------------------------------------------------------------------------- +// Memory ranking helpers (ported from openclaw-plugin/memory-ranking.ts) +// --------------------------------------------------------------------------- + +function clampScore(value: number | undefined): number { + if (typeof value !== "number" || Number.isNaN(value)) return 0; + return Math.max(0, Math.min(1, value)); +} + +function normalizeDedupeText(text: string): string { + return text.toLowerCase().replace(/\s+/g, " ").trim(); +} + +function getMemoryDedupeKey(item: FindResultItem): string { + const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? ""); + const category = (item.category ?? "").toLowerCase() || "unknown"; + if (abstract) return `abstract:${category}:${abstract}`; + return `uri:${item.uri}`; +} + +function postProcessMemories( + items: FindResultItem[], + options: { limit: number; scoreThreshold: number; leafOnly?: boolean }, +): FindResultItem[] { + const deduped: FindResultItem[] = []; + const seen = new Set(); + const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score)); + for (const item of sorted) { + if (options.leafOnly && item.level !== 2) continue; + if (clampScore(item.score) < options.scoreThreshold) continue; + const key = getMemoryDedupeKey(item); + if (seen.has(key)) continue; + seen.add(key); + deduped.push(item); + if (deduped.length >= options.limit) break; + } + return deduped; +} + +function formatMemoryLines(items: FindResultItem[]): string { + return items + .map((item, i) => { + const score = clampScore(item.score); + const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri; + const category = item.category ?? "memory"; + return `${i + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`; + }) + .join("\n"); +} + +// Query-aware ranking (ported from openclaw-plugin/memory-ranking.ts) +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 QUERY_TOKEN_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", +]); + +function buildQueryProfile(query: string) { + const text = query.trim(); + const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? []; + const tokens = allTokens.filter((t) => !QUERY_TOKEN_STOPWORDS.has(t)); + return { + tokens, + wantsPreference: PREFERENCE_QUERY_RE.test(text), + wantsTemporal: TEMPORAL_QUERY_RE.test(text), + }; +} + +function lexicalOverlapBoost(tokens: string[], text: string): number { + 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 rankForInjection(item: FindResultItem, query: ReturnType): number { + const baseScore = clampScore(item.score); + const abstract = (item.abstract ?? item.overview ?? "").trim(); + const leafBoost = item.level === 2 ? 0.12 : 0; + const cat = (item.category ?? "").toLowerCase(); + const eventBoost = query.wantsTemporal && (cat === "events" || item.uri.includes("/events/")) ? 0.1 : 0; + const prefBoost = query.wantsPreference && (cat === "preferences" || item.uri.includes("/preferences/")) ? 0.08 : 0; + const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`); + return baseScore + leafBoost + eventBoost + prefBoost + overlapBoost; +} + +function pickMemoriesForInjection(items: FindResultItem[], limit: number, queryText: string): FindResultItem[] { + if (items.length === 0 || limit <= 0) return []; + const query = buildQueryProfile(queryText); + const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query)); + + const deduped: FindResultItem[] = []; + const seen = new Set(); + for (const item of sorted) { + const key = (item.abstract ?? item.overview ?? "").trim().toLowerCase() || item.uri; + if (seen.has(key)) continue; + seen.add(key); + deduped.push(item); + } + + const leaves = deduped.filter((item) => item.level === 2); + 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; + picked.push(item); + } + return picked; +} + +// --------------------------------------------------------------------------- +// Shared search helpers +// --------------------------------------------------------------------------- + +async function searchBothScopes( + client: OpenVikingClient, + query: string, + limit: number, +): Promise { + const [userSettled, agentSettled] = await Promise.allSettled([ + client.find(query, { targetUri: "viking://user/memories", limit, scoreThreshold: 0 }), + client.find(query, { targetUri: "viking://agent/memories", limit, scoreThreshold: 0 }), + ]); + + const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] }; + const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] }; + + const all = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])]; + // Deduplicate by URI and keep only leaf memories + const unique = all.filter((m, i, self) => i === self.findIndex((o) => o.uri === m.uri)); + return unique.filter((m) => m.level === 2); +} + +function markRecalledMemoriesUsed(client: OpenVikingClient, contexts: string[]): void { + const uniqueContexts = [...new Set(contexts.filter((uri) => typeof uri === "string" && uri.length > 0))]; + if (uniqueContexts.length === 0) return; + + void (async () => { + let sessionId: string | undefined; + try { + sessionId = await client.createSession(); + await client.sessionUsed(sessionId, uniqueContexts); + await client.commitSession(sessionId); + } catch { + // Fire-and-forget usage tracking must never block or fail the caller. + } finally { + if (sessionId) { + await client.deleteSession(sessionId).catch(() => {}); + } + } + })(); +} + +// --------------------------------------------------------------------------- +// MCP Server +// --------------------------------------------------------------------------- + +const client = new OpenVikingClient(config.baseUrl, config.apiKey, config.agentId, config.timeoutMs); + +const server = new McpServer({ + name: "openviking-memory-codex", + version: "0.1.0", +}); + +// -- Tool: memory_recall -------------------------------------------------- + +server.tool( + "memory_recall", + "Search long-term memories from OpenViking. Use when you need past user preferences, facts, decisions, or any previously stored information.", + { + query: z.string().describe("Search query — describe what you want to recall"), + limit: z.number().optional().describe("Max results to return (default: 6)"), + score_threshold: z.number().optional().describe("Min relevance score 0-1 (default: 0.01)"), + target_uri: z.string().optional().describe("Search scope URI, e.g. viking://user/memories"), + }, + async ({ query, limit, score_threshold, target_uri }) => { + const recallLimit = limit ?? config.recallLimit; + const threshold = score_threshold ?? config.scoreThreshold; + const candidateLimit = Math.max(recallLimit * 4, 20); + + let leafMemories: FindResultItem[]; + if (target_uri) { + const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 }); + leafMemories = (result.memories ?? []).filter((m) => m.level === 2); + } else { + leafMemories = await searchBothScopes(client, query, candidateLimit); + } + + const processed = postProcessMemories(leafMemories, { limit: candidateLimit, scoreThreshold: threshold }); + const memories = pickMemoriesForInjection(processed, recallLimit, query); + + if (memories.length === 0) { + return { content: [{ type: "text" as const, text: "No relevant memories found in OpenViking." }] }; + } + + markRecalledMemoriesUsed(client, memories.map((memory) => memory.uri)); + + // Read full content for leaf memories + const lines = await Promise.all( + memories.map(async (item) => { + if (item.level === 2) { + try { + const content = await client.read(item.uri); + if (content?.trim()) return `- [${item.category ?? "memory"}] ${content.trim()}`; + } catch { /* fallback */ } + } + return `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`; + }), + ); + + return { + content: [{ + type: "text" as const, + text: `Found ${memories.length} relevant memories:\n\n${lines.join("\n")}\n\n---\n${formatMemoryLines(memories)}`, + }], + }; + }, +); + +// -- Tool: memory_store --------------------------------------------------- + +server.tool( + "memory_store", + "Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, decisions, or any information worth persisting across sessions.", + { + text: z.string().describe("The information to store as memory"), + role: z.string().optional().describe("Message role: 'user' (default) or 'assistant'"), + }, + async ({ text, role }) => { + const msgRole = role || "user"; + let sessionId: string | undefined; + try { + sessionId = await client.createSession(); + await client.addSessionMessage(sessionId, msgRole, text); + const extracted = await client.extractSessionMemories(sessionId); + + if (extracted.length === 0) { + return { + content: [{ + type: "text" as const, + text: "Memory stored but extraction returned 0 memories. The text may be too short or not contain extractable information. Check OpenViking server logs for details.", + }], + }; + } + + return { + content: [{ + type: "text" as const, + text: `Successfully extracted ${extracted.length} memory/memories from the provided text and stored them in OpenViking.`, + }], + }; + } finally { + if (sessionId) { + await client.deleteSession(sessionId).catch(() => {}); + } + } + }, +); + +// -- Tool: memory_forget -------------------------------------------------- + +server.tool( + "memory_forget", + "Delete a memory from OpenViking. Provide an exact URI for direct deletion, or a search query to find and delete matching memories.", + { + uri: z.string().optional().describe("Exact viking:// memory URI to delete"), + query: z.string().optional().describe("Search query to find the memory to delete"), + target_uri: z.string().optional().describe("Search scope URI (default: viking://user/memories)"), + }, + async ({ uri, query, target_uri }) => { + // Direct URI deletion + if (uri) { + if (!isMemoryUri(uri)) { + return { content: [{ type: "text" as const, text: `Refusing to delete non-memory URI: ${uri}` }] }; + } + await client.deleteUri(uri); + return { content: [{ type: "text" as const, text: `Deleted memory: ${uri}` }] }; + } + + if (!query) { + return { content: [{ type: "text" as const, text: "Please provide either a uri or query parameter." }] }; + } + + // Search then delete + const candidateLimit = 20; + let candidates: FindResultItem[]; + + if (target_uri) { + const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 }); + candidates = postProcessMemories(result.memories ?? [], { + limit: candidateLimit, + scoreThreshold: config.scoreThreshold, + leafOnly: true, + }).filter((item) => isMemoryUri(item.uri)); + } else { + const leafMemories = await searchBothScopes(client, query, candidateLimit); + candidates = postProcessMemories(leafMemories, { + limit: candidateLimit, + scoreThreshold: config.scoreThreshold, + leafOnly: true, + }).filter((item) => isMemoryUri(item.uri)); + } + + if (candidates.length === 0) { + return { content: [{ type: "text" as const, text: "No matching memories found. Try a more specific query." }] }; + } + + // Auto-delete if single strong match + const top = candidates[0]!; + if (candidates.length === 1 && clampScore(top.score) >= 0.85) { + await client.deleteUri(top.uri); + return { content: [{ type: "text" as const, text: `Deleted memory: ${top.uri}` }] }; + } + + // List candidates for confirmation + const list = candidates + .map((item) => `- ${item.uri} — ${item.abstract?.trim() || "?"} (${(clampScore(item.score) * 100).toFixed(0)}%)`) + .join("\n"); + + return { + content: [{ + type: "text" as const, + text: `Found ${candidates.length} candidate memories. Please specify the exact URI to delete:\n\n${list}`, + }], + }; + }, +); + +// -- Tool: memory_health -------------------------------------------------- + +server.tool( + "memory_health", + "Check whether the OpenViking memory server is reachable and healthy.", + {}, + async () => { + const ok = await client.healthCheck(); + return { + content: [{ + type: "text" as const, + text: ok + ? `OpenViking is healthy (${config.baseUrl})` + : `OpenViking is unreachable at ${config.baseUrl}. Please check if the server is running.`, + }], + }; + }, +); + +// --------------------------------------------------------------------------- +// Start +// --------------------------------------------------------------------------- + +const transport = new StdioServerTransport(); +await server.connect(transport); diff --git a/examples/codex-memory-plugin/tsconfig.json b/examples/codex-memory-plugin/tsconfig.json new file mode 100644 index 000000000..7f284c9a1 --- /dev/null +++ b/examples/codex-memory-plugin/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "outDir": "./servers", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "declaration": false, + "sourceMap": false + }, + "include": ["src/**/*.ts"] +}