Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

[codex] fix memory plugin recall and auth handling (#2676)

agent3757a143f0c1
diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjs
index fa7e1c845..0d3814452 100644
--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs
@@ -56,8 +56,8 @@ async function fetchJSON(path, init = {}) {
headers["Authorization"] = `Bearer ${cfg.apiKey}`;
headers["X-API-Key"] = cfg.apiKey;
}
- if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;
const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
const body = await res.json().catch(() => null);
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index bd06e5953..4d722bc0d 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -91,8 +91,8 @@ async function fetchJSON(path, init = {}) {
headers["Authorization"] = `Bearer ${cfg.apiKey}`;
headers["X-API-Key"] = cfg.apiKey;
}
- if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;
const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
const body = await res.json().catch(() => null);
@@ -212,59 +212,10 @@ function postProcess(items, limit, threshold) {
return result;
}
-// ---------------------------------------------------------------------------
-// User URI space resolution
-// ---------------------------------------------------------------------------
-
-const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
-let _userSpaceCache = "";
-
-async function resolveUserSpace() {
- if (_userSpaceCache) return _userSpaceCache;
-
- let fallbackSpace = "default";
- try {
- const status = await fetchJSON("/api/v1/system/status");
- if (status && typeof status.user === "string" && status.user.trim()) {
- fallbackSpace = status.user.trim();
- }
- } catch { /* fallback */ }
-
- try {
- const entries = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`);
- if (Array.isArray(entries)) {
- const spaces = entries
- .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]; }
- }
- }
- } catch { /* fallback */ }
-
- _userSpaceCache = fallbackSpace;
- return fallbackSpace;
-}
-
-async function resolveTargetUri(targetUri) {
- 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();
- return `viking://user/${space}/${parts.join("/")}`;
-}
-
async function searchScope(query, targetUri, limit, bucket = "memories") {
- const resolvedUri = await resolveTargetUri(targetUri);
- const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };
+ // Keep current-user shorthand here; the server canonicalizes it using the
+ // authenticated/trusted request context.
+ const body = { query, target_uri: targetUri, limit, score_threshold: 0 };
const result = await fetchJSON("/api/v1/search/find", {
method: "POST",
body: JSON.stringify(body),
diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjs
index 07f03ff3b..a13a22e13 100644
--- a/examples/codex-memory-plugin/scripts/config.mjs
+++ b/examples/codex-memory-plugin/scripts/config.mjs
@@ -26,6 +26,7 @@
* Connection / identity env vars:
* OPENVIKING_URL / OPENVIKING_BASE_URL
* OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN
+ * OPENVIKING_AUTH_MODE
* OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID
*
* Misc env vars:
@@ -67,12 +68,23 @@ function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj || {}, key);
}
+function normalizeAuthMode(val) {
+ const mode = str(val, "").toLowerCase();
+ return ["trusted", "api_key"].includes(mode) ? mode : "";
+}
+
export function loadConfig() {
const creds = resolveOpenVikingCredentials();
const { cliPath, ovFile, ovPath } = creds;
const configPath = cliPath || ovPath || null;
const cx = ovFile.codex || {};
+ const server = ovFile.server || {};
+ const explicitAuthMode = normalizeAuthMode(process.env.OPENVIKING_AUTH_MODE)
+ || normalizeAuthMode(cx.authMode)
+ || normalizeAuthMode(cx.auth_mode)
+ || normalizeAuthMode(server.auth_mode);
+ const authMode = explicitAuthMode || ((creds.account || creds.user) ? "trusted" : "api_key");
const debug = envBool("OPENVIKING_DEBUG") ?? (cx.debug === true);
const defaultLogPath = join(homedir(), ".openviking", "logs", "codex-hooks.log");
@@ -116,6 +128,8 @@ export function loadConfig() {
ovConfigPath: ovPath,
credentialSource: creds.credentialSource,
baseUrl: creds.baseUrl,
+ authMode,
+ sendIdentityHeaders: authMode === "trusted",
apiKey: creds.apiKey,
account: creds.account,
user: creds.user,
diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.mjs
index bdc688159..e0871f432 100644
--- a/examples/codex-memory-plugin/scripts/ov-credentials.mjs
+++ b/examples/codex-memory-plugin/scripts/ov-credentials.mjs
@@ -58,6 +58,23 @@ function hasCredentialFields(obj) {
].some((key) => typeof obj[key] === "string");
}
+function normalizeAuthMode(val) {
+ const mode = str(val, "").toLowerCase();
+ return ["trusted", "api_key"].includes(mode) ? mode : "";
+}
+
+function resolveAuthMode(creds, env = process.env) {
+ const cx = creds.ovFile.codex || {};
+ const server = creds.ovFile.server || {};
+ return (
+ normalizeAuthMode(env.OPENVIKING_AUTH_MODE) ||
+ normalizeAuthMode(cx.authMode) ||
+ normalizeAuthMode(cx.auth_mode) ||
+ normalizeAuthMode(server.auth_mode) ||
+ ((creds.account || creds.user) ? "trusted" : "api_key")
+ );
+}
+
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;
@@ -224,6 +241,7 @@ function printShellEnv() {
export function syncMcpConfig(file, env = process.env) {
const creds = resolveOpenVikingCredentials(env);
+ const authMode = resolveAuthMode(creds, env);
const j = JSON.parse(readFileSync(file, "utf-8"));
const s = j.mcpServers && j.mcpServers["openviking-memory"];
if (!s) return false;
@@ -244,10 +262,19 @@ export function syncMcpConfig(file, env = process.env) {
}
const headers = s.env_http_headers || {};
- const expectedHeaders = {
- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
- "X-OpenViking-User": "OPENVIKING_USER",
- };
+ const expectedHeaders = {};
+ if (authMode === "trusted" && creds.account) {
+ expectedHeaders["X-OpenViking-Account"] = "OPENVIKING_ACCOUNT";
+ } else if (headers["X-OpenViking-Account"]) {
+ delete headers["X-OpenViking-Account"];
+ changed = true;
+ }
+ if (authMode === "trusted" && creds.user) {
+ expectedHeaders["X-OpenViking-User"] = "OPENVIKING_USER";
+ } else if (headers["X-OpenViking-User"]) {
+ delete headers["X-OpenViking-User"];
+ changed = true;
+ }
// Actor-peer is only mapped when a peer is actually configured. Codex's MCP
// runtime treats unset env vars in env_http_headers as empty-string headers,
// which the OV side then has to disambiguate from "no peer scope". Match
@@ -291,6 +318,10 @@ function main() {
process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
return;
}
+ if (cmd === "has-peer-id") {
+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
+ return;
+ }
if (cmd === "sync-mcp") {
const file = process.argv[3];
if (!file) {
@@ -301,7 +332,7 @@ function main() {
syncMcpConfig(file);
return;
}
- process.stderr.write("usage: ov-credentials.mjs <shell-env|mcp-url|has-api-key|sync-mcp>\n");
+ process.stderr.write("usage: ov-credentials.mjs <shell-env|mcp-url|has-api-key|has-peer-id|sync-mcp>\n");
process.exitCode = 2;
}
diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs
index 1e78b2c64..1082d1088 100644
--- a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs
+++ b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs
@@ -117,8 +117,6 @@ test("syncMcpConfig with peerId maps actor-peer header", async () => {
assert.equal(server.url, "https://ov.example.com/mcp");
assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");
assert.deepEqual(server.env_http_headers, {
- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
- "X-OpenViking-User": "OPENVIKING_USER",
"X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID",
});
} finally {
@@ -149,10 +147,7 @@ test("syncMcpConfig without peerId omits actor-peer header (symmetric to bearer)
assert.equal(server.url, "https://ov.example.com/mcp");
assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");
- assert.deepEqual(server.env_http_headers, {
- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
- "X-OpenViking-User": "OPENVIKING_USER",
- });
+ assert.deepEqual(server.env_http_headers, {});
assert.equal(
Object.prototype.hasOwnProperty.call(server.env_http_headers, "X-OpenViking-Actor-Peer"),
false,
@@ -162,6 +157,78 @@ test("syncMcpConfig without peerId omits actor-peer header (symmetric to bearer)
}
});
+test("syncMcpConfig in trusted mode maps configured identity headers", async () => {
+ const { dir, path } = await tempJson("ov-creds-mcp-trusted-auth-", {
+ url: "https://ov.example.com",
+ api_key: "cli-key",
+ account: "default",
+ user: "zeus",
+ });
+ const mcpPath = join(dir, ".mcp.json");
+ await writeFile(mcpPath, JSON.stringify({
+ mcpServers: {
+ "openviking-memory": {
+ url: "__OPENVIKING_MCP_URL__",
+ bearer_token_env_var: "STALE_KEY",
+ env_http_headers: {},
+ },
+ },
+ }, null, 2) + "\n");
+
+ try {
+ syncMcpConfig(mcpPath, {
+ OPENVIKING_CLI_CONFIG_FILE: path,
+ OPENVIKING_AUTH_MODE: "trusted",
+ });
+ const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));
+ const server = rendered.mcpServers["openviking-memory"];
+
+ assert.deepEqual(server.env_http_headers, {
+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
+ "X-OpenViking-User": "OPENVIKING_USER",
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("syncMcpConfig in api_key mode omits trusted identity headers", async () => {
+ const { dir, path } = await tempJson("ov-creds-mcp-apikey-auth-", {
+ url: "https://ov.example.com",
+ api_key: "cli-key",
+ account: "default",
+ user: "zeus",
+ });
+ const mcpPath = join(dir, ".mcp.json");
+ await writeFile(mcpPath, JSON.stringify({
+ mcpServers: {
+ "openviking-memory": {
+ url: "__OPENVIKING_MCP_URL__",
+ bearer_token_env_var: "STALE_KEY",
+ env_http_headers: {
+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
+ "X-OpenViking-User": "OPENVIKING_USER",
+ },
+ },
+ },
+ }, null, 2) + "\n");
+
+ try {
+ syncMcpConfig(mcpPath, {
+ OPENVIKING_CLI_CONFIG_FILE: path,
+ OPENVIKING_AUTH_MODE: "api_key",
+ });
+ const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));
+ const server = rendered.mcpServers["openviking-memory"];
+
+ assert.equal(server.url, "https://ov.example.com/mcp");
+ assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");
+ assert.deepEqual(server.env_http_headers, {});
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
test("syncMcpConfig drops stale actor-peer header when peer is unset", async () => {
const { dir, path } = await tempJson("ov-creds-mcp-drop-peer-", {
url: "https://ov.example.com",
diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
index ce25486d6..b662f1226 100644
--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
@@ -51,8 +51,8 @@ async function fetchJSON(path, init = {}) {
headers["Authorization"] = `Bearer ${cfg.apiKey}`;
headers["X-API-Key"] = cfg.apiKey;
}
- if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;
const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
const body = await res.json().catch(() => null);
diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
index a50172ab9..48e99bc77 100644
--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs
+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
@@ -85,8 +85,8 @@ async function fetchJSON(path, init = {}) {
headers["Authorization"] = `Bearer ${cfg.apiKey}`;
headers["X-API-Key"] = cfg.apiKey;
}
- if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;
const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
const body = await res.json().catch(() => null);
diff --git a/examples/codex-memory-plugin/setup-helper/install.sh b/examples/codex-memory-plugin/setup-helper/install.sh
index e1c55d1cd..5239ea728 100755
--- a/examples/codex-memory-plugin/setup-helper/install.sh
+++ b/examples/codex-memory-plugin/setup-helper/install.sh
@@ -352,6 +352,14 @@ detect_api_key() {
}
HAS_API_KEY="$(detect_api_key)"
+# Detect whether a peer id is configured. Older/new local setups may not use
+# peer-aware identity yet, so validation must accept both header-present and
+# header-absent MCP cache output depending on the actual config.
+detect_peer_id() {
+ OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" has-peer-id 2>/dev/null || echo "0"
+}
+HAS_PEER_ID="$(detect_peer_id)"
+
render_plugin_cache() {
mkdir -p "$(dirname "$CACHE_DIR")"
rm -rf "$CACHE_DIR"
@@ -588,7 +596,9 @@ validate_plugin_install() {
if [ ! -L "$marketplace_link" ] || [ "$(readlink "$marketplace_link" 2>/dev/null || true)" != "$PLUGIN_DIR" ]; then
issues+=("marketplace symlink does not point at $PLUGIN_DIR")
fi
- if ! codex plugin list 2>/dev/null | grep -E -q "${PLUGIN_ID}[[:space:]]+installed, enabled"; then
+ # Codex has printed both `installed, enabled` and `(installed, enabled)`
+ # across versions; accept either to avoid false-negative install failures.
+ if ! codex plugin list 2>/dev/null | grep -E -q "${PLUGIN_ID}[[:space:]]+\(?installed, enabled\)?"; then
issues+=("codex plugin list does not show $PLUGIN_ID as installed, enabled")
fi
if [ ! -d "$CACHE_DIR" ]; then
@@ -610,7 +620,12 @@ validate_plugin_install() {
if [ "$HAS_API_KEY" != "1" ] && grep -q "bearer_token_env_var" "$mcp_json"; then
issues+=("cached .mcp.json keeps bearer_token_env_var without configured API key")
fi
- grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json" || issues+=("cached .mcp.json is missing X-OpenViking-Actor-Peer header mapping")
+ if [ "$HAS_PEER_ID" = "1" ] && ! grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json"; then
+ issues+=("cached .mcp.json is missing X-OpenViking-Actor-Peer header mapping despite configured peer")
+ fi
+ if [ "$HAS_PEER_ID" != "1" ] && grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json"; then
+ issues+=("cached .mcp.json keeps X-OpenViking-Actor-Peer without configured peer")
+ fi
fi
for script in \