Skip to content

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

fix(plugins): resolve one connection for every plugin's hooks and MCP proxy (#5132)

t0saki0ec8d2599661
diff --git a/agent-plugins/README.md b/agent-plugins/README.md
index 6e9e10a61..134ceb47b 100644
--- a/agent-plugins/README.md
+++ b/agent-plugins/README.md
@@ -37,8 +37,8 @@ OpenViking already speaks streamable HTTP at `/mcp`, but a `streamable-http` ent
Highest to lowest priority (same chain as the `ov` CLI and the other OpenViking plugins):
1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
-2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account`, `user`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
-3. `~/.openviking/ov.conf` `server` section (`url` or `host`/`port`, `root_api_key`) — override the path with `OPENVIKING_CONFIG_FILE`
+2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account`, `user`, then the `plugin.agent_plugins` and `plugin` keys) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
+3. `~/.openviking/ov.conf` `agent_plugins` section, then its `server` section (`url` or `host`/`port`, `root_api_key`) — override the path with `OPENVIKING_CONFIG_FILE`
4. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
Config file changes are picked up by the running proxy without a restart. Debugging: set `OPENVIKING_DEBUG=1` to log JSON lines to `~/.openviking/logs/agent-plugins.log` (path override: `OPENVIKING_DEBUG_LOG`).
@@ -76,6 +76,6 @@ node --test agent-plugins/plugin.test.mjs
node examples/memory-plugin-shared/sync.mjs
```
-`examples/memory-plugin-shared/sync.test.mjs` fails if they drift, and pins this package to the connection half of the shared runtime: `servers/mcp-proxy.mjs` resolves everything through `buildProxyConnection()` in `shared/credentials.mjs`, so the hook-tuning knobs — which this spec has no hooks to run — never enter the bundle.
+`examples/memory-plugin-shared/sync.test.mjs` fails if they drift, and pins this package to the connection half of the shared runtime: `servers/mcp-proxy.mjs` resolves everything through `buildProxyConnection()` in `shared/credentials.mjs` — the same `resolveConnection()` every other plugin's hooks and proxy use — so the hook-tuning knobs — which this spec has no hooks to run — never enter the bundle.
Both test files run in CI via `.github/workflows/pr.yml`.
diff --git a/agent-plugins/plugin.json b/agent-plugins/plugin.json
index 9226437c5..6a2b167db 100644
--- a/agent-plugins/plugin.json
+++ b/agent-plugins/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "openviking",
- "version": "0.1.1",
+ "version": "0.1.2",
"description": "Semantic long-term memory and context engine for coding agents. Recall prior knowledge with the find/search/read MCP tools and persist durable facts with remember/write, backed by an OpenViking server.",
"author": {
"name": "Volcano Engine",
diff --git a/agent-plugins/servers/mcp-proxy.mjs b/agent-plugins/servers/mcp-proxy.mjs
index ac80a0e52..aa7992b19 100644
--- a/agent-plugins/servers/mcp-proxy.mjs
+++ b/agent-plugins/servers/mcp-proxy.mjs
@@ -18,29 +18,15 @@ import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { buildProxyConnection } from "./shared/credentials.mjs";
import { createLogger } from "./shared/debug-log.mjs";
-import { buildMcpProxyConfig, resolveMcpActorPeerId } from "./shared/mcp-proxy-config.mjs";
+import { toMcpProxyConfig } from "./shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "./shared/mcp-proxy-core.mjs";
-function readProxyConfig() {
+export function readProxyConfig(env = process.env) {
const cfg = buildProxyConnection("agent-plugins", {
+ env,
manifestUrl: new URL("../plugin.json", import.meta.url),
});
- return buildMcpProxyConfig({
- baseUrl: cfg.baseUrl,
- mcpUrl: cfg.mcpUrl,
- apiKey: cfg.apiKey,
- account: cfg.account,
- user: cfg.user,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
- peerId: resolveMcpActorPeerId(cfg),
- userAgent: cfg.userAgent,
- timeoutMs: cfg.timeoutMs,
- debug: cfg.debug,
- debugLogPath: cfg.debugLogPath,
- credentialSource: cfg.credentialSource,
- credentialPath: cfg.credentialPath,
- watchedPaths: cfg.watchedPaths,
- });
+ return toMcpProxyConfig(cfg, { env });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
diff --git a/agent-plugins/servers/shared/credentials.mjs b/agent-plugins/servers/shared/credentials.mjs
index 0ab2d984d..fea82315c 100644
--- a/agent-plugins/servers/shared/credentials.mjs
+++ b/agent-plugins/servers/shared/credentials.mjs
@@ -2,11 +2,9 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { fileURLToPath } from "node:url";
const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
-const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
const DEFAULT_TIMEOUT_MS = 15000;
const MIN_TIMEOUT_MS = 1000;
@@ -111,17 +109,74 @@ export function loadCredentialFiles(env = process.env) {
}
/**
- * The calling harness's own section of ov.conf.
- *
+ * The environment variables that name part of the connection. Any one of them
+ * set is what takes the chain off ovcli.conf in `auto` mode, so a variable
+ * that only tunes how the chain runs must not be on this list: an
+ * `OPENVIKING_AUTH_MODE` exported on its own would otherwise unpin the file.
+ */
+export const CREDENTIAL_ENV_VARS = [
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_MCP_URL",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+ "OPENVIKING_PEER_ID",
+];
+
+/** Every environment variable `resolveConnection` reads. */
+export const CONNECTION_ENV_VARS = [
+ ...CREDENTIAL_ENV_VARS,
+ "OPENVIKING_AUTH_MODE",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
+ "OPENVIKING_CLI_CONFIG_FILE",
+ "OPENVIKING_CONFIG_FILE",
+];
+
+function isSection(value) {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/**
* ov.conf spells its sections snake_case while a host may call itself
* `claude-code` or `trae-cn`, so both spellings land on the same block. The
* normalization stays inline rather than importing `config-schema.mjs`, which
* the portable agent-plugins bundle would then have to ship as well.
*/
+function sectionKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** The calling harness's own section of ov.conf. */
function harnessSection(ovFile, harness) {
- const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
- const section = key ? ovFile[key] : null;
- return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+ const section = ovFile[sectionKey(harness)];
+ return isSection(section) ? section : {};
+}
+
+/**
+ * ovcli.conf's `plugin` section as this harness sees it: the shared scalars,
+ * then `plugin.<harness>` over them in both spellings, the hyphenated one last.
+ * `loadPluginSettings` merges the same way for every other knob, and the two
+ * must agree or a key would win in the hooks and lose here.
+ */
+function pluginSection(cliFile, harness) {
+ const plugin = isSection(cliFile.plugin) ? cliFile.plugin : {};
+ const merged = {};
+ for (const [key, value] of Object.entries(plugin)) {
+ if (!isSection(value)) merged[key] = value;
+ }
+ const key = sectionKey(harness);
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ if (candidate && isSection(plugin[candidate])) Object.assign(merged, plugin[candidate]);
+ }
+ return merged;
+}
+
+/** A knob-file scalar as the schema coerces a string knob: `12345` is "12345". */
+function scalar(value) {
+ return value === undefined || value === null ? "" : String(value).trim();
}
const AUTH_MODES = ["trusted", "api_key"];
@@ -131,22 +186,8 @@ function normalizeAuthMode(value) {
return AUTH_MODES.includes(mode) ? mode : "";
}
-/**
- * Which auth mode the server is in, and with it whether the identity headers
- * may go on the wire.
- *
- * An `api_key` server reads the account and the user out of the key and ignores
- * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
- * every proxy on the path who the operator is and buys nothing. A named mode
- * wins; ov.conf's server block answers next; failing both, a credential layer
- * that supplied an identity at all means the deployment expects one.
- */
-export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
- const server = ovFile.server || {};
- const authMode = normalizeAuthMode(settings.authMode)
- || normalizeAuthMode(server.auth_mode)
- || ((account || user) ? "trusted" : "api_key");
- return { authMode, sendIdentityHeaders: authMode === "trusted" };
+function authModeIn(section) {
+ return normalizeAuthMode(section.authMode) || normalizeAuthMode(section.auth_mode);
}
function sourceMode(env) {
@@ -158,135 +199,130 @@ function sourceMode(env) {
}
function hasEnvCredentialFields(env) {
- return Boolean(
- str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
- str(env.OPENVIKING_MCP_URL, "") ||
- str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(env.OPENVIKING_USER, "") ||
- str(env.OPENVIKING_PEER_ID, ""),
- );
+ return CREDENTIAL_ENV_VARS.some((name) => str(env[name], ""));
}
-function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
- const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
- const cliUrl = str(cliFile.url, "");
-
- if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
- if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
- if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
-
- const server = ovFile.server || {};
- const ovUrl = str(server.url, "");
- if (ovUrl) return ovUrl.replace(/\/+$/, "");
+function trimSlash(value) {
+ return value.replace(/\/+$/, "");
+}
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
- return `http://${host}:${port}`;
+/** The first layer that holds a value, with the source label and file it names. */
+function firstLayer(layers) {
+ for (const [value, source, path = ""] of layers) {
+ if (value) return { value, source, path };
+ }
+ return { value: "", source: "none", path: "" };
}
/**
- * `harness` names whose ov.conf section supplies the legacy fallback. It sits
- * where it always did — after ovcli.conf, before `server.root_api_key` — but a
- * harness now reads its own section instead of every one of them reading
- * codex's. The default keeps codex, the only caller that never passes one.
+ * The one connection a harness has: which server, which key, whose identity,
+ * and whether that identity goes on the wire. Hooks reach it through
+ * `buildPluginConfig`, every MCP proxy through the same loader or through
+ * `buildProxyConnection`, so the two sides of one harness cannot disagree.
+ *
+ * Only three kinds of input count: what an embedding host named (`hostInput`),
+ * the environment, and the two files under `~/.openviking`. The working
+ * directory never does — an MCP proxy starts wherever its host launches it.
*
- * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
- * section named, which this module cannot read for itself: resolving that
- * section needs the knob schema, and the portable bundles would then have to
- * ship it. All three rank where the file they come from ranks — under
- * ovcli.conf's own fields, over ov.conf.
+ * ovcli.conf pins the chain when it names a url, key, identity or peer and the
+ * environment names none of those; pinned, the environment's credentials no
+ * longer apply. `OPENVIKING_CREDENTIAL_SOURCE` forces either side, and forced
+ * to `env` no file is read at all — which is what lets a parent process hand a
+ * resolved connection, including an empty key, to a child verbatim. Every chain
+ * runs host → env (unpinned) → ovcli.conf → its `plugin.<harness>` and
+ * `plugin` keys → ov.conf's harness section; the key then ends at
+ * `server.root_api_key`, which a pinned chain reaches only with
+ * `rootKeyFallback`, and the identity skips ov.conf's harness section when
+ * pinned. The auth mode reads the environment in either mode, then the
+ * `plugin` keys, the harness section and `server.auth_mode`; failing all of
+ * them, an identity from any layer means the deployment expects one.
*/
-export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
- const files = loadCredentialFiles(env);
+export function resolveConnection(harness, {
+ env = process.env,
+ files = null,
+ hostInput = {},
+ rootKeyFallback = false,
+} = {}) {
+ const name = str(harness, "");
+ const loaded = files || loadCredentialFiles(env);
+ const { cliFile, ovFile, cliPath, ovPath } = loaded;
+ const host = hostInput || {};
const mode = sourceMode(env);
const envHasCredentials = hasEnvCredentialFields(env);
- const useCli = mode === "cli" ||
- (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
- const cx = harnessSection(files.ovFile, harness);
- const server = files.ovFile.server || {};
-
- const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
-
- const pluginApiKey = str(plugin?.apiKey, "");
- const apiKey = useCli
- ? (str(files.cliFile.api_key, "") || pluginApiKey)
- : (
- str(env.OPENVIKING_BEARER_TOKEN, "") ||
- str(env.OPENVIKING_API_KEY, "") ||
- str(files.cliFile.api_key, "") ||
- pluginApiKey ||
- str(cx.apiKey, "") ||
- str(server.root_api_key, "")
- );
-
- const pluginAccount = str(plugin?.accountId, "");
- const account = useCli
- ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
- : (
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
- pluginAccount ||
- str(cx.accountId, "")
- );
-
- const pluginUser = str(plugin?.userId, "");
- const user = useCli
- ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
- : (
- str(env.OPENVIKING_USER, "") ||
- str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
- pluginUser ||
- str(cx.userId, "")
- );
-
- const peerId = useCli
- ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
- : (
- str(env.OPENVIKING_PEER_ID, "") ||
- str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
- str(cx.peerId, str(cx.peer_id, ""))
- );
-
- const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
- const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
-
- // Which layer actually supplied the api_key, following the same chain, and
- // the file behind it — empty when the key came from the environment or was
- // never found. `apiKeySource` is what a doctor and a 401 hint report; the
- // credential *source* beside it is the mode the chain ran in, not a file.
- let apiKeySource = "none";
- let credentialPath = "";
- if (apiKey) {
- if (useCli) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
- apiKeySource = "env";
- } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else {
- apiKeySource = "ov";
- credentialPath = files.ovPath;
- }
- }
+ const pinned = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && Boolean(cliPath) && hasCredentialFields(cliFile));
+ const unpinned = (layer) => (pinned ? [] : [layer]);
+ const fromFiles = mode !== "env";
+ const filed = (...layers) => (fromFiles ? layers : []);
+ const plugin = pluginSection(cliFile, name);
+ const section = harnessSection(ovFile, name);
+ const server = isSection(ovFile.server) ? ovFile.server : {};
+
+ const key = firstLayer([
+ [str(host.apiKey, ""), "host"],
+ ...unpinned([str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")), "env"]),
+ ...filed(
+ [str(cliFile.api_key, ""), "ovcli", cliPath],
+ [scalar(plugin.apiKey), "ovcli", cliPath],
+ [scalar(section.apiKey), "ov", ovPath],
+ ),
+ ...((pinned && !rootKeyFallback) ? [] : filed([str(server.root_api_key, ""), "ov", ovPath])),
+ ]);
+
+ const identity = (hostValue, envName, cliValue, knob) => firstLayer([
+ [str(hostValue, ""), "host"],
+ ...unpinned([str(env[envName], ""), "env"]),
+ ...filed([cliValue, "ovcli", cliPath], [scalar(plugin[knob]), "ovcli", cliPath]),
+ ...(pinned ? [] : filed([str(section[knob], ""), "ov", ovPath])),
+ ]).value;
+ const account = identity(host.account, "OPENVIKING_ACCOUNT", str(cliFile.account, str(cliFile.account_id, "")), "accountId");
+ const user = identity(host.user, "OPENVIKING_USER", str(cliFile.user, str(cliFile.user_id, "")), "userId");
+
+ const peerId = firstLayer([
+ ...unpinned([str(env.OPENVIKING_PEER_ID, ""), "env"]),
+ ...filed([str(cliFile.actor_peer_id, str(cliFile.peer_id, "")), "ovcli"]),
+ ...(pinned ? [] : filed([str(section.peerId, str(section.peer_id, "")), "ov"])),
+ ]).value;
+
+ const authMode = normalizeAuthMode(host.authMode)
+ || normalizeAuthMode(env.OPENVIKING_AUTH_MODE)
+ || (fromFiles && (authModeIn(plugin) || authModeIn(section) || normalizeAuthMode(server.auth_mode)))
+ || ((account || user) ? "trusted" : "api_key");
+
+ const hostBaseUrl = trimSlash(str(host.baseUrl, ""));
+ const envUrl = pinned ? "" : str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const fileUrl = fromFiles ? (str(cliFile.url, "") || str(server.url, "")) : "";
+ const baseUrl = hostBaseUrl || trimSlash(envUrl || fileUrl) || serverAddress(fromFiles ? server : {});
+ const envMcpUrl = pinned ? "" : str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (!hostBaseUrl && envMcpUrl) ? envMcpUrl : `${baseUrl}/mcp`;
return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- apiKeySource,
- credentialPath,
+ ...loaded,
+ harness: name,
+ credentialSource: pinned ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
baseUrl,
mcpUrl,
- apiKey,
+ apiKey: key.value,
account,
user,
peerId,
- hasApiKey: Boolean(apiKey),
+ authMode,
+ sendIdentityHeaders: authMode === "trusted",
+ hasApiKey: Boolean(key.value),
+ // Which layer supplied the key and the file behind it, empty when the key
+ // came from the host or the environment. A doctor and a 401 hint report it;
+ // `credentialSource` is the mode the chain ran in, not a file.
+ apiKeySource: key.source,
+ credentialPath: key.path,
};
}
+function serverAddress(server) {
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
function envFlag(env, name) {
const raw = str(env[name], "").toLowerCase();
return raw === "1" || raw === "true" || raw === "yes";
@@ -304,9 +340,8 @@ function clampTimeout(value) {
* `buildPluginConfig` answers the same question one layer up, but reaching it
* means vendoring the knob schema and the workspace layers — a closure the
* portable agent-plugins bundle would carry in git to send one HTTP header.
- * This is the connection half alone: the credential chain, the auth mode that
- * decides whether the identity headers may go on the wire, the User-Agent, the
- * request timeout, and the debug log.
+ * This is the same connection plus what a proxy adds to it: the User-Agent,
+ * the request timeout, and the debug log.
*
* The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
* chain to itself. A portable package has no installer to migrate anyone, so
@@ -314,62 +349,27 @@ function clampTimeout(value) {
*/
export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
const name = str(harness);
- const credentials = resolveOpenVikingCredentials(env, name);
-
- let { apiKey, apiKeySource, credentialPath } = credentials;
- if (!apiKey) {
- apiKey = str(credentials.ovFile?.server?.root_api_key);
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
-
+ const connection = resolveConnection(name, { env, rootKeyFallback: true });
return {
harness: name,
userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
- baseUrl: credentials.baseUrl,
- mcpUrl: credentials.mcpUrl,
- apiKey,
- account: credentials.account,
- user: credentials.user,
- peerId: credentials.peerId,
- ...resolveAuthMode({
- settings: { authMode: env.OPENVIKING_AUTH_MODE },
- ovFile: credentials.ovFile,
- account: credentials.account,
- user: credentials.user,
- }),
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ baseUrl: connection.baseUrl,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
+ account: connection.account,
+ user: connection.user,
+ peerId: connection.peerId,
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
debug: envFlag(env, "OPENVIKING_DEBUG"),
debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
|| join(homedir(), ".openviking", "logs", `${name}.log`),
};
}
-
-function main() {
- const cmd = process.argv[2] || "";
- if (cmd === "mcp-url") {
- process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
- return;
- }
- if (cmd === "has-api-key") {
- process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
- return;
- }
- if (cmd === "has-peer-id") {
- process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
- return;
- }
- process.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
- process.exitCode = 2;
-}
-
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- main();
-}
diff --git a/agent-plugins/servers/shared/mcp-proxy-config.mjs b/agent-plugins/servers/shared/mcp-proxy-config.mjs
index c1e527967..e4f2428cc 100644
--- a/agent-plugins/servers/shared/mcp-proxy-config.mjs
+++ b/agent-plugins/servers/shared/mcp-proxy-config.mjs
@@ -12,9 +12,56 @@
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
+import { CONNECTION_ENV_VARS, CREDENTIAL_ENV_VARS } from "./credentials.mjs";
+
export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
const MIN_PROXY_TIMEOUT_MS = 1000;
+/**
+ * Every variable that changes what an MCP proxy sends. Hooks inherit their
+ * host's whole environment; a host that hands its MCP servers an allowlist
+ * instead (Codex's `env_vars`) has to name each of these, or the proxy
+ * resolves a different connection from the hooks beside it.
+ */
+export const MCP_PROXY_ENV_VARS = [
+ ...CONNECTION_ENV_VARS,
+ "OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
+ "OPENVIKING_RECALL_PEER_SCOPE",
+ "OPENVIKING_TIMEOUT_MS",
+ "OPENVIKING_DEBUG",
+ "OPENVIKING_DEBUG_LOG",
+ "OPENVIKING_EXTRA_HEADERS",
+];
+
+/**
+ * A resolved connection as the environment of a child proxy process.
+ *
+ * The other way across the process boundary, for a host that cannot hand its
+ * MCP servers the inputs (DSH drops credential-shaped names from what a child
+ * inherits): the parent resolves once and the child reads the answer back. The
+ * forced `env` source makes that exact — the child reads no file, so a key the
+ * parent left empty stays empty instead of falling through to
+ * `server.root_api_key`. Every credential variable is written, the empty ones
+ * too, because the rest of the parent's environment still reaches the child:
+ * an `OPENVIKING_ACCOUNT` the parent's pinned chain ignored must not fill the
+ * gap there.
+ */
+export function forwardConnectionEnv(connection) {
+ const env = Object.fromEntries(CREDENTIAL_ENV_VARS.map((name) => [name, ""]));
+ return {
+ ...env,
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: connection.baseUrl,
+ OPENVIKING_MCP_URL: connection.mcpUrl,
+ OPENVIKING_API_KEY: connection.apiKey || "",
+ OPENVIKING_ACCOUNT: connection.account || "",
+ OPENVIKING_USER: connection.user || "",
+ OPENVIKING_PEER_ID: connection.peerId || "",
+ OPENVIKING_AUTH_MODE: connection.authMode,
+ };
+}
+
export function trimSlash(value) {
return String(value || "").replace(/\/+$/, "");
}
@@ -55,7 +102,7 @@ export function defaultCredentialPaths(env = process.env) {
* start: the proxy is what carries every memory tool, and taking those away
* because a scope preference cannot be honoured costs the user far more than
* the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
+ * (dsh, `mcp-env.mjs`) can satisfy this without the user setting it.
*/
export function resolveMcpActorPeerId({
peerId = "",
@@ -192,3 +239,38 @@ export function buildMcpProxyConfig({
extraHeaders: resolvedExtraHeaders,
};
}
+
+/**
+ * The proxy config for a resolved harness config, mapped in one place.
+ *
+ * Every proxy used to copy fields out of its loader by hand, and the copies
+ * drifted: two dropped `mcpUrl`, so `OPENVIKING_MCP_URL` reached the hooks and
+ * not the tools. `cfg` is what `buildPluginConfig` or `buildProxyConnection`
+ * returned. `peerId` replaces the actor peer only for a harness whose parent
+ * process resolved it (dsh); everywhere else a long-lived proxy may send one
+ * only when actor-scoped recall asks for it.
+ */
+export function toMcpProxyConfig(cfg, {
+ env = process.env,
+ peerId = undefined,
+ debug = cfg.debug,
+ debugLogPath = cfg.debugLogPath,
+} = {}) {
+ return buildMcpProxyConfig({
+ baseUrl: cfg.baseUrl,
+ mcpUrl: cfg.mcpUrl,
+ apiKey: cfg.apiKey,
+ account: cfg.account,
+ user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
+ peerId: peerId === undefined ? resolveMcpActorPeerId(cfg) : peerId,
+ userAgent: cfg.userAgent,
+ timeoutMs: cfg.timeoutMs,
+ debug,
+ debugLogPath,
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.credentialPath || "",
+ watchedPaths: [cfg.cliPath, cfg.ovPath],
+ env,
+ });
+}
diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.md
index 1e50535e9..9e958ec17 100644
--- a/docs/en/agent-integrations/04-codex.md
+++ b/docs/en/agent-integrations/04-codex.md
@@ -73,7 +73,7 @@ Credential source: env vars win by default — when any `OPENVIKING_*` credentia
| `OPENVIKING_URL` / `OPENVIKING_BASE_URL` | — | Full server URL |
| `OPENVIKING_API_KEY` | — | API key (sent as `Authorization: Bearer`) |
| `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | Active CLI config to use for hooks, MCP, and child `ov` commands |
-| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | `auto` prefers env-var credentials when any are set; `cli` forces the active ovcli config, `env` forces env vars |
+| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | `auto` prefers env-var credentials when any are set; `cli` forces the active ovcli config; `env` reads env vars only, and neither config file |
| `OPENVIKING_NO_AUTO_INJECT` | `false` | Disable fixed session-start profile/background injection without disabling per-prompt recall |
| `OPENVIKING_PROFILE_TOKEN_BUDGET` | `10000` | CJK-aware token budget for `profile.md` plus `preferences/` and `entities/` indexes |
| `OPENVIKING_CODEX_IDLE_TTL_MS` | `1800000` | SessionStart idle-TTL sweep threshold |
diff --git a/docs/en/agent-integrations/15-agent-plugins.md b/docs/en/agent-integrations/15-agent-plugins.md
index 279fce91a..0e0a0fac1 100644
--- a/docs/en/agent-integrations/15-agent-plugins.md
+++ b/docs/en/agent-integrations/15-agent-plugins.md
@@ -35,15 +35,15 @@ OpenViking already speaks streamable HTTP at `/mcp`, but a `streamable-http` ent
Highest to lowest priority — the same chain as the `ov` CLI and the other OpenViking plugins:
-1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_MCP_URL`, `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
-2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account` / `account_id`, `user` / `user_id`, `actor_peer_id` / `peer_id`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
-3. `~/.openviking/ov.conf`, `agent_plugins` section (`apiKey`, `accountId`, `userId`, `peerId`) — override the path with `OPENVIKING_CONFIG_FILE`
+1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_MCP_URL`, `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`, `OPENVIKING_AUTH_MODE`
+2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account` / `account_id`, `user` / `user_id`, `actor_peer_id` / `peer_id`), then its `plugin.agent_plugins` and shared `plugin` keys (`apiKey`, `accountId`, `userId`, `authMode`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
+3. `~/.openviking/ov.conf`, `agent_plugins` section (`apiKey`, `accountId`, `userId`, `peerId`, `authMode`) — override the path with `OPENVIKING_CONFIG_FILE`
4. `~/.openviking/ov.conf`, `server` section (`url`, or `host` / `port`, and `root_api_key`)
5. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
`OPENVIKING_MCP_URL` replaces the derived `<url>/mcp` endpoint, not the base URL.
-`OPENVIKING_CREDENTIAL_SOURCE` (or `OPENVIKING_CREDENTIALS_SOURCE`) pins the chain to one end: `env` for the environment, `cli` (also `ovcli` / `file` / `config`) for ovcli.conf. The default `auto` pins it to ovcli.conf when that file carries credentials and none of the variables above is set, and runs the whole chain otherwise. While the chain is pinned to ovcli.conf, the environment, `OPENVIKING_MCP_URL` and the `agent_plugins` section are all skipped; `server.root_api_key` still answers when ovcli.conf carries no key of its own, so an install that names only a `url` there keeps the key it has always used.
+`OPENVIKING_CREDENTIAL_SOURCE` (or `OPENVIKING_CREDENTIALS_SOURCE`) pins the chain to one end: `env` for the environment, `cli` (also `ovcli` / `file` / `config`) for ovcli.conf. The default `auto` pins it to ovcli.conf when that file carries credentials and none of the variables above is set, and runs the whole chain otherwise. While the chain is pinned to ovcli.conf, the environment's credentials and `OPENVIKING_MCP_URL` are skipped. A key still falls through the `plugin` keys, the `agent_plugins` section and finally `server.root_api_key`, so an install that names only a `url` there keeps the key it has always used; the account and user stop at the `plugin` keys. `env` reads neither file.
```json
// ~/.openviking/ovcli.conf
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index 8d7da322c..de510d7e6 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -202,12 +202,13 @@ Four parallel credential-resolution systems coexist within the codebase, each ut
Family A resolves credentials in the following order (refer to individual profile cards for other families):
-1. The resolution mode is controlled by `OPENVIKING_CREDENTIAL_SOURCE` (aliased as `_CREDENTIALS_SOURCE`), accepting values of `env|cli|auto` (defaults to `auto`).
-2. **`auto` prioritizes environment variables**: If any environment credential field is present, the entire resolution process relies on the environment. Only when all environment fields are empty, and an `ovcli.conf` file exists with credential fields, does the system fall back to the configuration file (meaning the key, account, user, and peer are then exclusively sourced from the file).
+1. The resolution mode is controlled by `OPENVIKING_CREDENTIAL_SOURCE` (aliased as `_CREDENTIALS_SOURCE`), accepting values of `env|cli|auto` (defaults to `auto`). Forced to `env`, the connection reads neither file: an unset variable stays empty, and the URL defaults to `http://127.0.0.1:1933`. The `peerId` setting still resolves through its own layers.
+2. **`auto` prioritizes environment variables**: If any environment credential field (`URL`, `BASE_URL`, `MCP_URL`, `BEARER_TOKEN`, `API_KEY`, `ACCOUNT`, `USER`, `PEER_ID`) is present, the chain runs from the environment down. Only when all of them are empty, and an `ovcli.conf` file exists with credential fields, is the chain pinned to that file: the environment's credentials are skipped, `apiKey` still falls through to the `plugin` keys and `ov.conf` `<harness>.apiKey` (Claude Code and agent-plugins continue to `server.root_api_key`), and `account` / `user` stop at the `plugin` keys. `OPENVIKING_AUTH_MODE` does not count as a credential field and never unpins the file.
3. **baseUrl**: Resolves via environment variables → `ovcli` `url` → `ov.conf` `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}` (where `0.0.0.0` normalizes to `127.0.0.1`), with a final fallback to `http://127.0.0.1:1933`.
-4. **apiKey**: Resolves via `BEARER_TOKEN` → `API_KEY` → `ovcli` `api_key` → `ovcli` `plugin.<harness>.apiKey` → `ovcli` `plugin.apiKey` → `ov.conf` `<harness>.apiKey` → `server.root_api_key`. The `<harness>` block is the one named after the calling harness (snake_case, so `trae_cn`; `claude-code` and `claude_code` reach the same block), and `account` / `user` / `peerId` read that same block at the same position in their own chains.
+4. **apiKey**: A value the embedding host passed (dsh's Cordis patch) outranks every layer, as it does for the URL, account, user and auth mode; then `BEARER_TOKEN` → `API_KEY` → `ovcli` `api_key` → `ovcli` `plugin.<harness>.apiKey` → `ovcli` `plugin.apiKey` → `ov.conf` `<harness>.apiKey` → `server.root_api_key`. The `<harness>` block is the one named after the calling harness (snake_case, so `trae_cn`; `claude-code` and `claude_code` reach the same block), and `account` / `user` / `peerId` read that same block at the same position in their own chains.
5. **mcpUrl**: Resolves via `OPENVIKING_MCP_URL` (when outside CLI mode) → `${baseUrl}/mcp`.
-6. **Common request headers**: `Authorization: Bearer` + `X-OpenViking-Account/User` (trusted mode only) + `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`. An `api_key` server reads the identity out of the key and ignores those two headers, so they are withheld there rather than named to every proxy on the path. The mode resolves via `ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → trusted whenever an account or user resolved at all.
+6. **Common request headers**: `Authorization: Bearer` + `X-OpenViking-Account/User` (trusted mode only) + `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`. An `api_key` server reads the identity out of the key and ignores those two headers, so they are withheld there rather than named to every proxy on the path. The mode resolves via `OPENVIKING_AUTH_MODE` (read in every mode) → `ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → trusted whenever an account or user resolved at all.
+7. **One connection for hooks and MCP**: everything above is `resolveConnection()` in `credentials.mjs`. The hook loader (`buildPluginConfig()`) and every MCP proxy (through its harness's loader, or `buildProxyConnection()` for agent-plugins) call it, and it never reads the working directory, so a proxy launched from the plugin directory resolves what the hooks resolve. The process boundary is handled in one of two ways: Codex passes its MCP server only the names in `.mcp.json` `env_vars`, which must include `MCP_PROXY_ENV_VARS`; dsh forwards the resolved connection itself, every credential variable written even when empty, with `OPENVIKING_CREDENTIAL_SOURCE=env`, so neither a file nor a variable the child inherits can change it. `mcp-hook-parity.test.mjs` checks that both sides put the same URL, key and identity on the wire.
**Workspace peer** (applies to every Family A harness; the agent-plugins package derives no workspace peer and forwards none — it has no knob layer that could set `recallPeerScope` to `actor`, so its proxy never sends the header): If no explicit `peerId` is provided and `OPENVIKING_WORKSPACE_PEER≠0`, the peer is derived from the workspace and sent as the `X-OpenViking-Actor-Peer` (the server validates this header and returns a `400` error if it contains `/` or `\`). The derivation rule is `peer.source`, which **defaults to `git`**: the normalized `origin` URL first, falling back to the repository root. Outside a repository nothing is sent, and what is remembered there goes to the user-level space `viking://user/<you>/memories` instead. In `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` with an origin of `[email protected]:volcengine/OpenViking.git`, the peer is `github.com-volcengine-openviking` — the same value from any subdirectory, any worktree, any machine, and any clone. `peer.source` is read from the env var `OPENVIKING_PEER_SOURCE`, the ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource` keys, and the workspace file's `peer.source`; every Family A harness reads those layers.
diff --git a/docs/en/agent-integrations/18-plugin-development.md b/docs/en/agent-integrations/18-plugin-development.md
index c3abc1afa..98e689415 100644
--- a/docs/en/agent-integrations/18-plugin-development.md
+++ b/docs/en/agent-integrations/18-plugin-development.md
@@ -164,7 +164,7 @@ Switches must govern actual behavior. Disabling recall prevents automatic recall
### 4.2 Credentials are not ordinary workspace settings
-Resolve connections and identity through `credentials.mjs` and `buildPluginConfig()`. The `auto`, `cli`, and `env` modes of `OPENVIKING_CREDENTIAL_SOURCE` select credential sources; they do not simply follow the behavior-setting precedence above. Verify custom configuration paths, `plugin.<harness>` overrides, and hook/MCP behavior after `ov config switch`. Comparing a few default loader fields is insufficient.
+Resolve connections and identity through `resolveConnection()` in `credentials.mjs`, which `buildPluginConfig()` calls. The `auto`, `cli`, and `env` modes of `OPENVIKING_CREDENTIAL_SOURCE` select credential sources; they do not simply follow the behavior-setting precedence above. An MCP proxy exports `readProxyConfig(env)`, resolves through the same loader as its hooks, and maps the result with `toMcpProxyConfig()`; it never picks fields by hand or calls `credentials.mjs` itself. If the host hands MCP servers an allowlisted environment, the allowlist must cover `MCP_PROXY_ENV_VARS`; if it hands them a closed one, forward the resolved connection with `forwardConnectionEnv()`. Add every new proxy to `mcp-hook-parity.test.mjs`, which fails until it has a row.
Workspace files must not contain forbidden connection or credential fields such as URLs, API keys, and user credentials, and must not interpolate environment variables. [`workspace-config.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-config.mjs) owns this rule; do not add a separate allowlist per host. Installers must not write resolved API keys into `.mcp.json` or replace the user's selected cloud connection.
@@ -397,7 +397,7 @@ Put common helpers in [`testing/support.mjs`](https://github.com/volcengine/Open
| Area | Behavior to verify | Existing entrypoints |
| --- | --- | --- |
| Configuration and switches | Layer precedence, alias conflicts, invalid values, configured flags, no new network effects when disabled | `plugin-config.test.mjs`, `plugin-known-keys.test.mjs`, host config tests |
-| Credentials and peers | Matching hook/MCP request identity; custom paths, profile switching, multiple workspaces | `credentials.test.mjs`, `wire-headers.test.mjs`, `mcp-proxy-config.test.mjs` |
+| Credentials and peers | Matching hook/MCP request identity; custom paths, profile switching, multiple workspaces | `credentials.test.mjs`, `mcp-hook-parity.test.mjs`, `wire-headers.test.mjs`, `mcp-proxy-config.test.mjs` |
| Hook output | Real payloads, one valid response, empty results, missing/unknown fields, failures | `agent-hook-runtime.test.mjs`, host event tests |
| Recall | Switches, bypass, empty results, server compatibility, compression failure, readable URIs | `recall-core.test.mjs`, host recall tests |
| Capture | Complete text/tools, repeated events and text, nested tools, partial success, truncation recovery | `capture-utils.test.mjs`, `batch-send.test.mjs`, host transcript tests |
diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.md
index f4c48dd19..e67abd8dc 100644
--- a/docs/zh/agent-integrations/04-codex.md
+++ b/docs/zh/agent-integrations/04-codex.md
@@ -72,7 +72,7 @@ TraeCode CLI 2.0 用户启动 `trae-cli`,并可用 `trae-cli plugin list` 确
| `OPENVIKING_URL` / `OPENVIKING_BASE_URL` | — | 完整的服务器 URL |
| `OPENVIKING_API_KEY` | — | API 密钥(将通过 `Authorization: Bearer` 标头发送) |
| `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | hook、MCP 和 Codex 内部 `ov` 命令共同使用的当前 CLI 配置 |
-| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | `auto` 下已设置的凭据环境变量优先;设为 `cli` 强制使用激活的 ovcli 配置,设为 `env` 强制使用环境变量 |
+| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | `auto` 下已设置的凭据环境变量优先;设为 `cli` 强制使用激活的 ovcli 配置;设为 `env` 只读环境变量,两个配置文件都不读 |
| `OPENVIKING_NO_AUTO_INJECT` | `false` | 关闭会话启动阶段的固定 profile/背景注入,但不关闭逐 prompt 语义召回 |
| `OPENVIKING_PROFILE_TOKEN_BUDGET` | `10000` | `profile.md` 及 `preferences/`、`entities/` 索引共用的 CJK-aware token 预算 |
| `OPENVIKING_CODEX_IDLE_TTL_MS` | `1800000` | `SessionStart` 闲置 TTL 清理阈值(毫秒) |
diff --git a/docs/zh/agent-integrations/15-agent-plugins.md b/docs/zh/agent-integrations/15-agent-plugins.md
index a9a837550..04f23816e 100644
--- a/docs/zh/agent-integrations/15-agent-plugins.md
+++ b/docs/zh/agent-integrations/15-agent-plugins.md
@@ -35,15 +35,15 @@ OpenViking 服务端本身在 `/mcp` 上就是 streamable HTTP,但 `mcp.json`
从高到低 —— 与 `ov` CLI 及其他 OpenViking 插件完全一致:
-1. 环境变量:`OPENVIKING_URL`(或 `OPENVIKING_BASE_URL`)、`OPENVIKING_MCP_URL`、`OPENVIKING_API_KEY`(或 `OPENVIKING_BEARER_TOKEN`)、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`
-2. `~/.openviking/ovcli.conf`(`url`、`api_key`、`account` / `account_id`、`user` / `user_id`、`actor_peer_id` / `peer_id`)—— 可用 `OPENVIKING_CLI_CONFIG_FILE` 覆盖路径
-3. `~/.openviking/ov.conf` 的 `agent_plugins` 段(`apiKey`、`accountId`、`userId`、`peerId`)—— 可用 `OPENVIKING_CONFIG_FILE` 覆盖路径
+1. 环境变量:`OPENVIKING_URL`(或 `OPENVIKING_BASE_URL`)、`OPENVIKING_MCP_URL`、`OPENVIKING_API_KEY`(或 `OPENVIKING_BEARER_TOKEN`)、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`、`OPENVIKING_AUTH_MODE`
+2. `~/.openviking/ovcli.conf`(`url`、`api_key`、`account` / `account_id`、`user` / `user_id`、`actor_peer_id` / `peer_id`),其后是它的 `plugin.agent_plugins` 与共享 `plugin` 键(`apiKey`、`accountId`、`userId`、`authMode`)—— 可用 `OPENVIKING_CLI_CONFIG_FILE` 覆盖路径
+3. `~/.openviking/ov.conf` 的 `agent_plugins` 段(`apiKey`、`accountId`、`userId`、`peerId`、`authMode`)—— 可用 `OPENVIKING_CONFIG_FILE` 覆盖路径
4. `~/.openviking/ov.conf` 的 `server` 段(`url`,或 `host` / `port`,以及 `root_api_key`)
5. 默认值:`http://127.0.0.1:1933`,不鉴权(本地模式)
`OPENVIKING_MCP_URL` 覆盖的是推导出的 `<url>/mcp` 端点,而不是 base URL。
-`OPENVIKING_CREDENTIAL_SOURCE`(或 `OPENVIKING_CREDENTIALS_SOURCE`)把整条链钉在某一端:`env` 只认环境变量,`cli`(同义写法还有 `ovcli` / `file` / `config`)只认 ovcli.conf。默认的 `auto` 在 ovcli.conf 带凭据、且上面这些环境变量一个都没设时钉向 ovcli.conf,否则按整条链解析。钉在 ovcli.conf 时,环境变量、`OPENVIKING_MCP_URL` 和 `agent_plugins` 段都会被跳过;只有 `server.root_api_key` 仍然生效——ovcli.conf 自己没有 api_key 时由它兜底,这样一份只写了 `url` 的旧安装仍然能用原来的 key。
+`OPENVIKING_CREDENTIAL_SOURCE`(或 `OPENVIKING_CREDENTIALS_SOURCE`)把整条链钉在某一端:`env` 只认环境变量,`cli`(同义写法还有 `ovcli` / `file` / `config`)只认 ovcli.conf。默认的 `auto` 在 ovcli.conf 带凭据、且上面这些环境变量一个都没设时钉向 ovcli.conf,否则按整条链解析。钉在 ovcli.conf 时,环境变量里的凭据和 `OPENVIKING_MCP_URL` 会被跳过。key 仍依次回落到 `plugin` 键、`agent_plugins` 段,最后是 `server.root_api_key`,所以只写了 `url` 的旧安装仍能用原来的 key;account 和 user 只回落到 `plugin` 键。`env` 模式两个文件都不读。
```json
// ~/.openviking/ovcli.conf
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 8d3b8fc9c..b389f1270 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -204,12 +204,13 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
家族 A 的解析链如下(其余家族见档案卡):
-1. 模式由 `OPENVIKING_CREDENTIAL_SOURCE`(别名 `_CREDENTIALS_SOURCE`)控制,取值 ∈ `env|cli|auto`(默认 auto)。
-2. **auto 语义是 env 优先**:只要任一 env 凭据字段存在,整体就走 env;只有 env 全空、且 ovcli.conf 存在并含凭据字段时,才整体切换到文件(此时 key/account/user/peer 全部只从文件取)。
+1. 模式由 `OPENVIKING_CREDENTIAL_SOURCE`(别名 `_CREDENTIALS_SOURCE`)控制,取值 ∈ `env|cli|auto`(默认 auto)。强制为 `env` 时,连接不读两个文件:没设的变量就是空,URL 默认 `http://127.0.0.1:1933`。`peerId` 配置仍按它自己的分层解析。
+2. **auto 语义是 env 优先**:只要任一 env 凭据字段(`URL`、`BASE_URL`、`MCP_URL`、`BEARER_TOKEN`、`API_KEY`、`ACCOUNT`、`USER`、`PEER_ID`)存在,就从环境变量开始往下解析;只有这些全空、且 ovcli.conf 存在并含凭据字段时,链条才钉在这个文件上:跳过环境变量里的凭据,`apiKey` 仍会依次回落到 `plugin` 键和 ov.conf `<harness>.apiKey`(Claude Code 与 agent-plugins 再回落到 `server.root_api_key`),`account` / `user` 只回落到 `plugin` 键。`OPENVIKING_AUTH_MODE` 不算凭据字段,单独设置不会解除钉定。
3. baseUrl:env → ovcli `url` → ov.conf `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}`(其中 `0.0.0.0` 归一为 `127.0.0.1`);兜底 `http://127.0.0.1:1933`。
-4. apiKey:`BEARER_TOKEN` → `API_KEY` → ovcli `api_key` → ovcli `plugin.<harness>.apiKey` → ovcli `plugin.apiKey` → ov.conf `<harness>.apiKey` → `server.root_api_key`。`<harness>` 是调用方 harness 自己的那段(snake_case,如 `trae_cn`;`claude-code` 与 `claude_code` 指向同一段);account / user / peerId 在各自链条的同一位置读同一段。
+4. apiKey:嵌入宿主传入的值(dsh 的 Cordis patch)排在所有层之上,URL、account、user、auth mode 同理;其后是 `BEARER_TOKEN` → `API_KEY` → ovcli `api_key` → ovcli `plugin.<harness>.apiKey` → ovcli `plugin.apiKey` → ov.conf `<harness>.apiKey` → `server.root_api_key`。`<harness>` 是调用方 harness 自己的那段(snake_case,如 `trae_cn`;`claude-code` 与 `claude_code` 指向同一段);account / user / peerId 在各自链条的同一位置读同一段。
5. mcpUrl:`OPENVIKING_MCP_URL`(非 cli 模式)→ `${baseUrl}/mcp`。
-6. 统一请求头:`Authorization: Bearer` + `X-OpenViking-Account/User`(仅 trusted 模式)+ `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`。`api_key` 模式的服务端从 key 里取身份、忽略这两个头,所以那里不发,免得把身份报给链路上的每一层代理。模式解析顺序:`ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → 只要解析出了 account 或 user 就算 trusted。
+6. 统一请求头:`Authorization: Bearer` + `X-OpenViking-Account/User`(仅 trusted 模式)+ `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`。`api_key` 模式的服务端从 key 里取身份、忽略这两个头,所以那里不发,免得把身份报给链路上的每一层代理。模式解析顺序:`OPENVIKING_AUTH_MODE`(任何模式下都读)→ `ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → 只要解析出了 account 或 user 就算 trusted。
+7. **hook 与 MCP 共用一份连接**:以上规则都由 `credentials.mjs` 的 `resolveConnection()` 实现。hook 的 loader(`buildPluginConfig()`)和每个 MCP proxy(经各自 harness 的 loader,agent-plugins 经 `buildProxyConnection()`)都调用它,而且它不读当前目录,所以从插件目录启动的 proxy 与 hook 解析结果相同。跨进程边界只有两种做法:Codex 只把 `.mcp.json` `env_vars` 列出的变量交给 MCP 进程,这份名单必须包含 `MCP_PROXY_ENV_VARS`;dsh 直接转发解析好的连接,每个凭据变量都显式写出(空值也写),并带上 `OPENVIKING_CREDENTIAL_SOURCE=env`,所以文件和子进程继承到的变量都改变不了它。`mcp-hook-parity.test.mjs` 断言两边发出的 URL、key 和身份一致。
**workspace peer**(家族 A 各 harness 均适用;agent-plugins 包既不派生 workspace peer,也不转发任何 peer——它没有能把 `recallPeerScope` 设成 `actor` 的旋钮层,代理始终不发这个头):无显式 peerId 且 `OPENVIKING_WORKSPACE_PEER≠0` 时由 workspace 派生,随 `X-OpenViking-Actor-Peer` 发送(服务端会对该头校验,含 `/` 或 `\` 返回 400)。派生规则由 `peer.source` 决定,**默认 `git`**:先取归一化后的 `origin` URL,取不到回落到仓库根路径;不在仓库中则什么都不发送,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。例如在 `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` 下、origin 为 `[email protected]:volcengine/OpenViking.git` 时,peer 是 `github.com-volcengine-openviking`——任意子目录、任意 worktree、任意机器、任意 clone 都是同一个值。`peer.source` 的读取层为 env `OPENVIKING_PEER_SOURCE`、ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource`、workspace 文件的 `peer.source`;家族 A 的每个 harness 都会读这几层。
diff --git a/docs/zh/agent-integrations/18-plugin-development.md b/docs/zh/agent-integrations/18-plugin-development.md
index 1e4332687..98c4d9a9a 100644
--- a/docs/zh/agent-integrations/18-plugin-development.md
+++ b/docs/zh/agent-integrations/18-plugin-development.md
@@ -164,7 +164,7 @@ sync / install / pack 负责把这张依赖图完整交付到机器上
### 4.2 凭据不是普通 workspace 配置
-连接和身份必须走 `credentials.mjs` 与 `buildPluginConfig()`。`OPENVIKING_CREDENTIAL_SOURCE` 的 `auto`、`cli`、`env` 控制凭据来源,不能简单套用行为配置优先级。必须验证自定义配置路径、`plugin.<harness>` 覆盖和 `ov config switch` 后 hook 与 MCP 的结果,不能只比较 loader 返回的几个默认字段。
+连接和身份必须走 `credentials.mjs` 的 `resolveConnection()`,`buildPluginConfig()` 就是调用它。`OPENVIKING_CREDENTIAL_SOURCE` 的 `auto`、`cli`、`env` 控制凭据来源,不能简单套用行为配置优先级。MCP proxy 导出 `readProxyConfig(env)`,经与 hook 相同的 loader 解析,再用 `toMcpProxyConfig()` 映射,不手工挑字段,也不直接调用 `credentials.mjs`。宿主若只把白名单里的环境变量交给 MCP 进程,白名单必须覆盖 `MCP_PROXY_ENV_VARS`;宿主若给的是封闭环境,就用 `forwardConnectionEnv()` 转发解析好的连接。新 proxy 必须加入 `mcp-hook-parity.test.mjs`,缺行时该测试会失败。
workspace 文件不得包含 URL、API key、用户凭据等禁止字段,也不做环境变量插值。规则由 [`workspace-config.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-config.mjs) 执行,不在每个宿主增加自己的白名单。安装器不得把解析后的 API key 固化到 `.mcp.json`,也不得替换用户已选择的云端连接。
@@ -397,7 +397,7 @@ PR 必须包含应提交的最新生成物,并检查新出现但未跟踪的
| 验证范围 | 至少覆盖的真实行为 | 现有入口 |
| --- | --- | --- |
| 配置与开关 | 分层覆盖、别名冲突、非法值、未配置标记、关闭后无新网络副作用 | `plugin-config.test.mjs`、`plugin-known-keys.test.mjs`、宿主 config 测试 |
-| 凭据与 peer | hook/MCP 的请求身份一致;自定义路径、profile 切换、多 workspace | `credentials.test.mjs`、`wire-headers.test.mjs`、`mcp-proxy-config.test.mjs` |
+| 凭据与 peer | hook/MCP 的请求身份一致;自定义路径、profile 切换、多 workspace | `credentials.test.mjs`、`mcp-hook-parity.test.mjs`、`wire-headers.test.mjs`、`mcp-proxy-config.test.mjs` |
| Hook 输出 | 真实 payload、单次合法输出、空结果、未知/缺失字段、错误路径 | `agent-hook-runtime.test.mjs`、宿主事件测试 |
| Recall | 开关、bypass、空结果、服务端兼容、压缩失败、可读 URI | `recall-core.test.mjs`、宿主 recall 测试 |
| Capture | 完整文本和工具记录、重复事件、重复文本、嵌套工具、部分成功、截短恢复 | `capture-utils.test.mjs`、`batch-send.test.mjs`、宿主 transcript 测试 |
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index 5f8933281..d49be2c23 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.3.1",
+ "version": "0.3.2",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index 2d9b19eb7..d888f4728 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.3.1",
+ "version": "0.3.2",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index e768c5dd2..d70465589 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.3.1",
+ "version": "0.3.2",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index 4b7843c62..d03af30dd 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agent-hook-plugin",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Long-term semantic memory for the config-driven hook hosts — Cursor, TRAE, TRAE CN and ZCode — powered by OpenViking. Auto-recall relevant memories at session start and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/servers/mcp-proxy.mjs b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
index f0f4e8188..55030d77f 100644
--- a/examples/agent-hook-plugin/servers/mcp-proxy.mjs
+++ b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
@@ -5,34 +5,20 @@ import { resolve as resolvePath } from "node:path";
import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
import { createLogger } from "../../memory-plugin-shared/lib/debug-log.mjs";
-import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../../memory-plugin-shared/lib/mcp-proxy-config.mjs";
+import { toMcpProxyConfig } from "../../memory-plugin-shared/lib/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../../memory-plugin-shared/lib/mcp-proxy-core.mjs";
import { HOSTS } from "../hosts/index.mjs";
-function readConfig() {
+export function readProxyConfig(env = process.env) {
// The installer writes the client id into the MCP server's environment; it is
// the only thing that tells this proxy which harness launched it. A hand-written
// entry that names none resolves through the layers every harness shares rather
// than borrowing another client's `plugin.<harness>` section.
- const requested = process.env.OPENVIKING_HOOK_SOURCE || "";
- const cfg = loadAgentHookConfig(HOSTS[requested] ? requested : "agent-hook");
- return buildMcpProxyConfig({
- mcpUrl: cfg.mcpUrl,
- apiKey: cfg.apiKey,
- account: cfg.account,
- user: cfg.user,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
- peerId: resolveMcpActorPeerId(cfg),
- userAgent: cfg.userAgent,
- timeoutMs: cfg.timeoutMs,
- debug: cfg.debug,
- debugLogPath: cfg.debugLogPath,
- credentialSource: cfg.credentialSource,
- credentialPath: cfg.cliPath || cfg.ovPath || "",
- watchedPaths: [cfg.cliPath, cfg.ovPath],
- });
+ const requested = env.OPENVIKING_HOOK_SOURCE || "";
+ const cfg = loadAgentHookConfig(HOSTS[requested] ? requested : "agent-hook", undefined, { env });
+ return toMcpProxyConfig(cfg, { env });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- createOpenVikingMcpProxy({ readConfig, loggerFactory: createLogger }).start();
+ createOpenVikingMcpProxy({ readConfig: readProxyConfig, loggerFactory: createLogger }).start();
}
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index acf3a63dd..60bc1dec9 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index 77baa8759..5aebec403 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjs
index dcbcfddc9..74a99f730 100644
--- a/examples/claude-code-memory-plugin/scripts/config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/config.mjs
@@ -105,9 +105,10 @@ export function isPluginEnabled() {
* baseUrl/apiKey cannot move — loggers and fetch helpers built from the first
* load stay valid.
*/
-export function loadConfig(cwd = process.cwd()) {
+export function loadConfig(cwd = process.cwd(), { env = process.env } = {}) {
const config = buildPluginConfig("claude-code", {
cwd,
+ env,
manifestUrl: MANIFEST_URL,
logFile: "cc-hooks.log",
rootKeyFallback: true,
@@ -127,8 +128,8 @@ export function loadConfig(cwd = process.cwd()) {
// server's `rewrite` request field; OPENVIKING_RECALL_REWRITE is the older
// env spelling and still works.
recallRewrite: normalizeRewriteMode(
- process.env.OPENVIKING_RECALL_COMPRESS
- ?? process.env.OPENVIKING_RECALL_REWRITE
+ env.OPENVIKING_RECALL_COMPRESS
+ ?? env.OPENVIKING_RECALL_REWRITE
?? config.recallCompress,
"auto",
),
diff --git a/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
index 745bfaece..83b1d2bcd 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -44,11 +44,12 @@ export function stableHash(...values) {
* file may not carry connection or credential keys, so the base URL and API key
* cannot move under a logger or fetch helper already built from the first load.
*/
-export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
+export function loadAgentHookConfig(clientId, cwd = process.cwd(), { env = process.env } = {}) {
return {
...buildPluginConfig(clientId, {
cwd,
- version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ env,
+ version: env.OPENVIKING_INTEGRATION_VERSION,
logFile: `${clientId}-hooks.log`,
}),
clientId,
diff --git a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
index 0ab2d984d..fea82315c 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
@@ -2,11 +2,9 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { fileURLToPath } from "node:url";
const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
-const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
const DEFAULT_TIMEOUT_MS = 15000;
const MIN_TIMEOUT_MS = 1000;
@@ -111,17 +109,74 @@ export function loadCredentialFiles(env = process.env) {
}
/**
- * The calling harness's own section of ov.conf.
- *
+ * The environment variables that name part of the connection. Any one of them
+ * set is what takes the chain off ovcli.conf in `auto` mode, so a variable
+ * that only tunes how the chain runs must not be on this list: an
+ * `OPENVIKING_AUTH_MODE` exported on its own would otherwise unpin the file.
+ */
+export const CREDENTIAL_ENV_VARS = [
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_MCP_URL",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+ "OPENVIKING_PEER_ID",
+];
+
+/** Every environment variable `resolveConnection` reads. */
+export const CONNECTION_ENV_VARS = [
+ ...CREDENTIAL_ENV_VARS,
+ "OPENVIKING_AUTH_MODE",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
+ "OPENVIKING_CLI_CONFIG_FILE",
+ "OPENVIKING_CONFIG_FILE",
+];
+
+function isSection(value) {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/**
* ov.conf spells its sections snake_case while a host may call itself
* `claude-code` or `trae-cn`, so both spellings land on the same block. The
* normalization stays inline rather than importing `config-schema.mjs`, which
* the portable agent-plugins bundle would then have to ship as well.
*/
+function sectionKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** The calling harness's own section of ov.conf. */
function harnessSection(ovFile, harness) {
- const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
- const section = key ? ovFile[key] : null;
- return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+ const section = ovFile[sectionKey(harness)];
+ return isSection(section) ? section : {};
+}
+
+/**
+ * ovcli.conf's `plugin` section as this harness sees it: the shared scalars,
+ * then `plugin.<harness>` over them in both spellings, the hyphenated one last.
+ * `loadPluginSettings` merges the same way for every other knob, and the two
+ * must agree or a key would win in the hooks and lose here.
+ */
+function pluginSection(cliFile, harness) {
+ const plugin = isSection(cliFile.plugin) ? cliFile.plugin : {};
+ const merged = {};
+ for (const [key, value] of Object.entries(plugin)) {
+ if (!isSection(value)) merged[key] = value;
+ }
+ const key = sectionKey(harness);
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ if (candidate && isSection(plugin[candidate])) Object.assign(merged, plugin[candidate]);
+ }
+ return merged;
+}
+
+/** A knob-file scalar as the schema coerces a string knob: `12345` is "12345". */
+function scalar(value) {
+ return value === undefined || value === null ? "" : String(value).trim();
}
const AUTH_MODES = ["trusted", "api_key"];
@@ -131,22 +186,8 @@ function normalizeAuthMode(value) {
return AUTH_MODES.includes(mode) ? mode : "";
}
-/**
- * Which auth mode the server is in, and with it whether the identity headers
- * may go on the wire.
- *
- * An `api_key` server reads the account and the user out of the key and ignores
- * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
- * every proxy on the path who the operator is and buys nothing. A named mode
- * wins; ov.conf's server block answers next; failing both, a credential layer
- * that supplied an identity at all means the deployment expects one.
- */
-export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
- const server = ovFile.server || {};
- const authMode = normalizeAuthMode(settings.authMode)
- || normalizeAuthMode(server.auth_mode)
- || ((account || user) ? "trusted" : "api_key");
- return { authMode, sendIdentityHeaders: authMode === "trusted" };
+function authModeIn(section) {
+ return normalizeAuthMode(section.authMode) || normalizeAuthMode(section.auth_mode);
}
function sourceMode(env) {
@@ -158,135 +199,130 @@ function sourceMode(env) {
}
function hasEnvCredentialFields(env) {
- return Boolean(
- str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
- str(env.OPENVIKING_MCP_URL, "") ||
- str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(env.OPENVIKING_USER, "") ||
- str(env.OPENVIKING_PEER_ID, ""),
- );
+ return CREDENTIAL_ENV_VARS.some((name) => str(env[name], ""));
}
-function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
- const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
- const cliUrl = str(cliFile.url, "");
-
- if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
- if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
- if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
-
- const server = ovFile.server || {};
- const ovUrl = str(server.url, "");
- if (ovUrl) return ovUrl.replace(/\/+$/, "");
+function trimSlash(value) {
+ return value.replace(/\/+$/, "");
+}
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
- return `http://${host}:${port}`;
+/** The first layer that holds a value, with the source label and file it names. */
+function firstLayer(layers) {
+ for (const [value, source, path = ""] of layers) {
+ if (value) return { value, source, path };
+ }
+ return { value: "", source: "none", path: "" };
}
/**
- * `harness` names whose ov.conf section supplies the legacy fallback. It sits
- * where it always did — after ovcli.conf, before `server.root_api_key` — but a
- * harness now reads its own section instead of every one of them reading
- * codex's. The default keeps codex, the only caller that never passes one.
+ * The one connection a harness has: which server, which key, whose identity,
+ * and whether that identity goes on the wire. Hooks reach it through
+ * `buildPluginConfig`, every MCP proxy through the same loader or through
+ * `buildProxyConnection`, so the two sides of one harness cannot disagree.
+ *
+ * Only three kinds of input count: what an embedding host named (`hostInput`),
+ * the environment, and the two files under `~/.openviking`. The working
+ * directory never does — an MCP proxy starts wherever its host launches it.
*
- * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
- * section named, which this module cannot read for itself: resolving that
- * section needs the knob schema, and the portable bundles would then have to
- * ship it. All three rank where the file they come from ranks — under
- * ovcli.conf's own fields, over ov.conf.
+ * ovcli.conf pins the chain when it names a url, key, identity or peer and the
+ * environment names none of those; pinned, the environment's credentials no
+ * longer apply. `OPENVIKING_CREDENTIAL_SOURCE` forces either side, and forced
+ * to `env` no file is read at all — which is what lets a parent process hand a
+ * resolved connection, including an empty key, to a child verbatim. Every chain
+ * runs host → env (unpinned) → ovcli.conf → its `plugin.<harness>` and
+ * `plugin` keys → ov.conf's harness section; the key then ends at
+ * `server.root_api_key`, which a pinned chain reaches only with
+ * `rootKeyFallback`, and the identity skips ov.conf's harness section when
+ * pinned. The auth mode reads the environment in either mode, then the
+ * `plugin` keys, the harness section and `server.auth_mode`; failing all of
+ * them, an identity from any layer means the deployment expects one.
*/
-export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
- const files = loadCredentialFiles(env);
+export function resolveConnection(harness, {
+ env = process.env,
+ files = null,
+ hostInput = {},
+ rootKeyFallback = false,
+} = {}) {
+ const name = str(harness, "");
+ const loaded = files || loadCredentialFiles(env);
+ const { cliFile, ovFile, cliPath, ovPath } = loaded;
+ const host = hostInput || {};
const mode = sourceMode(env);
const envHasCredentials = hasEnvCredentialFields(env);
- const useCli = mode === "cli" ||
- (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
- const cx = harnessSection(files.ovFile, harness);
- const server = files.ovFile.server || {};
-
- const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
-
- const pluginApiKey = str(plugin?.apiKey, "");
- const apiKey = useCli
- ? (str(files.cliFile.api_key, "") || pluginApiKey)
- : (
- str(env.OPENVIKING_BEARER_TOKEN, "") ||
- str(env.OPENVIKING_API_KEY, "") ||
- str(files.cliFile.api_key, "") ||
- pluginApiKey ||
- str(cx.apiKey, "") ||
- str(server.root_api_key, "")
- );
-
- const pluginAccount = str(plugin?.accountId, "");
- const account = useCli
- ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
- : (
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
- pluginAccount ||
- str(cx.accountId, "")
- );
-
- const pluginUser = str(plugin?.userId, "");
- const user = useCli
- ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
- : (
- str(env.OPENVIKING_USER, "") ||
- str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
- pluginUser ||
- str(cx.userId, "")
- );
-
- const peerId = useCli
- ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
- : (
- str(env.OPENVIKING_PEER_ID, "") ||
- str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
- str(cx.peerId, str(cx.peer_id, ""))
- );
-
- const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
- const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
-
- // Which layer actually supplied the api_key, following the same chain, and
- // the file behind it — empty when the key came from the environment or was
- // never found. `apiKeySource` is what a doctor and a 401 hint report; the
- // credential *source* beside it is the mode the chain ran in, not a file.
- let apiKeySource = "none";
- let credentialPath = "";
- if (apiKey) {
- if (useCli) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
- apiKeySource = "env";
- } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else {
- apiKeySource = "ov";
- credentialPath = files.ovPath;
- }
- }
+ const pinned = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && Boolean(cliPath) && hasCredentialFields(cliFile));
+ const unpinned = (layer) => (pinned ? [] : [layer]);
+ const fromFiles = mode !== "env";
+ const filed = (...layers) => (fromFiles ? layers : []);
+ const plugin = pluginSection(cliFile, name);
+ const section = harnessSection(ovFile, name);
+ const server = isSection(ovFile.server) ? ovFile.server : {};
+
+ const key = firstLayer([
+ [str(host.apiKey, ""), "host"],
+ ...unpinned([str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")), "env"]),
+ ...filed(
+ [str(cliFile.api_key, ""), "ovcli", cliPath],
+ [scalar(plugin.apiKey), "ovcli", cliPath],
+ [scalar(section.apiKey), "ov", ovPath],
+ ),
+ ...((pinned && !rootKeyFallback) ? [] : filed([str(server.root_api_key, ""), "ov", ovPath])),
+ ]);
+
+ const identity = (hostValue, envName, cliValue, knob) => firstLayer([
+ [str(hostValue, ""), "host"],
+ ...unpinned([str(env[envName], ""), "env"]),
+ ...filed([cliValue, "ovcli", cliPath], [scalar(plugin[knob]), "ovcli", cliPath]),
+ ...(pinned ? [] : filed([str(section[knob], ""), "ov", ovPath])),
+ ]).value;
+ const account = identity(host.account, "OPENVIKING_ACCOUNT", str(cliFile.account, str(cliFile.account_id, "")), "accountId");
+ const user = identity(host.user, "OPENVIKING_USER", str(cliFile.user, str(cliFile.user_id, "")), "userId");
+
+ const peerId = firstLayer([
+ ...unpinned([str(env.OPENVIKING_PEER_ID, ""), "env"]),
+ ...filed([str(cliFile.actor_peer_id, str(cliFile.peer_id, "")), "ovcli"]),
+ ...(pinned ? [] : filed([str(section.peerId, str(section.peer_id, "")), "ov"])),
+ ]).value;
+
+ const authMode = normalizeAuthMode(host.authMode)
+ || normalizeAuthMode(env.OPENVIKING_AUTH_MODE)
+ || (fromFiles && (authModeIn(plugin) || authModeIn(section) || normalizeAuthMode(server.auth_mode)))
+ || ((account || user) ? "trusted" : "api_key");
+
+ const hostBaseUrl = trimSlash(str(host.baseUrl, ""));
+ const envUrl = pinned ? "" : str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const fileUrl = fromFiles ? (str(cliFile.url, "") || str(server.url, "")) : "";
+ const baseUrl = hostBaseUrl || trimSlash(envUrl || fileUrl) || serverAddress(fromFiles ? server : {});
+ const envMcpUrl = pinned ? "" : str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (!hostBaseUrl && envMcpUrl) ? envMcpUrl : `${baseUrl}/mcp`;
return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- apiKeySource,
- credentialPath,
+ ...loaded,
+ harness: name,
+ credentialSource: pinned ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
baseUrl,
mcpUrl,
- apiKey,
+ apiKey: key.value,
account,
user,
peerId,
- hasApiKey: Boolean(apiKey),
+ authMode,
+ sendIdentityHeaders: authMode === "trusted",
+ hasApiKey: Boolean(key.value),
+ // Which layer supplied the key and the file behind it, empty when the key
+ // came from the host or the environment. A doctor and a 401 hint report it;
+ // `credentialSource` is the mode the chain ran in, not a file.
+ apiKeySource: key.source,
+ credentialPath: key.path,
};
}
+function serverAddress(server) {
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
function envFlag(env, name) {
const raw = str(env[name], "").toLowerCase();
return raw === "1" || raw === "true" || raw === "yes";
@@ -304,9 +340,8 @@ function clampTimeout(value) {
* `buildPluginConfig` answers the same question one layer up, but reaching it
* means vendoring the knob schema and the workspace layers — a closure the
* portable agent-plugins bundle would carry in git to send one HTTP header.
- * This is the connection half alone: the credential chain, the auth mode that
- * decides whether the identity headers may go on the wire, the User-Agent, the
- * request timeout, and the debug log.
+ * This is the same connection plus what a proxy adds to it: the User-Agent,
+ * the request timeout, and the debug log.
*
* The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
* chain to itself. A portable package has no installer to migrate anyone, so
@@ -314,62 +349,27 @@ function clampTimeout(value) {
*/
export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
const name = str(harness);
- const credentials = resolveOpenVikingCredentials(env, name);
-
- let { apiKey, apiKeySource, credentialPath } = credentials;
- if (!apiKey) {
- apiKey = str(credentials.ovFile?.server?.root_api_key);
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
-
+ const connection = resolveConnection(name, { env, rootKeyFallback: true });
return {
harness: name,
userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
- baseUrl: credentials.baseUrl,
- mcpUrl: credentials.mcpUrl,
- apiKey,
- account: credentials.account,
- user: credentials.user,
- peerId: credentials.peerId,
- ...resolveAuthMode({
- settings: { authMode: env.OPENVIKING_AUTH_MODE },
- ovFile: credentials.ovFile,
- account: credentials.account,
- user: credentials.user,
- }),
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ baseUrl: connection.baseUrl,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
+ account: connection.account,
+ user: connection.user,
+ peerId: connection.peerId,
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
debug: envFlag(env, "OPENVIKING_DEBUG"),
debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
|| join(homedir(), ".openviking", "logs", `${name}.log`),
};
}
-
-function main() {
- const cmd = process.argv[2] || "";
- if (cmd === "mcp-url") {
- process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
- return;
- }
- if (cmd === "has-api-key") {
- process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
- return;
- }
- if (cmd === "has-peer-id") {
- process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
- return;
- }
- process.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
- process.exitCode = 2;
-}
-
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- main();
-}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
index 7cdd797cf..a24da5b29 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
@@ -1143,7 +1143,7 @@ export function inspectConfigFiles(report, { harness = "", launcherHint = "this
* block from `server.root_api_key`.
*
* The identity has no such answer to read, so account and user follow the chain
- * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * in `resolveConnection` step for step: pinned to ovcli.conf it ends
* at that file's `plugin` section, and otherwise the environment wins and
* ov.conf's harness block is last.
*/
@@ -1157,14 +1157,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
const scoped = (section && plugin[section]) || {};
const block = (section && ov[section]) || {};
const server = ov.server || {};
- // Pinned to ovcli.conf, the chain never looks at the environment.
+ // Pinned to ovcli.conf, the chain never looks at the environment; forced to
+ // the environment, it never looks at a file.
const pinned = cfg.credentialSource === "ovcli";
+ const envOnly = /^(env|environment)$/i.test(String(env.OPENVIKING_CREDENTIAL_SOURCE || env.OPENVIKING_CREDENTIALS_SOURCE || "").trim());
const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
const url = (!pinned && envUrl) ? "env"
- : cli.url ? cliShort
- : server.url ? ovShort
- : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+ : envOnly ? "default (http://127.0.0.1:1933)"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
let apiKey;
if (cfg.apiKeySource === "env") {
@@ -1179,15 +1182,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
} else if (cfg.apiKeySource === "host") {
apiKey = "the host application";
} else {
- apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)"
+ : envOnly ? "(none — env mode reads no file)" : "(none)";
}
const identity = (envName, cliValue, name) => (
(!pinned && env[envName]) ? "env"
- : cliValue ? cliShort
- : scoped[name] ? `${cliShort} plugin.${section}.${name}`
- : plugin[name] ? `${cliShort} plugin.${name}`
- : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ : envOnly ? "(unset)"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
);
return {
url,
diff --git a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
index c1e527967..e4f2428cc 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
@@ -12,9 +12,56 @@
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
+import { CONNECTION_ENV_VARS, CREDENTIAL_ENV_VARS } from "./credentials.mjs";
+
export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
const MIN_PROXY_TIMEOUT_MS = 1000;
+/**
+ * Every variable that changes what an MCP proxy sends. Hooks inherit their
+ * host's whole environment; a host that hands its MCP servers an allowlist
+ * instead (Codex's `env_vars`) has to name each of these, or the proxy
+ * resolves a different connection from the hooks beside it.
+ */
+export const MCP_PROXY_ENV_VARS = [
+ ...CONNECTION_ENV_VARS,
+ "OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
+ "OPENVIKING_RECALL_PEER_SCOPE",
+ "OPENVIKING_TIMEOUT_MS",
+ "OPENVIKING_DEBUG",
+ "OPENVIKING_DEBUG_LOG",
+ "OPENVIKING_EXTRA_HEADERS",
+];
+
+/**
+ * A resolved connection as the environment of a child proxy process.
+ *
+ * The other way across the process boundary, for a host that cannot hand its
+ * MCP servers the inputs (DSH drops credential-shaped names from what a child
+ * inherits): the parent resolves once and the child reads the answer back. The
+ * forced `env` source makes that exact — the child reads no file, so a key the
+ * parent left empty stays empty instead of falling through to
+ * `server.root_api_key`. Every credential variable is written, the empty ones
+ * too, because the rest of the parent's environment still reaches the child:
+ * an `OPENVIKING_ACCOUNT` the parent's pinned chain ignored must not fill the
+ * gap there.
+ */
+export function forwardConnectionEnv(connection) {
+ const env = Object.fromEntries(CREDENTIAL_ENV_VARS.map((name) => [name, ""]));
+ return {
+ ...env,
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: connection.baseUrl,
+ OPENVIKING_MCP_URL: connection.mcpUrl,
+ OPENVIKING_API_KEY: connection.apiKey || "",
+ OPENVIKING_ACCOUNT: connection.account || "",
+ OPENVIKING_USER: connection.user || "",
+ OPENVIKING_PEER_ID: connection.peerId || "",
+ OPENVIKING_AUTH_MODE: connection.authMode,
+ };
+}
+
export function trimSlash(value) {
return String(value || "").replace(/\/+$/, "");
}
@@ -55,7 +102,7 @@ export function defaultCredentialPaths(env = process.env) {
* start: the proxy is what carries every memory tool, and taking those away
* because a scope preference cannot be honoured costs the user far more than
* the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
+ * (dsh, `mcp-env.mjs`) can satisfy this without the user setting it.
*/
export function resolveMcpActorPeerId({
peerId = "",
@@ -192,3 +239,38 @@ export function buildMcpProxyConfig({
extraHeaders: resolvedExtraHeaders,
};
}
+
+/**
+ * The proxy config for a resolved harness config, mapped in one place.
+ *
+ * Every proxy used to copy fields out of its loader by hand, and the copies
+ * drifted: two dropped `mcpUrl`, so `OPENVIKING_MCP_URL` reached the hooks and
+ * not the tools. `cfg` is what `buildPluginConfig` or `buildProxyConnection`
+ * returned. `peerId` replaces the actor peer only for a harness whose parent
+ * process resolved it (dsh); everywhere else a long-lived proxy may send one
+ * only when actor-scoped recall asks for it.
+ */
+export function toMcpProxyConfig(cfg, {
+ env = process.env,
+ peerId = undefined,
+ debug = cfg.debug,
+ debugLogPath = cfg.debugLogPath,
+} = {}) {
+ return buildMcpProxyConfig({
+ baseUrl: cfg.baseUrl,
+ mcpUrl: cfg.mcpUrl,
+ apiKey: cfg.apiKey,
+ account: cfg.account,
+ user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
+ peerId: peerId === undefined ? resolveMcpActorPeerId(cfg) : peerId,
+ userAgent: cfg.userAgent,
+ timeoutMs: cfg.timeoutMs,
+ debug,
+ debugLogPath,
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.credentialPath || "",
+ watchedPaths: [cfg.cliPath, cfg.ovPath],
+ env,
+ });
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
index cbae04ab8..214a287f9 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
@@ -34,8 +34,7 @@ import {
buildUserAgent,
loadCredentialFiles,
readManifestVersion,
- resolveAuthMode,
- resolveOpenVikingCredentials,
+ resolveConnection,
} from "./credentials.mjs";
import {
announcedOverrides,
@@ -165,15 +164,6 @@ function ovConfSection(ovFile, key) {
return section && typeof section === "object" && !Array.isArray(section) ? section : {};
}
-/**
- * A connection value ovcli.conf's `plugin` section supplied, as opposed to
- * ov.conf's harness block or the environment — the credential chain ranks
- * those two itself, and would rank a `plugin` value wrong.
- */
-function fromPluginSection(settings, sources, name) {
- return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
-}
-
/**
* One harness's whole configuration: the files, the knobs, the peer, and the
* handful of fields derived from them.
@@ -185,12 +175,16 @@ function fromPluginSection(settings, sources, name) {
* else. What is left in a loader after this call is what only that harness
* knows.
*
- * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
- * host hands it one of its own); `hostInput` is what an embedding host named
- * for this process, which is the more specific answer and outranks every file;
- * `logFile` is the log basename this harness has always used, and a harness
- * that never had a default log path does not get one invented for it;
- * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * The connection — server, key, identity, auth mode — is not a knob: it comes
+ * from `resolveConnection`, the same call an MCP proxy's connection comes
+ * from, and the `plugin` keys and ov.conf block that name it are read there.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get for its
+ * knobs (dsh's host hands it one of its own); `hostInput` is what an embedding
+ * host named for this process, which is the more specific answer and outranks
+ * every file; `logFile` is the log basename this harness has always used, and
+ * a harness that never had a default log path does not get one invented for
+ * it; `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
* pinning and has always ended at `server.root_api_key`.
*/
export function buildPluginConfig(harness, {
@@ -218,46 +212,15 @@ export function buildPluginConfig(harness, {
cliFile: files.cliFile,
clientVersion,
});
- const credentials = resolveOpenVikingCredentials(env, key, {
- apiKey: fromPluginSection(settings, sources, "apiKey"),
- accountId: fromPluginSection(settings, sources, "accountId"),
- userId: fromPluginSection(settings, sources, "userId"),
- });
-
- // Pinned to ovcli.conf, the credential chain stops at that file. The layers
- // under it still answer: ov.conf's harness block is where tuning used to
- // live, and `server.root_api_key` is where a harness that predates the
- // pinning has always ended its chain.
- let apiKey = credentials.apiKey;
- let apiKeySource = credentials.apiKeySource;
- let credentialPath = credentials.credentialPath;
- if (!apiKey) {
- apiKey = sources.apiKey === OV_CONF_LAYER
- ? str(settings.apiKey)
- : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
- const hostApiKey = str(hostInput.apiKey);
- if (hostApiKey) {
- apiKey = hostApiKey;
- apiKeySource = "host";
- credentialPath = "";
- }
-
- const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
- const baseUrl = hostBaseUrl || credentials.baseUrl;
- const account = str(hostInput.account) || credentials.account;
- const user = str(hostInput.user) || credentials.user;
+ const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback });
+ const { baseUrl, account, user } = connection;
const timeoutMs = settings.timeoutMs;
const peerId = resolvePluginPeerId({
settings,
configured,
sources,
- credentials,
- hostInput: hostInput.peerId,
+ credentials: connection,
+ hostInput: hostInput?.peerId,
env,
});
@@ -268,21 +231,22 @@ export function buildPluginConfig(harness, {
userAgent: buildUserAgent(name, clientVersion),
baseUrl,
- mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
- apiKey,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
account,
user,
- ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- configPath: credentials.cliPath || credentials.ovPath || null,
- cliConfigPath: credentials.cliPath,
- ovConfigPath: credentials.ovPath,
- cliPath: credentials.cliPath,
- ovPath: credentials.ovPath,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ configPath: connection.cliPath || connection.ovPath || null,
+ cliConfigPath: connection.cliPath,
+ ovConfigPath: connection.ovPath,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
peerId,
explicitPeerId: peerId,
@@ -309,7 +273,7 @@ export function buildPluginConfig(harness, {
// it per session, against the directory the payload names, and an MCP proxy
// must not derive one from wherever it happened to be launched.
if (deriveEffectivePeer) {
- const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env });
config.effectivePeer = effectivePeer;
config.legacyPeerId = effectivePeer.legacyPeerId;
}
diff --git a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
index 04084e265..b762bdf02 100644
--- a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
@@ -3,8 +3,8 @@
/**
* stdio -> streamable-HTTP MCP proxy for the OpenViking Claude Code plugin.
*
- * Claude Code starts this process as a local stdio MCP server. The proxy reads
- * the same OpenViking credential sources as the lifecycle hooks, forwards
+ * Claude Code starts this process as a local stdio MCP server. The proxy
+ * resolves its connection through the hooks' own `loadConfig()`, forwards
* JSON-RPC requests to the server's /mcp endpoint, and keeps stdout
* protocol-clean.
*/
@@ -13,26 +13,11 @@ import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../scripts/config.mjs";
import { createLogger } from "../scripts/debug-log.mjs";
-import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../scripts/shared/mcp-proxy-config.mjs";
+import { toMcpProxyConfig } from "../scripts/shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
-function readProxyConfig() {
- const cfg = loadConfig();
- return buildMcpProxyConfig({
- baseUrl: cfg.baseUrl,
- apiKey: cfg.apiKey,
- account: cfg.accountId,
- user: cfg.userId,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
- peerId: resolveMcpActorPeerId(cfg),
- userAgent: cfg.userAgent,
- timeoutMs: cfg.timeoutMs,
- debug: cfg.debug,
- debugLogPath: cfg.debugLogPath,
- credentialSource: cfg.credentialSource,
- credentialPath: cfg.credentialPath || "",
- watchedPaths: [cfg.credentialPath, cfg.configPath].filter(Boolean),
- });
+export function readProxyConfig(env = process.env) {
+ return toMcpProxyConfig(loadConfig(undefined, { env }), { env });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
index 3ea6c0f42..6b33ca6a7 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -35,10 +35,12 @@ and `OPENVIKING_PENDING_DIR` relocate individual pieces.
| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/user` → `ovcli.conf plugin.claude_code.accountId/userId` → `ovcli.conf plugin.accountId/userId` → `ov.conf claude_code.accountId/userId` |
| peer | `OPENVIKING_PEER_ID` → registry → `config.local.json` → `config.json` (`peer.id`) → `ovcli.conf plugin.claude_code.peerId` → `ovcli.conf plugin.peerId` → `ovcli.conf actor_peer_id/peer_id` → `ov.conf claude_code.peerId` → derived per `peer.source` unless `OPENVIKING_WORKSPACE_PEER=0` |
| peer.source | `OPENVIKING_PEER_SOURCE` → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.claude_code.peerSource` → `ovcli.conf plugin.peerSource` → `ov.conf claude_code.peerSource` → `git` |
-| auth mode | `ovcli.conf plugin.claude_code.authMode` → `ovcli.conf plugin.authMode` → `ov.conf claude_code.authMode` → `ov.conf server.auth_mode` → `trusted` when account/user are set, else `api_key` |
+| auth mode | `OPENVIKING_AUTH_MODE` → `ovcli.conf plugin.claude_code.authMode` → `ovcli.conf plugin.authMode` → `ov.conf claude_code.authMode` → `ov.conf server.auth_mode` → `trusted` when account/user are set, else `api_key` |
| enabled | `OPENVIKING_MEMORY_ENABLED` → `ov.conf claude_code.enabled === false` → "ov.conf or ovcli.conf exists and parses" |
| tuning | env → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.claude_code.*` → `ovcli.conf plugin.*` → `ov.conf claude_code.*` → defaults |
+The order above is the `auto` mode with a credential variable set, or with no ovcli.conf credentials. When ovcli.conf names a url, key, identity or peer and no credential variable is set, the chain is pinned to that file: the credential variables are skipped, `api_key` still falls back through the `plugin` keys, `ov.conf claude_code.apiKey` and `server.root_api_key`, and account/user stop at the `plugin` keys. `OPENVIKING_CREDENTIAL_SOURCE=cli` forces that; `=env` reads the variables only, and neither file. The MCP proxy resolves this same chain.
+
Only trailing slashes are stripped from the url; no scheme check, no path
normalisation. `https://api.vikingdb.cn-beijing.volces.com/openviking` (the Volcengine-hosted OpenViking Service)
is a legitimate path prefix; `/api/v1` or `/mcp` suffixes are not.
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index d85e5d27e..827e484c8 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.9.1",
+ "version": "0.9.2",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/.mcp.json b/examples/codex-memory-plugin/.mcp.json
index 15067efc6..25fbc58f5 100644
--- a/examples/codex-memory-plugin/.mcp.json
+++ b/examples/codex-memory-plugin/.mcp.json
@@ -11,11 +11,13 @@
"OPENVIKING_CLI_CONFIG_FILE",
"OPENVIKING_CONFIG_FILE",
"OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
"OPENVIKING_URL",
"OPENVIKING_BASE_URL",
"OPENVIKING_MCP_URL",
"OPENVIKING_API_KEY",
"OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_AUTH_MODE",
"OPENVIKING_ACCOUNT",
"OPENVIKING_USER",
"OPENVIKING_PEER_ID",
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index f0a413498..090a175d4 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -110,10 +110,10 @@ If you don't want the installer touching your rc, do these things yourself:
Connection / identity source (applies to hooks, MCP, and `ov` commands run inside Codex):
1. **Default (auto)**: env-var credentials (`OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`) win when any is set; otherwise the active `ovcli.conf` is used: `OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`. With no credential env vars set, `ov config switch <name>` changes the active credentials for the CLI, hooks, MCP, and child `ov` commands together.
-2. **Forced**: set `OPENVIKING_CREDENTIAL_SOURCE=cli` to force `ovcli.conf`, or `OPENVIKING_CREDENTIAL_SOURCE=env` to force env-var credentials.
+2. **Forced**: set `OPENVIKING_CREDENTIAL_SOURCE=cli` to force `ovcli.conf`, or `OPENVIKING_CREDENTIAL_SOURCE=env` to read env vars only, with neither config file.
3. **Fallback**: without credential env vars or an ovcli config, `ov.conf` is used (`server.url` / `server.root_api_key` plus legacy `codex.*` tuning); then `http://127.0.0.1:1933` unauthenticated.
-Hooks and the MCP proxy call the same resolver directly, so the model tools and lifecycle hooks follow the same target.
+The MCP proxy loads its connection through the same `loadConfig()` as the hooks, so the model tools and lifecycle hooks use the same target and key, including one set only in ovcli.conf's `plugin.codex` section. Codex passes the proxy only the variables `.mcp.json` lists, and that list covers every variable the connection reads.
Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model), and as nothing else — the hooks used to repeat the key as `X-API-Key`, which a gateway of your own can still add if it needs one. `account` and `user` go out as `X-OpenViking-Account` / `X-OpenViking-User` only in trusted mode; an `api_key` server reads both out of the key and ignores the headers.
diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjs
index 7a1e36969..d77fbfc7d 100644
--- a/examples/codex-memory-plugin/scripts/config.mjs
+++ b/examples/codex-memory-plugin/scripts/config.mjs
@@ -17,12 +17,12 @@
* set; otherwise the active ovcli.conf is used, so `ov config switch`
* changes hooks, MCP, and in-process `ov` commands together on next launch.
* - Set OPENVIKING_CREDENTIAL_SOURCE=cli to force ovcli.conf, or =env to
- * force env-var credentials.
+ * read env vars only, with neither config file.
* - Without env vars or ovcli.conf, ov.conf/defaults are used.
*
- * The stdio MCP proxy calls the same resolver directly. Aligning the resolver
- * prevents identity drift between auto-capture/auto-recall hooks, MCP calls,
- * and child `ov` commands launched from inside Codex.
+ * The stdio MCP proxy builds its connection from this same `loadConfig()`, so
+ * the auto-capture/auto-recall hooks and MCP calls cannot drift apart on
+ * identity.
*
* File-path env vars:
* OPENVIKING_CLI_CONFIG_FILE alternate ovcli.conf path (preferred)
@@ -61,9 +61,10 @@ function configBool(value, fallback) {
* workspace file may not carry connection or credential keys, so baseUrl/apiKey
* cannot move — loggers and fetch helpers built from the first load stay valid.
*/
-export function loadConfig(cwd = process.cwd()) {
+export function loadConfig(cwd = process.cwd(), { env = process.env } = {}) {
const config = buildPluginConfig("codex", {
cwd,
+ env,
manifestUrl: MANIFEST_URL,
logFile: "codex-hooks.log",
});
diff --git a/examples/codex-memory-plugin/scripts/config.test.mjs b/examples/codex-memory-plugin/scripts/config.test.mjs
index 6f568983a..af2878a76 100644
--- a/examples/codex-memory-plugin/scripts/config.test.mjs
+++ b/examples/codex-memory-plugin/scripts/config.test.mjs
@@ -22,8 +22,15 @@ const OVERRIDES = [
"OPENVIKING_RECALL_COMPRESS_THINKING",
"OPENVIKING_URL",
"OPENVIKING_BASE_URL",
+ "OPENVIKING_MCP_URL",
"OPENVIKING_API_KEY",
"OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+ "OPENVIKING_PEER_ID",
+ "OPENVIKING_AUTH_MODE",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
"OPENVIKING_RECALL_QUERY_FILTERS",
"OPENVIKING_CAPTURE_FILTERS",
];
diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
index 1c8b5b54a..4e296c233 100644
--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs
+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
@@ -16,6 +16,8 @@ import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { MCP_PROXY_ENV_VARS } from "./shared/mcp-proxy-config.mjs";
+
const scriptsDir = dirname(fileURLToPath(import.meta.url));
const pluginDir = resolve(scriptsDir, "..");
const repoRoot = resolve(scriptsDir, "..", "..", "..");
@@ -203,11 +205,21 @@ test(".mcp.json starts the stdio MCP proxy from the plugin root", () => {
execFileSync("node", ["--check", join(pluginDir, "servers", "mcp-proxy.mjs")], { stdio: "pipe" });
});
+test(".mcp.json forwards every env var that changes what the MCP proxy sends", () => {
+ // Hooks inherit Codex's whole environment, but a stdio MCP server only gets
+ // the names listed here; a missing one is a setting the proxy never sees.
+ const server = readJson(join(pluginDir, ".mcp.json")).mcpServers[PLUGIN_NAME];
+ const forwarded = new Set(server.env_vars);
+ for (const name of MCP_PROXY_ENV_VARS) {
+ assert.ok(forwarded.has(name), `.mcp.json env_vars must forward ${name}`);
+ }
+});
+
test("Codex MCP entrypoint forwards only native OpenViking tools", () => {
const entrypoint = readFileSync(join(pluginDir, "servers", "mcp-proxy.mjs"), "utf-8");
assert.doesNotMatch(entrypoint, /createExperienceToolProvider/);
assert.doesNotMatch(entrypoint, /localToolProvider/);
- assert.match(entrypoint, /resolveMcpActorPeerId\(cfg\)/);
+ assert.match(entrypoint, /toMcpProxyConfig\(/);
assert.doesNotMatch(entrypoint, /resolveEffectivePeerId|process\.cwd\(\)/);
});
diff --git a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
index ca4760a47..035c02ce3 100644
--- a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
+++ b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
@@ -309,7 +309,9 @@ function checkConfig(report, cfg, host) {
}
const modeEnv = process.env.OPENVIKING_CREDENTIAL_SOURCE || process.env.OPENVIKING_CREDENTIALS_SOURCE;
- const modeText = cfg.credentialSource === "ovcli" ? "ovcli.conf only (env and ov.conf ignored)" : cfg.credentialSource === "env" ? "environment variables win" : "fell through to ov.conf / defaults";
+ const modeText = cfg.credentialSource === "ovcli" ? "ovcli.conf only (env and ov.conf ignored)"
+ : /^(env|environment)$/i.test(String(modeEnv || "").trim()) ? "environment variables only (both files ignored)"
+ : cfg.credentialSource === "env" ? "environment variables win" : "fell through to ov.conf / defaults";
report.info(`credential source: ${cfg.credentialSource} — ${modeText}${modeEnv ? ` (OPENVIKING_CREDENTIAL_SOURCE=${modeEnv})` : ""}`);
if (modeEnv && !/^(env|environment|cli|ovcli|file|config|auto)$/i.test(modeEnv)) report.warn(`OPENVIKING_CREDENTIAL_SOURCE=${modeEnv} is not a recognised value`, "valid: env, cli (ovcli/file/config), auto", "fix or unset it");
diff --git a/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
index 745bfaece..83b1d2bcd 100644
--- a/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -44,11 +44,12 @@ export function stableHash(...values) {
* file may not carry connection or credential keys, so the base URL and API key
* cannot move under a logger or fetch helper already built from the first load.
*/
-export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
+export function loadAgentHookConfig(clientId, cwd = process.cwd(), { env = process.env } = {}) {
return {
...buildPluginConfig(clientId, {
cwd,
- version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ env,
+ version: env.OPENVIKING_INTEGRATION_VERSION,
logFile: `${clientId}-hooks.log`,
}),
clientId,
diff --git a/examples/codex-memory-plugin/scripts/shared/credentials.mjs b/examples/codex-memory-plugin/scripts/shared/credentials.mjs
index 0ab2d984d..fea82315c 100644
--- a/examples/codex-memory-plugin/scripts/shared/credentials.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/credentials.mjs
@@ -2,11 +2,9 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { fileURLToPath } from "node:url";
const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
-const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
const DEFAULT_TIMEOUT_MS = 15000;
const MIN_TIMEOUT_MS = 1000;
@@ -111,17 +109,74 @@ export function loadCredentialFiles(env = process.env) {
}
/**
- * The calling harness's own section of ov.conf.
- *
+ * The environment variables that name part of the connection. Any one of them
+ * set is what takes the chain off ovcli.conf in `auto` mode, so a variable
+ * that only tunes how the chain runs must not be on this list: an
+ * `OPENVIKING_AUTH_MODE` exported on its own would otherwise unpin the file.
+ */
+export const CREDENTIAL_ENV_VARS = [
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_MCP_URL",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+ "OPENVIKING_PEER_ID",
+];
+
+/** Every environment variable `resolveConnection` reads. */
+export const CONNECTION_ENV_VARS = [
+ ...CREDENTIAL_ENV_VARS,
+ "OPENVIKING_AUTH_MODE",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
+ "OPENVIKING_CLI_CONFIG_FILE",
+ "OPENVIKING_CONFIG_FILE",
+];
+
+function isSection(value) {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/**
* ov.conf spells its sections snake_case while a host may call itself
* `claude-code` or `trae-cn`, so both spellings land on the same block. The
* normalization stays inline rather than importing `config-schema.mjs`, which
* the portable agent-plugins bundle would then have to ship as well.
*/
+function sectionKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** The calling harness's own section of ov.conf. */
function harnessSection(ovFile, harness) {
- const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
- const section = key ? ovFile[key] : null;
- return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+ const section = ovFile[sectionKey(harness)];
+ return isSection(section) ? section : {};
+}
+
+/**
+ * ovcli.conf's `plugin` section as this harness sees it: the shared scalars,
+ * then `plugin.<harness>` over them in both spellings, the hyphenated one last.
+ * `loadPluginSettings` merges the same way for every other knob, and the two
+ * must agree or a key would win in the hooks and lose here.
+ */
+function pluginSection(cliFile, harness) {
+ const plugin = isSection(cliFile.plugin) ? cliFile.plugin : {};
+ const merged = {};
+ for (const [key, value] of Object.entries(plugin)) {
+ if (!isSection(value)) merged[key] = value;
+ }
+ const key = sectionKey(harness);
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ if (candidate && isSection(plugin[candidate])) Object.assign(merged, plugin[candidate]);
+ }
+ return merged;
+}
+
+/** A knob-file scalar as the schema coerces a string knob: `12345` is "12345". */
+function scalar(value) {
+ return value === undefined || value === null ? "" : String(value).trim();
}
const AUTH_MODES = ["trusted", "api_key"];
@@ -131,22 +186,8 @@ function normalizeAuthMode(value) {
return AUTH_MODES.includes(mode) ? mode : "";
}
-/**
- * Which auth mode the server is in, and with it whether the identity headers
- * may go on the wire.
- *
- * An `api_key` server reads the account and the user out of the key and ignores
- * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
- * every proxy on the path who the operator is and buys nothing. A named mode
- * wins; ov.conf's server block answers next; failing both, a credential layer
- * that supplied an identity at all means the deployment expects one.
- */
-export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
- const server = ovFile.server || {};
- const authMode = normalizeAuthMode(settings.authMode)
- || normalizeAuthMode(server.auth_mode)
- || ((account || user) ? "trusted" : "api_key");
- return { authMode, sendIdentityHeaders: authMode === "trusted" };
+function authModeIn(section) {
+ return normalizeAuthMode(section.authMode) || normalizeAuthMode(section.auth_mode);
}
function sourceMode(env) {
@@ -158,135 +199,130 @@ function sourceMode(env) {
}
function hasEnvCredentialFields(env) {
- return Boolean(
- str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
- str(env.OPENVIKING_MCP_URL, "") ||
- str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(env.OPENVIKING_USER, "") ||
- str(env.OPENVIKING_PEER_ID, ""),
- );
+ return CREDENTIAL_ENV_VARS.some((name) => str(env[name], ""));
}
-function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
- const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
- const cliUrl = str(cliFile.url, "");
-
- if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
- if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
- if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
-
- const server = ovFile.server || {};
- const ovUrl = str(server.url, "");
- if (ovUrl) return ovUrl.replace(/\/+$/, "");
+function trimSlash(value) {
+ return value.replace(/\/+$/, "");
+}
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
- return `http://${host}:${port}`;
+/** The first layer that holds a value, with the source label and file it names. */
+function firstLayer(layers) {
+ for (const [value, source, path = ""] of layers) {
+ if (value) return { value, source, path };
+ }
+ return { value: "", source: "none", path: "" };
}
/**
- * `harness` names whose ov.conf section supplies the legacy fallback. It sits
- * where it always did — after ovcli.conf, before `server.root_api_key` — but a
- * harness now reads its own section instead of every one of them reading
- * codex's. The default keeps codex, the only caller that never passes one.
+ * The one connection a harness has: which server, which key, whose identity,
+ * and whether that identity goes on the wire. Hooks reach it through
+ * `buildPluginConfig`, every MCP proxy through the same loader or through
+ * `buildProxyConnection`, so the two sides of one harness cannot disagree.
+ *
+ * Only three kinds of input count: what an embedding host named (`hostInput`),
+ * the environment, and the two files under `~/.openviking`. The working
+ * directory never does — an MCP proxy starts wherever its host launches it.
*
- * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
- * section named, which this module cannot read for itself: resolving that
- * section needs the knob schema, and the portable bundles would then have to
- * ship it. All three rank where the file they come from ranks — under
- * ovcli.conf's own fields, over ov.conf.
+ * ovcli.conf pins the chain when it names a url, key, identity or peer and the
+ * environment names none of those; pinned, the environment's credentials no
+ * longer apply. `OPENVIKING_CREDENTIAL_SOURCE` forces either side, and forced
+ * to `env` no file is read at all — which is what lets a parent process hand a
+ * resolved connection, including an empty key, to a child verbatim. Every chain
+ * runs host → env (unpinned) → ovcli.conf → its `plugin.<harness>` and
+ * `plugin` keys → ov.conf's harness section; the key then ends at
+ * `server.root_api_key`, which a pinned chain reaches only with
+ * `rootKeyFallback`, and the identity skips ov.conf's harness section when
+ * pinned. The auth mode reads the environment in either mode, then the
+ * `plugin` keys, the harness section and `server.auth_mode`; failing all of
+ * them, an identity from any layer means the deployment expects one.
*/
-export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
- const files = loadCredentialFiles(env);
+export function resolveConnection(harness, {
+ env = process.env,
+ files = null,
+ hostInput = {},
+ rootKeyFallback = false,
+} = {}) {
+ const name = str(harness, "");
+ const loaded = files || loadCredentialFiles(env);
+ const { cliFile, ovFile, cliPath, ovPath } = loaded;
+ const host = hostInput || {};
const mode = sourceMode(env);
const envHasCredentials = hasEnvCredentialFields(env);
- const useCli = mode === "cli" ||
- (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
- const cx = harnessSection(files.ovFile, harness);
- const server = files.ovFile.server || {};
-
- const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
-
- const pluginApiKey = str(plugin?.apiKey, "");
- const apiKey = useCli
- ? (str(files.cliFile.api_key, "") || pluginApiKey)
- : (
- str(env.OPENVIKING_BEARER_TOKEN, "") ||
- str(env.OPENVIKING_API_KEY, "") ||
- str(files.cliFile.api_key, "") ||
- pluginApiKey ||
- str(cx.apiKey, "") ||
- str(server.root_api_key, "")
- );
-
- const pluginAccount = str(plugin?.accountId, "");
- const account = useCli
- ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
- : (
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
- pluginAccount ||
- str(cx.accountId, "")
- );
-
- const pluginUser = str(plugin?.userId, "");
- const user = useCli
- ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
- : (
- str(env.OPENVIKING_USER, "") ||
- str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
- pluginUser ||
- str(cx.userId, "")
- );
-
- const peerId = useCli
- ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
- : (
- str(env.OPENVIKING_PEER_ID, "") ||
- str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
- str(cx.peerId, str(cx.peer_id, ""))
- );
-
- const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
- const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
-
- // Which layer actually supplied the api_key, following the same chain, and
- // the file behind it — empty when the key came from the environment or was
- // never found. `apiKeySource` is what a doctor and a 401 hint report; the
- // credential *source* beside it is the mode the chain ran in, not a file.
- let apiKeySource = "none";
- let credentialPath = "";
- if (apiKey) {
- if (useCli) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
- apiKeySource = "env";
- } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else {
- apiKeySource = "ov";
- credentialPath = files.ovPath;
- }
- }
+ const pinned = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && Boolean(cliPath) && hasCredentialFields(cliFile));
+ const unpinned = (layer) => (pinned ? [] : [layer]);
+ const fromFiles = mode !== "env";
+ const filed = (...layers) => (fromFiles ? layers : []);
+ const plugin = pluginSection(cliFile, name);
+ const section = harnessSection(ovFile, name);
+ const server = isSection(ovFile.server) ? ovFile.server : {};
+
+ const key = firstLayer([
+ [str(host.apiKey, ""), "host"],
+ ...unpinned([str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")), "env"]),
+ ...filed(
+ [str(cliFile.api_key, ""), "ovcli", cliPath],
+ [scalar(plugin.apiKey), "ovcli", cliPath],
+ [scalar(section.apiKey), "ov", ovPath],
+ ),
+ ...((pinned && !rootKeyFallback) ? [] : filed([str(server.root_api_key, ""), "ov", ovPath])),
+ ]);
+
+ const identity = (hostValue, envName, cliValue, knob) => firstLayer([
+ [str(hostValue, ""), "host"],
+ ...unpinned([str(env[envName], ""), "env"]),
+ ...filed([cliValue, "ovcli", cliPath], [scalar(plugin[knob]), "ovcli", cliPath]),
+ ...(pinned ? [] : filed([str(section[knob], ""), "ov", ovPath])),
+ ]).value;
+ const account = identity(host.account, "OPENVIKING_ACCOUNT", str(cliFile.account, str(cliFile.account_id, "")), "accountId");
+ const user = identity(host.user, "OPENVIKING_USER", str(cliFile.user, str(cliFile.user_id, "")), "userId");
+
+ const peerId = firstLayer([
+ ...unpinned([str(env.OPENVIKING_PEER_ID, ""), "env"]),
+ ...filed([str(cliFile.actor_peer_id, str(cliFile.peer_id, "")), "ovcli"]),
+ ...(pinned ? [] : filed([str(section.peerId, str(section.peer_id, "")), "ov"])),
+ ]).value;
+
+ const authMode = normalizeAuthMode(host.authMode)
+ || normalizeAuthMode(env.OPENVIKING_AUTH_MODE)
+ || (fromFiles && (authModeIn(plugin) || authModeIn(section) || normalizeAuthMode(server.auth_mode)))
+ || ((account || user) ? "trusted" : "api_key");
+
+ const hostBaseUrl = trimSlash(str(host.baseUrl, ""));
+ const envUrl = pinned ? "" : str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const fileUrl = fromFiles ? (str(cliFile.url, "") || str(server.url, "")) : "";
+ const baseUrl = hostBaseUrl || trimSlash(envUrl || fileUrl) || serverAddress(fromFiles ? server : {});
+ const envMcpUrl = pinned ? "" : str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (!hostBaseUrl && envMcpUrl) ? envMcpUrl : `${baseUrl}/mcp`;
return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- apiKeySource,
- credentialPath,
+ ...loaded,
+ harness: name,
+ credentialSource: pinned ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
baseUrl,
mcpUrl,
- apiKey,
+ apiKey: key.value,
account,
user,
peerId,
- hasApiKey: Boolean(apiKey),
+ authMode,
+ sendIdentityHeaders: authMode === "trusted",
+ hasApiKey: Boolean(key.value),
+ // Which layer supplied the key and the file behind it, empty when the key
+ // came from the host or the environment. A doctor and a 401 hint report it;
+ // `credentialSource` is the mode the chain ran in, not a file.
+ apiKeySource: key.source,
+ credentialPath: key.path,
};
}
+function serverAddress(server) {
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
function envFlag(env, name) {
const raw = str(env[name], "").toLowerCase();
return raw === "1" || raw === "true" || raw === "yes";
@@ -304,9 +340,8 @@ function clampTimeout(value) {
* `buildPluginConfig` answers the same question one layer up, but reaching it
* means vendoring the knob schema and the workspace layers — a closure the
* portable agent-plugins bundle would carry in git to send one HTTP header.
- * This is the connection half alone: the credential chain, the auth mode that
- * decides whether the identity headers may go on the wire, the User-Agent, the
- * request timeout, and the debug log.
+ * This is the same connection plus what a proxy adds to it: the User-Agent,
+ * the request timeout, and the debug log.
*
* The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
* chain to itself. A portable package has no installer to migrate anyone, so
@@ -314,62 +349,27 @@ function clampTimeout(value) {
*/
export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
const name = str(harness);
- const credentials = resolveOpenVikingCredentials(env, name);
-
- let { apiKey, apiKeySource, credentialPath } = credentials;
- if (!apiKey) {
- apiKey = str(credentials.ovFile?.server?.root_api_key);
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
-
+ const connection = resolveConnection(name, { env, rootKeyFallback: true });
return {
harness: name,
userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
- baseUrl: credentials.baseUrl,
- mcpUrl: credentials.mcpUrl,
- apiKey,
- account: credentials.account,
- user: credentials.user,
- peerId: credentials.peerId,
- ...resolveAuthMode({
- settings: { authMode: env.OPENVIKING_AUTH_MODE },
- ovFile: credentials.ovFile,
- account: credentials.account,
- user: credentials.user,
- }),
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ baseUrl: connection.baseUrl,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
+ account: connection.account,
+ user: connection.user,
+ peerId: connection.peerId,
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
debug: envFlag(env, "OPENVIKING_DEBUG"),
debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
|| join(homedir(), ".openviking", "logs", `${name}.log`),
};
}
-
-function main() {
- const cmd = process.argv[2] || "";
- if (cmd === "mcp-url") {
- process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
- return;
- }
- if (cmd === "has-api-key") {
- process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
- return;
- }
- if (cmd === "has-peer-id") {
- process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
- return;
- }
- process.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
- process.exitCode = 2;
-}
-
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- main();
-}
diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
index 7cdd797cf..a24da5b29 100644
--- a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
@@ -1143,7 +1143,7 @@ export function inspectConfigFiles(report, { harness = "", launcherHint = "this
* block from `server.root_api_key`.
*
* The identity has no such answer to read, so account and user follow the chain
- * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * in `resolveConnection` step for step: pinned to ovcli.conf it ends
* at that file's `plugin` section, and otherwise the environment wins and
* ov.conf's harness block is last.
*/
@@ -1157,14 +1157,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
const scoped = (section && plugin[section]) || {};
const block = (section && ov[section]) || {};
const server = ov.server || {};
- // Pinned to ovcli.conf, the chain never looks at the environment.
+ // Pinned to ovcli.conf, the chain never looks at the environment; forced to
+ // the environment, it never looks at a file.
const pinned = cfg.credentialSource === "ovcli";
+ const envOnly = /^(env|environment)$/i.test(String(env.OPENVIKING_CREDENTIAL_SOURCE || env.OPENVIKING_CREDENTIALS_SOURCE || "").trim());
const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
const url = (!pinned && envUrl) ? "env"
- : cli.url ? cliShort
- : server.url ? ovShort
- : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+ : envOnly ? "default (http://127.0.0.1:1933)"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
let apiKey;
if (cfg.apiKeySource === "env") {
@@ -1179,15 +1182,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
} else if (cfg.apiKeySource === "host") {
apiKey = "the host application";
} else {
- apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)"
+ : envOnly ? "(none — env mode reads no file)" : "(none)";
}
const identity = (envName, cliValue, name) => (
(!pinned && env[envName]) ? "env"
- : cliValue ? cliShort
- : scoped[name] ? `${cliShort} plugin.${section}.${name}`
- : plugin[name] ? `${cliShort} plugin.${name}`
- : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ : envOnly ? "(unset)"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
);
return {
url,
diff --git a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
index c1e527967..e4f2428cc 100644
--- a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
@@ -12,9 +12,56 @@
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
+import { CONNECTION_ENV_VARS, CREDENTIAL_ENV_VARS } from "./credentials.mjs";
+
export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
const MIN_PROXY_TIMEOUT_MS = 1000;
+/**
+ * Every variable that changes what an MCP proxy sends. Hooks inherit their
+ * host's whole environment; a host that hands its MCP servers an allowlist
+ * instead (Codex's `env_vars`) has to name each of these, or the proxy
+ * resolves a different connection from the hooks beside it.
+ */
+export const MCP_PROXY_ENV_VARS = [
+ ...CONNECTION_ENV_VARS,
+ "OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
+ "OPENVIKING_RECALL_PEER_SCOPE",
+ "OPENVIKING_TIMEOUT_MS",
+ "OPENVIKING_DEBUG",
+ "OPENVIKING_DEBUG_LOG",
+ "OPENVIKING_EXTRA_HEADERS",
+];
+
+/**
+ * A resolved connection as the environment of a child proxy process.
+ *
+ * The other way across the process boundary, for a host that cannot hand its
+ * MCP servers the inputs (DSH drops credential-shaped names from what a child
+ * inherits): the parent resolves once and the child reads the answer back. The
+ * forced `env` source makes that exact — the child reads no file, so a key the
+ * parent left empty stays empty instead of falling through to
+ * `server.root_api_key`. Every credential variable is written, the empty ones
+ * too, because the rest of the parent's environment still reaches the child:
+ * an `OPENVIKING_ACCOUNT` the parent's pinned chain ignored must not fill the
+ * gap there.
+ */
+export function forwardConnectionEnv(connection) {
+ const env = Object.fromEntries(CREDENTIAL_ENV_VARS.map((name) => [name, ""]));
+ return {
+ ...env,
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: connection.baseUrl,
+ OPENVIKING_MCP_URL: connection.mcpUrl,
+ OPENVIKING_API_KEY: connection.apiKey || "",
+ OPENVIKING_ACCOUNT: connection.account || "",
+ OPENVIKING_USER: connection.user || "",
+ OPENVIKING_PEER_ID: connection.peerId || "",
+ OPENVIKING_AUTH_MODE: connection.authMode,
+ };
+}
+
export function trimSlash(value) {
return String(value || "").replace(/\/+$/, "");
}
@@ -55,7 +102,7 @@ export function defaultCredentialPaths(env = process.env) {
* start: the proxy is what carries every memory tool, and taking those away
* because a scope preference cannot be honoured costs the user far more than
* the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
+ * (dsh, `mcp-env.mjs`) can satisfy this without the user setting it.
*/
export function resolveMcpActorPeerId({
peerId = "",
@@ -192,3 +239,38 @@ export function buildMcpProxyConfig({
extraHeaders: resolvedExtraHeaders,
};
}
+
+/**
+ * The proxy config for a resolved harness config, mapped in one place.
+ *
+ * Every proxy used to copy fields out of its loader by hand, and the copies
+ * drifted: two dropped `mcpUrl`, so `OPENVIKING_MCP_URL` reached the hooks and
+ * not the tools. `cfg` is what `buildPluginConfig` or `buildProxyConnection`
+ * returned. `peerId` replaces the actor peer only for a harness whose parent
+ * process resolved it (dsh); everywhere else a long-lived proxy may send one
+ * only when actor-scoped recall asks for it.
+ */
+export function toMcpProxyConfig(cfg, {
+ env = process.env,
+ peerId = undefined,
+ debug = cfg.debug,
+ debugLogPath = cfg.debugLogPath,
+} = {}) {
+ return buildMcpProxyConfig({
+ baseUrl: cfg.baseUrl,
+ mcpUrl: cfg.mcpUrl,
+ apiKey: cfg.apiKey,
+ account: cfg.account,
+ user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
+ peerId: peerId === undefined ? resolveMcpActorPeerId(cfg) : peerId,
+ userAgent: cfg.userAgent,
+ timeoutMs: cfg.timeoutMs,
+ debug,
+ debugLogPath,
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.credentialPath || "",
+ watchedPaths: [cfg.cliPath, cfg.ovPath],
+ env,
+ });
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
index cbae04ab8..214a287f9 100644
--- a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
@@ -34,8 +34,7 @@ import {
buildUserAgent,
loadCredentialFiles,
readManifestVersion,
- resolveAuthMode,
- resolveOpenVikingCredentials,
+ resolveConnection,
} from "./credentials.mjs";
import {
announcedOverrides,
@@ -165,15 +164,6 @@ function ovConfSection(ovFile, key) {
return section && typeof section === "object" && !Array.isArray(section) ? section : {};
}
-/**
- * A connection value ovcli.conf's `plugin` section supplied, as opposed to
- * ov.conf's harness block or the environment — the credential chain ranks
- * those two itself, and would rank a `plugin` value wrong.
- */
-function fromPluginSection(settings, sources, name) {
- return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
-}
-
/**
* One harness's whole configuration: the files, the knobs, the peer, and the
* handful of fields derived from them.
@@ -185,12 +175,16 @@ function fromPluginSection(settings, sources, name) {
* else. What is left in a loader after this call is what only that harness
* knows.
*
- * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
- * host hands it one of its own); `hostInput` is what an embedding host named
- * for this process, which is the more specific answer and outranks every file;
- * `logFile` is the log basename this harness has always used, and a harness
- * that never had a default log path does not get one invented for it;
- * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * The connection — server, key, identity, auth mode — is not a knob: it comes
+ * from `resolveConnection`, the same call an MCP proxy's connection comes
+ * from, and the `plugin` keys and ov.conf block that name it are read there.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get for its
+ * knobs (dsh's host hands it one of its own); `hostInput` is what an embedding
+ * host named for this process, which is the more specific answer and outranks
+ * every file; `logFile` is the log basename this harness has always used, and
+ * a harness that never had a default log path does not get one invented for
+ * it; `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
* pinning and has always ended at `server.root_api_key`.
*/
export function buildPluginConfig(harness, {
@@ -218,46 +212,15 @@ export function buildPluginConfig(harness, {
cliFile: files.cliFile,
clientVersion,
});
- const credentials = resolveOpenVikingCredentials(env, key, {
- apiKey: fromPluginSection(settings, sources, "apiKey"),
- accountId: fromPluginSection(settings, sources, "accountId"),
- userId: fromPluginSection(settings, sources, "userId"),
- });
-
- // Pinned to ovcli.conf, the credential chain stops at that file. The layers
- // under it still answer: ov.conf's harness block is where tuning used to
- // live, and `server.root_api_key` is where a harness that predates the
- // pinning has always ended its chain.
- let apiKey = credentials.apiKey;
- let apiKeySource = credentials.apiKeySource;
- let credentialPath = credentials.credentialPath;
- if (!apiKey) {
- apiKey = sources.apiKey === OV_CONF_LAYER
- ? str(settings.apiKey)
- : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
- const hostApiKey = str(hostInput.apiKey);
- if (hostApiKey) {
- apiKey = hostApiKey;
- apiKeySource = "host";
- credentialPath = "";
- }
-
- const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
- const baseUrl = hostBaseUrl || credentials.baseUrl;
- const account = str(hostInput.account) || credentials.account;
- const user = str(hostInput.user) || credentials.user;
+ const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback });
+ const { baseUrl, account, user } = connection;
const timeoutMs = settings.timeoutMs;
const peerId = resolvePluginPeerId({
settings,
configured,
sources,
- credentials,
- hostInput: hostInput.peerId,
+ credentials: connection,
+ hostInput: hostInput?.peerId,
env,
});
@@ -268,21 +231,22 @@ export function buildPluginConfig(harness, {
userAgent: buildUserAgent(name, clientVersion),
baseUrl,
- mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
- apiKey,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
account,
user,
- ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- configPath: credentials.cliPath || credentials.ovPath || null,
- cliConfigPath: credentials.cliPath,
- ovConfigPath: credentials.ovPath,
- cliPath: credentials.cliPath,
- ovPath: credentials.ovPath,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ configPath: connection.cliPath || connection.ovPath || null,
+ cliConfigPath: connection.cliPath,
+ ovConfigPath: connection.ovPath,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
peerId,
explicitPeerId: peerId,
@@ -309,7 +273,7 @@ export function buildPluginConfig(harness, {
// it per session, against the directory the payload names, and an MCP proxy
// must not derive one from wherever it happened to be launched.
if (deriveEffectivePeer) {
- const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env });
config.effectivePeer = effectivePeer;
config.legacyPeerId = effectivePeer.legacyPeerId;
}
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
index 162dbf1d7..e2899df4e 100644
--- a/examples/codex-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
@@ -3,41 +3,20 @@
/**
* stdio -> streamable-HTTP MCP proxy for the OpenViking Codex plugin.
*
- * Codex starts this process as a local stdio MCP server. The proxy reads the
- * same OpenViking credential sources as the lifecycle hooks, forwards JSON-RPC
- * requests to the server's /mcp endpoint, and keeps stdout protocol-clean.
+ * Codex starts this process as a local stdio MCP server. The proxy resolves its
+ * connection through the hooks' own `loadConfig()`, forwards JSON-RPC requests
+ * to the server's /mcp endpoint, and keeps stdout protocol-clean.
*/
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../scripts/config.mjs";
import { createLogger } from "../scripts/debug-log.mjs";
-import { resolveOpenVikingCredentials } from "../scripts/shared/credentials.mjs";
-import {
- buildMcpProxyConfig,
- resolveMcpActorPeerId,
-} from "../scripts/shared/mcp-proxy-config.mjs";
+import { toMcpProxyConfig } from "../scripts/shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
-function readProxyConfig() {
- const creds = resolveOpenVikingCredentials();
- const cfg = loadConfig();
- return buildMcpProxyConfig({
- baseUrl: creds.baseUrl,
- mcpUrl: creds.mcpUrl,
- apiKey: creds.apiKey,
- account: creds.account,
- user: creds.user,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
- peerId: resolveMcpActorPeerId(cfg),
- userAgent: cfg.userAgent,
- timeoutMs: cfg.timeoutMs,
- debug: cfg.debug,
- debugLogPath: cfg.debugLogPath,
- credentialSource: creds.credentialSource,
- credentialPath: creds.credentialPath,
- watchedPaths: [creds.cliPath, creds.ovPath, creds.cliPathCandidate],
- });
+export function readProxyConfig(env = process.env) {
+ return toMcpProxyConfig(loadConfig(undefined, { env }), { env });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
index 9fa7cb31b..c929cb9b4 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -25,7 +25,7 @@ and `CODEX_CONFIG_FILE` relocate individual pieces.
## Config resolution
-`OPENVIKING_CREDENTIAL_SOURCE` picks the mode: `env` (env vars only), `cli`
+`OPENVIKING_CREDENTIAL_SOURCE` picks the mode: `env` (env vars only, neither file), `cli`
(ovcli.conf only — env and ov.conf ignored), default `auto` (env vars win when
any credential var is set, else ovcli.conf, else ov.conf/defaults). The
doctor prints the effective mode as `credential source`.
@@ -37,9 +37,11 @@ doctor prints the effective mode as `credential source`.
| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/account_id`, `user/user_id` → `ovcli.conf plugin.codex.accountId/userId` → `ovcli.conf plugin.accountId/userId` → `ov.conf codex.accountId/userId` |
| peer | `OPENVIKING_PEER_ID` → registry → `config.local.json` → `config.json` (`peer.id`) → `ovcli.conf plugin.codex.peerId` → `ovcli.conf plugin.peerId` → `ovcli.conf actor_peer_id/peer_id` → `ov.conf codex.peerId` → derived per `peer.source` unless `OPENVIKING_WORKSPACE_PEER=0` |
| peer.source | `OPENVIKING_PEER_SOURCE` → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.codex.peerSource` → `ovcli.conf plugin.peerSource` → `ov.conf codex.peerSource` → `git` |
-| auth mode | `OPENVIKING_AUTH_MODE` → `codex.authMode` → `server.auth_mode` → `trusted` when account/user are set, else `api_key` |
+| auth mode | `OPENVIKING_AUTH_MODE` → `ovcli.conf plugin.codex.authMode` → `ovcli.conf plugin.authMode` → `ov.conf codex.authMode` → `ov.conf server.auth_mode` → `trusted` when account/user are set, else `api_key` |
| tuning | env → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.codex.*` → `ovcli.conf plugin.*` → `ov.conf codex.*` → defaults |
+When ovcli.conf names a url, key, identity or peer and no credential variable is set, the chain is pinned to that file: the credential variables are skipped, `api_key` still falls back to `plugin.codex.apiKey` → `plugin.apiKey` → `ov.conf codex.apiKey` but never to `server.root_api_key`, and account/user stop at the `plugin` keys. The MCP proxy resolves this same chain from the variables `.mcp.json` forwards.
+
`peer.source` decides the derivation. `git` (the default) is the template list `["{git_remote}", "{git_root}"]`: the normalized origin URL (`[email protected]:volcengine/OpenViking.git` → `github.com-volcengine-openviking`, userinfo dropped so an embedded token can never reach the id), else the repository root path (the legacy `[^A-Za-z0-9] → -` rule), else nothing — outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space. `{cwd}` is still a variable but sits in no default chain, and `{dir}` is the workspace root's directory name, empty when the directory is not a workspace. `cwd` is that legacy rule alone (the pre-git behaviour); `none` sends no peer, which is also what `OPENVIKING_WORKSPACE_PEER=0` means. Anything else is a template, or a list of templates tried in order (`"git-{git_remote}"`, `["team-{dir}", "{cwd}"]`); a template naming an empty variable falls through to the next. Derivation is filesystem-only — no `git` subprocess, which also keeps it inside the hook budgets below — so it survives a missing `git` and a dubious-ownership refusal; worktrees converge through `commondir`, a submodule keeps its own identity, and `$HOME` and `/` are never workspace roots. Every clone of one repository shares one peer; a fork's origin differs, so it stays separate, and `gh pr checkout` does not change origin.
Peers minted before this need no migration: the old cwd-derived id is recomputed locally, `peer_scope: "all"` already sweeps it, and under `"actor"` recall asks it separately. Doctor prints it as `previous peer`. Across the workspace layers lists union rather than replace, with a leading `"!reset"` dropping what the lower layers contributed; unknown keys are kept and ignored, and a file declaring a version other than `1` is skipped with a warning.
diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.md
index fc6a6c19a..0d728a9b8 100644
--- a/examples/dsh-memory-plugin/README.md
+++ b/examples/dsh-memory-plugin/README.md
@@ -124,11 +124,13 @@ SDK client opens that standalone stream it stops resolving POST responses, so
`tools/list` never returns. The proxy owns the transport itself and is
unaffected.
-The bundle's resolved credentials travel to the proxy through the child
-environment, because DSH scrubs credential-shaped names out of the inherited env
-and a subprocess cannot see the Cordis patch; the proxy then applies the usual
-`OPENVIKING_*` → `ovcli.conf` → `ov.conf` chain and reloads when those files
-change.
+The bundle's resolved connection — url, MCP url, key, account, user and auth
+mode — travels to the proxy through the child environment, because DSH scrubs
+credential-shaped names out of the inherited env and a subprocess cannot see the
+Cordis patch. It goes with `OPENVIKING_CREDENTIAL_SOURCE=env`, so the proxy reads
+no config file and reaches the server exactly as the runtime does, including
+with no key when the runtime has none. A changed `ovcli.conf` therefore takes
+effect for the tools when DSH restarts the bundle, as it does for the runtime.
Two consequences follow from the proxy being one process per profile:
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
index 0661354dc..7aecb5d91 100644
--- a/examples/dsh-memory-plugin/config.mjs
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -1,7 +1,7 @@
import { buildPluginConfig } from "./shared/plugin-config.mjs";
import { loadCredentialFiles } from "./shared/credentials.mjs";
-export const PLUGIN_VERSION = "0.4.2";
+export const PLUGIN_VERSION = "0.4.3";
/**
* Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool
@@ -17,8 +17,9 @@ export const MCP_SERVER_NAME = "openviking";
* file of its own. Every knob is declared in `shared/config-schema.mjs`, and
* `ovcli.conf`'s `plugin` section outranks the host's input so one file
* configures every harness and `ov config switch` moves them together.
- * Connection fields are the exception: an endpoint or key named by the host is
- * the more specific answer and stays ahead of the credential chain.
+ * Connection fields are the exception: an endpoint, key, identity or auth mode
+ * named by the host is the more specific answer and stays ahead of the
+ * credential chain.
*/
export function resolveConfig(input = {}, env = process.env, cwd = process.cwd()) {
// ov.conf's `dsh` section is the legacy layer here as everywhere else, but
@@ -36,6 +37,8 @@ export function resolveConfig(input = {}, env = process.env, cwd = process.cwd()
user: input.user,
apiKey: input.apiKey,
baseUrl: input.endpoint,
+ // The legacy knob layer this used to ride accepted both spellings.
+ authMode: input.authMode || input.auth_mode,
},
deriveEffectivePeer: true,
});
diff --git a/examples/dsh-memory-plugin/config.test.mjs b/examples/dsh-memory-plugin/config.test.mjs
index 40ecc5e8b..6d1b7198e 100644
--- a/examples/dsh-memory-plugin/config.test.mjs
+++ b/examples/dsh-memory-plugin/config.test.mjs
@@ -50,6 +50,15 @@ test("explicit plugin config overrides credential files", () => {
assert.equal(config.peerId, "plugin-peer");
});
+test("the host's auth mode outranks the environment in either spelling", () => {
+ const env = { OPENVIKING_CLI_CONFIG_FILE: "/nonexistent/ovcli.conf", OPENVIKING_CONFIG_FILE: "/nonexistent/ov.conf", OPENVIKING_AUTH_MODE: "trusted" };
+ for (const input of [{ authMode: "api_key" }, { auth_mode: "api_key" }]) {
+ const config = resolveConfig({ account: "acme", workspacePeer: false, ...input }, env, "/workspace/project");
+ assert.equal(config.authMode, "api_key", JSON.stringify(input));
+ assert.equal(config.sendIdentityHeaders, false);
+ }
+});
+
// A knob set once in ovcli.conf reaches this harness like any other, and the
// host's own input is the lower layer.
test("the ovcli.conf plugin section outranks the cordis input", async () => {
diff --git a/examples/dsh-memory-plugin/mcp-env.mjs b/examples/dsh-memory-plugin/mcp-env.mjs
new file mode 100644
index 000000000..70eed3b5b
--- /dev/null
+++ b/examples/dsh-memory-plugin/mcp-env.mjs
@@ -0,0 +1,33 @@
+import { fileURLToPath } from "node:url";
+
+import { MCP_SERVER_NAME } from "./config.mjs";
+import { forwardConnectionEnv } from "./shared/mcp-proxy-config.mjs";
+
+/** The same stdio proxy every other OpenViking memory integration starts. */
+export const PROXY_PATH = fileURLToPath(new URL("./servers/mcp-proxy.mjs", import.meta.url));
+
+/**
+ * Build the dsh-mcp-client config for the OpenViking stdio proxy.
+ *
+ * DSH scrubs credential-shaped names out of the environment a subprocess
+ * inherits, and the Cordis patch is invisible to one, so the proxy cannot
+ * resolve the connection the way this process did. It gets the answer instead:
+ * the resolved connection and this session's peer, forwarded with the forced
+ * `env` source so the child reads no file and lands on exactly this url, key,
+ * identity, auth mode and peer — the empty ones included.
+ */
+export function buildMcpConfig(config) {
+ // In DSH Desktop, process.execPath is Electron's executable rather than a
+ // standalone Node binary. This tells Electron to run the proxy script as
+ // Node instead of attempting to launch a second Desktop instance.
+ const env = { ELECTRON_RUN_AS_NODE: "1", ...forwardConnectionEnv(config) };
+ if (config.timeoutMs) env.OPENVIKING_TIMEOUT_MS = String(config.timeoutMs);
+ return {
+ transport: "stdio",
+ serverName: MCP_SERVER_NAME,
+ command: process.execPath,
+ args: [PROXY_PATH],
+ env,
+ toolCallTimeoutMs: config.mcpToolCallTimeoutMs,
+ };
+}
diff --git a/examples/dsh-memory-plugin/mcp.mjs b/examples/dsh-memory-plugin/mcp.mjs
index 06740ef9b..6018353f3 100644
--- a/examples/dsh-memory-plugin/mcp.mjs
+++ b/examples/dsh-memory-plugin/mcp.mjs
@@ -1,39 +1,8 @@
-import { fileURLToPath } from "node:url";
import * as mcpClient from "@deepseek-ai/dsh-mcp-client";
-import { MCP_SERVER_NAME } from "./config.mjs";
+import { buildMcpConfig } from "./mcp-env.mjs";
-/** The same stdio proxy every other OpenViking memory integration starts. */
-export const PROXY_PATH = fileURLToPath(new URL("./servers/mcp-proxy.mjs", import.meta.url));
-
-/**
- * Build the dsh-mcp-client config for the OpenViking stdio proxy.
- *
- * The bundle's own credential resolution (`OPENVIKING_*` → `ovcli.conf` →
- * `ov.conf`, plus anything set in the Cordis patch) is forwarded through the
- * child environment: DSH scrubs credential-shaped names out of the inherited
- * env, and the patch is invisible to a subprocess, so values the runtime
- * already resolved have to be passed explicitly.
- */
-export function buildMcpConfig(config) {
- // In DSH Desktop, process.execPath is Electron's executable rather than a
- // standalone Node binary. This tells Electron to run the proxy script as
- // Node instead of attempting to launch a second Desktop instance.
- const env = { ELECTRON_RUN_AS_NODE: "1" };
- if (config.endpoint) env.OPENVIKING_URL = config.endpoint;
- if (config.apiKey) env.OPENVIKING_API_KEY = config.apiKey;
- if (config.account) env.OPENVIKING_ACCOUNT = config.account;
- if (config.user) env.OPENVIKING_USER = config.user;
- if (config.peerId) env.OPENVIKING_PEER_ID = config.peerId;
- return {
- transport: "stdio",
- serverName: MCP_SERVER_NAME,
- command: process.execPath,
- args: [PROXY_PATH],
- env,
- toolCallTimeoutMs: config.mcpToolCallTimeoutMs,
- };
-}
+export { buildMcpConfig, PROXY_PATH } from "./mcp-env.mjs";
/**
* Mount the tool surface. The bridge ships with dsh itself, so it resolves
diff --git a/examples/dsh-memory-plugin/mcp.test.mjs b/examples/dsh-memory-plugin/mcp.test.mjs
index d671b3686..347317894 100644
--- a/examples/dsh-memory-plugin/mcp.test.mjs
+++ b/examples/dsh-memory-plugin/mcp.test.mjs
@@ -1,11 +1,33 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { existsSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { Config } from "@deepseek-ai/dsh-mcp-client";
import { resolveConfig } from "./config.mjs";
import { apply } from "./index.mjs";
import { buildMcpConfig, mountOpenVikingMcp, PROXY_PATH } from "./mcp.mjs";
+/**
+ * Run `fn` with an env whose credential files live in a throwaway directory,
+ * so a developer's own ~/.openviking never leaks into what is forwarded.
+ */
+function withCredentialFiles({ ovcli = null, ov = null } = {}, fn) {
+ const dir = mkdtempSync(join(tmpdir(), "ov-dsh-mcp-"));
+ try {
+ const env = {
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "ovcli.conf"),
+ OPENVIKING_CONFIG_FILE: join(dir, "ov.conf"),
+ OPENVIKING_HOME: join(dir, "home"),
+ };
+ if (ovcli) writeFileSync(env.OPENVIKING_CLI_CONFIG_FILE, JSON.stringify(ovcli));
+ if (ov) writeFileSync(env.OPENVIKING_CONFIG_FILE, JSON.stringify(ov));
+ return fn({ env, dir });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
test("the mount config validates against the pinned bridge's own schema", () => {
const config = resolveConfig({
endpoint: "http://127.0.0.1:1933",
@@ -33,47 +55,129 @@ test("the shipped proxy entrypoint exists at the mounted path", () => {
});
test("credentials resolved by the plugin reach the proxy through the child env", async () => {
- const config = resolveConfig({
- endpoint: "http://ov.example.com/",
- apiKey: "secret",
- account: "acme",
- user: "casey",
- peerId: "workspace-peer",
- }, {});
- const { env } = buildMcpConfig(config);
-
- assert.deepEqual(env, {
- ELECTRON_RUN_AS_NODE: "1",
- OPENVIKING_URL: "http://ov.example.com",
- OPENVIKING_API_KEY: "secret",
- OPENVIKING_ACCOUNT: "acme",
- OPENVIKING_USER: "casey",
- OPENVIKING_PEER_ID: "workspace-peer",
+ const { readProxyConfig } = await import("./servers/mcp-proxy.mjs");
+ await withCredentialFiles({}, ({ env: files, dir }) => {
+ const config = resolveConfig({
+ endpoint: "http://ov.example.com/",
+ apiKey: "secret",
+ account: "acme",
+ user: "casey",
+ peerId: "workspace-peer",
+ }, files, dir);
+ const { env } = buildMcpConfig(config);
+
+ assert.deepEqual(env, {
+ ELECTRON_RUN_AS_NODE: "1",
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: "http://ov.example.com",
+ OPENVIKING_BASE_URL: "",
+ OPENVIKING_MCP_URL: "http://ov.example.com/mcp",
+ OPENVIKING_BEARER_TOKEN: "",
+ OPENVIKING_API_KEY: "secret",
+ OPENVIKING_ACCOUNT: "acme",
+ OPENVIKING_USER: "casey",
+ OPENVIKING_PEER_ID: "workspace-peer",
+ OPENVIKING_AUTH_MODE: "trusted",
+ OPENVIKING_TIMEOUT_MS: "10000",
+ });
+
+ // The proxy must reconstruct the same target from that env alone — DSH
+ // scrubs credential-shaped names out of the inherited environment, so this
+ // is the only channel patch-provided values travel on.
+ const proxy = readProxyConfig(env, dir);
+ assert.equal(proxy.mcpUrl, "http://ov.example.com/mcp");
+ assert.equal(proxy.apiKey, "secret");
+ assert.equal(proxy.account, "acme");
+ assert.equal(proxy.user, "casey");
+ assert.equal(proxy.sendIdentityHeaders, true);
+ assert.equal(proxy.peerId, "workspace-peer");
+ });
+});
+
+test("a key the plugin left empty stays empty in the proxy", async () => {
+ // ovcli.conf naming only a url pins the chain to that file, so the runtime
+ // sends no key. The proxy's env names a url, which would have unpinned the
+ // chain there and let it fall through to the machine's root key.
+ const { readProxyConfig } = await import("./servers/mcp-proxy.mjs");
+ await withCredentialFiles({
+ ovcli: { url: "https://ov.example.com" },
+ ov: { server: { root_api_key: "root-key" } },
+ }, ({ env: files, dir }) => {
+ const config = resolveConfig({ workspacePeer: false }, files, dir);
+ assert.equal(config.apiKey, "");
+
+ // The file paths stand in for the default ~/.openviking the child can
+ // still reach.
+ const proxy = readProxyConfig({ ...files, ...buildMcpConfig(config).env }, dir);
+ assert.equal(proxy.mcpUrl, "https://ov.example.com/mcp");
+ assert.equal(proxy.apiKey, "");
});
+});
- // The proxy must reconstruct the same target from that env alone — DSH
- // scrubs credential-shaped names out of the inherited environment, so this
- // is the only channel patch-provided values travel on.
+test("what DSH lets the proxy inherit cannot fill a gap the runtime left", async () => {
const { readProxyConfig } = await import("./servers/mcp-proxy.mjs");
- const proxy = readProxyConfig(env, "/workspace");
- assert.equal(proxy.mcpUrl, "http://ov.example.com/mcp");
- assert.equal(proxy.apiKey, "secret");
- assert.equal(proxy.account, "acme");
- assert.equal(proxy.user, "casey");
- assert.equal(proxy.peerId, "workspace-peer");
+ await withCredentialFiles({ ovcli: { url: "https://ov.example.com", api_key: "cli-key" } }, ({ env: files, dir }) => {
+ // DSH drops only names matching /KEY|PASSWORD|SECRET|TOKEN/i from what a
+ // child inherits, so these reach the proxy beside the forwarded ones. The
+ // repository makes the launch directory one a peer could be derived from.
+ const repo = join(dir, "repo");
+ mkdirSync(join(repo, ".git"), { recursive: true });
+ writeFileSync(join(repo, ".git", "HEAD"), "ref: refs/heads/main\n");
+ const inherited = {
+ ...files,
+ OPENVIKING_CREDENTIALS_SOURCE: "cli",
+ OPENVIKING_ACCOUNT: "stale-account",
+ OPENVIKING_USER: "stale-user",
+ OPENVIKING_PEER_ID: "stale-peer",
+ };
+ const config = resolveConfig({ workspacePeer: false }, inherited, dir);
+ const seen = (c) => ({ account: c.account, user: c.user, peerId: c.peerId, sendIdentityHeaders: c.sendIdentityHeaders });
+ assert.deepEqual(seen(config), { account: "", user: "", peerId: "", sendIdentityHeaders: false });
+
+ const proxy = readProxyConfig({ ...inherited, ...buildMcpConfig(config).env }, repo);
+ assert.deepEqual(seen(proxy), seen(config));
+ });
});
-test("an anonymous local server forwards no credential env", () => {
- // Built from a literal rather than resolveConfig: the credential chain
- // reaches ~/.openviking/*.conf, so a developer's own key would leak in.
- const { env } = buildMcpConfig({
- endpoint: "http://127.0.0.1:1933",
- mcpToolCallTimeoutMs: 60000,
+test("the auth mode and timeout the host named reach the proxy too", async () => {
+ const { readProxyConfig } = await import("./servers/mcp-proxy.mjs");
+ await withCredentialFiles({}, ({ env: files, dir }) => {
+ const config = resolveConfig({
+ endpoint: "http://ov.example.com",
+ apiKey: "secret",
+ account: "acme",
+ user: "casey",
+ authMode: "api_key",
+ timeoutMs: 45000,
+ }, { ...files, OPENVIKING_AUTH_MODE: "trusted" }, dir);
+ assert.equal(config.sendIdentityHeaders, false, "the host's answer outranks the environment");
+
+ // Left to derive them, the proxy would call an account and user "trusted"
+ // and fall back to the harness default timeout.
+ const proxy = readProxyConfig(buildMcpConfig(config).env, dir);
+ assert.equal(proxy.sendIdentityHeaders, false);
+ assert.equal(proxy.timeoutMs, 45000);
});
+});
+
+test("an anonymous local server forwards no key or identity", () => {
+ withCredentialFiles({}, ({ env: files, dir }) => {
+ const { env } = buildMcpConfig(resolveConfig({ endpoint: "http://127.0.0.1:1933", workspacePeer: false }, files, dir));
- assert.deepEqual(env, {
- ELECTRON_RUN_AS_NODE: "1",
- OPENVIKING_URL: "http://127.0.0.1:1933",
+ assert.deepEqual(env, {
+ ELECTRON_RUN_AS_NODE: "1",
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: "http://127.0.0.1:1933",
+ OPENVIKING_BASE_URL: "",
+ OPENVIKING_MCP_URL: "http://127.0.0.1:1933/mcp",
+ OPENVIKING_BEARER_TOKEN: "",
+ OPENVIKING_API_KEY: "",
+ OPENVIKING_ACCOUNT: "",
+ OPENVIKING_USER: "",
+ OPENVIKING_PEER_ID: "",
+ OPENVIKING_AUTH_MODE: "api_key",
+ OPENVIKING_TIMEOUT_MS: "10000",
+ });
});
});
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index 1b7159249..4aff24e29 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.4.2",
+ "version": "0.4.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.4.2",
+ "version": "0.4.3",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index 6ed5b32f9..826fb1de6 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.4.2",
+ "version": "0.4.3",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"type": "module",
"main": "index.mjs",
@@ -14,6 +14,7 @@
"capture.mjs",
"lifecycle.mjs",
"mcp.mjs",
+ "mcp-env.mjs",
"runtime.mjs",
"skills.mjs",
"uri-guard.mjs",
diff --git a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
index 8bcd4deec..453ea16be 100644
--- a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
@@ -4,41 +4,30 @@
* stdio -> streamable-HTTP MCP proxy for the OpenViking DSH bundle.
*
* DSH's MCP bridge starts this process as a local stdio MCP server. The proxy
- * reads the same OpenViking credential sources as the in-process runtime; the
- * bundle also forwards its resolved config through the child environment, so
- * values that came from the Cordis patch survive the process boundary.
+ * resolves its connection through the same `resolveConfig()` as the in-process
+ * runtime, from the child environment the bundle builds in `mcp.mjs`: DSH
+ * scrubs credential-shaped names out of what it inherits, and values that came
+ * from the Cordis patch are invisible to a subprocess otherwise.
*/
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveConfig } from "../config.mjs";
-import { resolveOpenVikingCredentials } from "../shared/credentials.mjs";
import { createLogger } from "../shared/debug-log.mjs";
-import { buildMcpProxyConfig } from "../shared/mcp-proxy-config.mjs";
+import { toMcpProxyConfig } from "../shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../shared/mcp-proxy-core.mjs";
export function readProxyConfig(env = process.env, cwd = process.cwd()) {
const cfg = resolveConfig({}, env, cwd);
- const creds = resolveOpenVikingCredentials(env, "dsh");
- return buildMcpProxyConfig({
- baseUrl: cfg.endpoint,
- apiKey: cfg.apiKey,
- account: cfg.account,
- user: cfg.user,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
+ return toMcpProxyConfig(cfg, {
+ env,
// Not gated through `resolveMcpActorPeerId` like the other proxies: DSH's
// parent process resolves the peer per session and hands it over in the
- // child env (`mcp.mjs` `buildMcpConfig`), so this one is not a guess at the
- // launch directory.
- peerId: cfg.peerId,
- userAgent: cfg.userAgent,
- timeoutMs: cfg.requestTimeoutMs,
+ // child env. Empty means it has none, and deriving one from wherever DSH
+ // launched this process would send a peer the runtime does not.
+ peerId: String(env.OPENVIKING_PEER_ID || "").trim(),
debug: Boolean(env.OV_DEBUG_LOG),
- debugLogPath: env.OV_DEBUG_LOG,
- credentialSource: creds.credentialSource,
- credentialPath: creds.cliPath || creds.ovPath,
- watchedPaths: [creds.cliPath, creds.ovPath, creds.cliPathCandidate],
- env,
+ debugLogPath: env.OV_DEBUG_LOG || "",
});
}
diff --git a/examples/memory-plugin-shared/credentials.test.mjs b/examples/memory-plugin-shared/credentials.test.mjs
index b06ff608a..44ad67695 100644
--- a/examples/memory-plugin-shared/credentials.test.mjs
+++ b/examples/memory-plugin-shared/credentials.test.mjs
@@ -3,188 +3,322 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { resolveOpenVikingCredentials } from "./lib/credentials.mjs";
+import { KNOB_BY_NAME } from "./lib/config-schema.mjs";
+import { CONNECTION_ENV_VARS, CREDENTIAL_ENV_VARS, resolveConnection } from "./lib/credentials.mjs";
-async function tempJson(prefix, value) {
- const dir = await mkdtemp(join(tmpdir(), prefix));
- const path = join(dir, "ovcli.conf");
- await writeFile(path, JSON.stringify(value, null, 2) + "\n");
- return { dir, path };
+/**
+ * Run `fn` against an ovcli.conf / ov.conf pair in a throwaway directory. A
+ * file given as `null` is not written, so the chain sees it as absent.
+ */
+async function withFiles({ ovcli = null, ov = null }, fn) {
+ const dir = await mkdtemp(join(tmpdir(), "ov-creds-"));
+ const cliPath = join(dir, "ovcli.conf");
+ const ovPath = join(dir, "ov.conf");
+ if (ovcli) await writeFile(cliPath, JSON.stringify(ovcli));
+ if (ov) await writeFile(ovPath, JSON.stringify(ov));
+ const env = { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: ovPath };
+ const write = async (files) => {
+ if (files.ovcli) await writeFile(cliPath, JSON.stringify(files.ovcli));
+ if (files.ov) await writeFile(ovPath, JSON.stringify(files.ov));
+ };
+ try {
+ return await fn({ env, cliPath, ovPath, write });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
}
+const identity = (c) => ({ apiKey: c.apiKey, account: c.account, user: c.user });
+
test("credential env wins over ovcli config by default", async () => {
- const { dir, path } = await tempJson("ov-creds-cli-", {
- url: "https://ov.example.com",
- api_key: "cli-key",
- account: "default",
- user: "zeus",
- actor_peer_id: "peer-a",
- });
- try {
- const creds = resolveOpenVikingCredentials({
- OPENVIKING_CLI_CONFIG_FILE: path,
- OPENVIKING_URL: "https://stale.example.com",
- OPENVIKING_MCP_URL: "https://stale.example.com/mcp",
- OPENVIKING_API_KEY: "stale-key",
- OPENVIKING_ACCOUNT: "stale-account",
- OPENVIKING_USER: "stale-user",
- OPENVIKING_PEER_ID: "stale-peer",
+ await withFiles({
+ ovcli: { url: "https://ov.example.com", api_key: "cli-key", account: "default", user: "zeus", actor_peer_id: "peer-a" },
+ }, async ({ env }) => {
+ const creds = resolveConnection("codex", {
+ env: {
+ ...env,
+ OPENVIKING_URL: "https://stale.example.com",
+ OPENVIKING_MCP_URL: "https://stale.example.com/mcp",
+ OPENVIKING_API_KEY: "stale-key",
+ OPENVIKING_ACCOUNT: "stale-account",
+ OPENVIKING_USER: "stale-user",
+ OPENVIKING_PEER_ID: "stale-peer",
+ },
});
assert.equal(creds.credentialSource, "env");
assert.equal(creds.baseUrl, "https://stale.example.com");
assert.equal(creds.mcpUrl, "https://stale.example.com/mcp");
- assert.equal(creds.apiKey, "stale-key");
- assert.equal(creds.account, "stale-account");
- assert.equal(creds.user, "stale-user");
+ assert.deepEqual(identity(creds), { apiKey: "stale-key", account: "stale-account", user: "stale-user" });
assert.equal(creds.peerId, "stale-peer");
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
+ });
});
test("env source can be forced explicitly", async () => {
- const { dir, path } = await tempJson("ov-creds-env-", {
- url: "https://ov.example.com",
- api_key: "cli-key",
- user: "zeus",
- });
- try {
- const creds = resolveOpenVikingCredentials({
- OPENVIKING_CREDENTIAL_SOURCE: "env",
- OPENVIKING_CLI_CONFIG_FILE: path,
- OPENVIKING_URL: "https://env.example.com",
- OPENVIKING_MCP_URL: "https://env.example.com/custom-mcp",
- OPENVIKING_API_KEY: "env-key",
- OPENVIKING_ACCOUNT: "env-account",
- OPENVIKING_USER: "env-user",
- OPENVIKING_PEER_ID: "env-peer",
+ await withFiles({ ovcli: { url: "https://ov.example.com", api_key: "cli-key", user: "zeus" } }, async ({ env }) => {
+ const creds = resolveConnection("codex", {
+ env: {
+ ...env,
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: "https://env.example.com",
+ OPENVIKING_MCP_URL: "https://env.example.com/custom-mcp",
+ OPENVIKING_API_KEY: "env-key",
+ OPENVIKING_ACCOUNT: "env-account",
+ OPENVIKING_USER: "env-user",
+ OPENVIKING_PEER_ID: "env-peer",
+ },
});
assert.equal(creds.credentialSource, "env");
assert.equal(creds.baseUrl, "https://env.example.com");
assert.equal(creds.mcpUrl, "https://env.example.com/custom-mcp");
- assert.equal(creds.apiKey, "env-key");
- assert.equal(creds.account, "env-account");
- assert.equal(creds.user, "env-user");
+ assert.deepEqual(identity(creds), { apiKey: "env-key", account: "env-account", user: "env-user" });
assert.equal(creds.peerId, "env-peer");
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
+ });
});
-test("ovcli source can be forced explicitly without inheriting env key", async () => {
- const { dir, path } = await tempJson("ov-creds-noauth-", {
- url: "http://127.0.0.1:1933",
+test("a forced env source reads no file, so an empty variable stays empty", async () => {
+ await withFiles({
+ ovcli: { url: "https://cli.example.com", api_key: "cli-key", account: "acct-cli", actor_peer_id: "cli-peer", plugin: { userId: "usr-plugin", authMode: "trusted" } },
+ ov: { server: { url: "https://ov.example.com", root_api_key: "root-key", auth_mode: "trusted" }, codex: { apiKey: "sk-codex" } },
+ }, async ({ env }) => {
+ const bare = resolveConnection("codex", { env: { ...env, OPENVIKING_CREDENTIAL_SOURCE: "env" }, rootKeyFallback: true });
+ assert.equal(bare.credentialSource, "env");
+ assert.equal(bare.baseUrl, "http://127.0.0.1:1933");
+ assert.deepEqual(identity(bare), { apiKey: "", account: "", user: "" });
+ assert.equal(bare.apiKeySource, "none");
+ assert.equal(bare.peerId, "");
+ assert.equal(bare.authMode, "api_key");
+
+ const named = resolveConnection("codex", {
+ env: { ...env, OPENVIKING_CREDENTIALS_SOURCE: "environment", OPENVIKING_URL: "https://env.example.com", OPENVIKING_USER: "usr-env" },
+ });
+ assert.equal(named.mcpUrl, "https://env.example.com/mcp");
+ assert.deepEqual(identity(named), { apiKey: "", account: "", user: "usr-env" });
+ assert.equal(named.authMode, "trusted");
});
- try {
- const creds = resolveOpenVikingCredentials({
- OPENVIKING_CLI_CONFIG_FILE: path,
- OPENVIKING_CREDENTIAL_SOURCE: "ovcli",
- OPENVIKING_API_KEY: "stale-key",
+});
+
+test("ovcli source can be forced explicitly without inheriting env key", async () => {
+ await withFiles({ ovcli: { url: "http://127.0.0.1:1933" } }, async ({ env }) => {
+ const creds = resolveConnection("codex", {
+ env: { ...env, OPENVIKING_CREDENTIAL_SOURCE: "ovcli", OPENVIKING_API_KEY: "stale-key" },
});
assert.equal(creds.credentialSource, "ovcli");
assert.equal(creds.baseUrl, "http://127.0.0.1:1933");
assert.equal(creds.apiKey, "");
assert.equal(creds.hasApiKey, false);
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
+ });
});
-test("credentialPath names the file that supplied the api_key", async () => {
- const dir = await mkdtemp(join(tmpdir(), "ov-creds-path-"));
- const cliPath = join(dir, "ovcli.conf");
- const ovPath = join(dir, "ov.conf");
- await writeFile(cliPath, JSON.stringify({ url: "http://127.0.0.1:1933", api_key: "cli-key" }));
- await writeFile(ovPath, JSON.stringify({ server: { root_api_key: "root-key" } }));
- const env = { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: ovPath };
- try {
- assert.equal(resolveOpenVikingCredentials(env).credentialPath, cliPath);
+test("only a variable that names the connection takes the chain off ovcli.conf", async () => {
+ await withFiles({ ovcli: { url: "https://ov.example.com", api_key: "cli-key" } }, async ({ env }) => {
+ const tuned = resolveConnection("codex", {
+ env: { ...env, OPENVIKING_AUTH_MODE: "api_key", OPENVIKING_TIMEOUT_MS: "5000" },
+ });
+ assert.equal(tuned.credentialSource, "ovcli");
+ assert.equal(tuned.apiKey, "cli-key");
- // env beats both files, so no file is named.
- assert.equal(
- resolveOpenVikingCredentials({ ...env, OPENVIKING_API_KEY: "env-key" }).credentialPath,
- "",
- );
+ for (const name of CREDENTIAL_ENV_VARS) {
+ const value = name.endsWith("URL") ? "https://env.example.com" : "from-env";
+ assert.equal(
+ resolveConnection("codex", { env: { ...env, [name]: value } }).credentialSource,
+ "env",
+ `${name} names part of the connection`,
+ );
+ }
+ });
+});
+
+test("the key's source names the layer and the file behind it", async () => {
+ await withFiles({
+ ovcli: { url: "http://127.0.0.1:1933", api_key: "cli-key" },
+ ov: { server: { root_api_key: "root-key" } },
+ }, async ({ env, cliPath, ovPath, write }) => {
+ const source = (c) => [c.apiKeySource, c.credentialPath];
+ assert.deepEqual(source(resolveConnection("codex", { env })), ["ovcli", cliPath]);
+
+ // env beats both files, so no file is named; a host beats env.
+ assert.deepEqual(source(resolveConnection("codex", { env: { ...env, OPENVIKING_API_KEY: "env-key" } })), ["env", ""]);
+ assert.deepEqual(source(resolveConnection("codex", { env, hostInput: { apiKey: "host-key" } })), ["host", ""]);
// A tuning-only ovcli.conf carries no credentials, so the chain lands on ov.conf.
- await writeFile(cliPath, JSON.stringify({ plugin: { recallCompress: "off" } }));
- const creds = resolveOpenVikingCredentials(env);
+ await write({ ovcli: { plugin: { recallCompress: "off" } } });
+ const creds = resolveConnection("codex", { env });
assert.equal(creds.apiKey, "root-key");
- assert.equal(creds.credentialPath, ovPath);
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
+ assert.deepEqual(source(creds), ["ov", ovPath]);
+
+ await write({ ovcli: { url: "http://127.0.0.1:1933" } });
+ assert.deepEqual(source(resolveConnection("codex", { env })), ["none", ""]);
+ });
});
test("each harness reads its own ov.conf section, not codex's", async () => {
- const dir = await mkdtemp(join(tmpdir(), "ov-creds-harness-"));
- const ovPath = join(dir, "ov.conf");
- await writeFile(ovPath, JSON.stringify({
- server: { root_api_key: "root-key" },
- codex: { apiKey: "sk-codex", accountId: "acct-codex", userId: "user-codex", peerId: "peer-codex" },
- opencode: { apiKey: "sk-opencode", accountId: "acct-opencode", userId: "user-opencode", peerId: "peer-opencode" },
- trae_cn: { apiKey: "sk-trae-cn" },
- }));
- const env = {
- OPENVIKING_CONFIG_FILE: ovPath,
- OPENVIKING_CLI_CONFIG_FILE: join(dir, "absent-ovcli.conf"),
- };
- try {
- const codex = resolveOpenVikingCredentials(env);
- assert.equal(codex.apiKey, "sk-codex");
- assert.equal(codex.account, "acct-codex");
- assert.equal(codex.user, "user-codex");
+ await withFiles({
+ ov: {
+ server: { root_api_key: "root-key" },
+ codex: { apiKey: "sk-codex", accountId: "acct-codex", userId: "user-codex", peerId: "peer-codex" },
+ opencode: { apiKey: "sk-opencode", accountId: "acct-opencode", userId: "user-opencode", peerId: "peer-opencode" },
+ trae_cn: { apiKey: "sk-trae-cn" },
+ },
+ }, async ({ env }) => {
+ const codex = resolveConnection("codex", { env });
+ assert.deepEqual(identity(codex), { apiKey: "sk-codex", account: "acct-codex", user: "user-codex" });
assert.equal(codex.peerId, "peer-codex");
- const opencode = resolveOpenVikingCredentials(env, "opencode");
- assert.equal(opencode.apiKey, "sk-opencode");
- assert.equal(opencode.account, "acct-opencode");
- assert.equal(opencode.user, "user-opencode");
+ const opencode = resolveConnection("opencode", { env });
+ assert.deepEqual(identity(opencode), { apiKey: "sk-opencode", account: "acct-opencode", user: "user-opencode" });
assert.equal(opencode.peerId, "peer-opencode");
// Either spelling of a harness name reaches the snake_case section.
- assert.equal(resolveOpenVikingCredentials(env, "trae-cn").apiKey, "sk-trae-cn");
+ assert.equal(resolveConnection("trae-cn", { env }).apiKey, "sk-trae-cn");
// A harness with no section of its own inherits nothing from codex's; the
// chain carries on to server.root_api_key as it always did.
- const cursor = resolveOpenVikingCredentials(env, "cursor");
- assert.equal(cursor.apiKey, "root-key");
- assert.equal(cursor.account, "");
- assert.equal(cursor.user, "");
+ const cursor = resolveConnection("cursor", { env });
+ assert.deepEqual(identity(cursor), { apiKey: "root-key", account: "", user: "" });
assert.equal(cursor.peerId, "");
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
+ });
});
-test("ovcli.conf still outranks the harness section, which outranks the root key", async () => {
- const dir = await mkdtemp(join(tmpdir(), "ov-creds-order-"));
- const ovPath = join(dir, "ov.conf");
- const cliPath = join(dir, "ovcli.conf");
- await writeFile(ovPath, JSON.stringify({
- server: { root_api_key: "root-key" },
- opencode: { apiKey: "sk-opencode", peerId: "peer-opencode" },
- }));
- await writeFile(cliPath, JSON.stringify({ url: "http://127.0.0.1:1933", actor_peer_id: "cli-peer" }));
- const env = { OPENVIKING_CONFIG_FILE: ovPath, OPENVIKING_CLI_CONFIG_FILE: cliPath };
- try {
- // ovcli.conf carries credential fields, so this is the pinned-file mode:
- // ov.conf is not consulted at all and the harness section stays out.
- const pinned = resolveOpenVikingCredentials(env, "opencode");
+test("ovcli.conf's plugin keys rank under its own fields and over ov.conf", async () => {
+ await withFiles({
+ ovcli: {
+ plugin: {
+ apiKey: "sk-plugin",
+ accountId: "acct-plugin",
+ userId: "usr-plugin",
+ claude_code: { apiKey: "sk-snake", accountId: "acct-snake" },
+ "claude-code": { apiKey: "sk-hyphen" },
+ },
+ },
+ ov: { server: { root_api_key: "root-key" }, claude_code: { apiKey: "sk-ov", accountId: "acct-ov", userId: "usr-ov" } },
+ }, async ({ env, write }) => {
+ // Shared keys, then plugin.claude_code over them, then the hyphenated
+ // spelling over that — the merge every knob in that section follows.
+ assert.deepEqual(identity(resolveConnection("claude-code", { env })), {
+ apiKey: "sk-hyphen",
+ account: "acct-snake",
+ user: "usr-plugin",
+ });
+
+ // A number is a value, as the knob schema coerces it.
+ await write({ ovcli: { plugin: { accountId: 12345 } } });
+ assert.equal(resolveConnection("codex", { env }).account, "12345");
+
+ // An empty scoped key blanks the shared one and the chain carries on.
+ await write({ ovcli: { plugin: { apiKey: "sk-plugin", claude_code: { apiKey: "" } } } });
+ assert.equal(resolveConnection("claude-code", { env }).apiKey, "sk-ov");
+
+ await write({ ovcli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { apiKey: "sk-plugin", userId: "usr-plugin" } } });
+ const pinned = resolveConnection("claude-code", { env });
assert.equal(pinned.credentialSource, "ovcli");
- assert.equal(pinned.apiKey, "");
+ assert.equal(pinned.apiKey, "sk-cli");
+ assert.equal(pinned.user, "usr-plugin");
+ });
+});
+
+test("pinned, the key falls back to ov.conf's harness section but the identity does not", async () => {
+ await withFiles({
+ ovcli: { url: "http://127.0.0.1:1933", actor_peer_id: "cli-peer" },
+ ov: {
+ server: { root_api_key: "root-key" },
+ opencode: { apiKey: "sk-opencode", accountId: "acct-opencode", userId: "usr-opencode", peerId: "peer-opencode" },
+ },
+ }, async ({ env, ovPath, write }) => {
+ const pinned = resolveConnection("opencode", { env });
+ assert.equal(pinned.credentialSource, "ovcli");
+ assert.deepEqual(identity(pinned), { apiKey: "sk-opencode", account: "", user: "" });
assert.equal(pinned.peerId, "cli-peer");
+ assert.equal(pinned.credentialPath, ovPath);
- // With ovcli.conf holding tuning only, the harness section supplies the key
+ // With ovcli.conf holding tuning only, the whole harness section applies
// and still sits ahead of server.root_api_key.
- await writeFile(cliPath, JSON.stringify({ plugin: { recallCompress: "off" } }));
- const layered = resolveOpenVikingCredentials(env, "opencode");
- assert.equal(layered.apiKey, "sk-opencode");
- assert.equal(layered.credentialPath, ovPath);
- } finally {
- await rm(dir, { recursive: true, force: true });
+ await write({ ovcli: { plugin: { recallCompress: "off" } } });
+ const layered = resolveConnection("opencode", { env });
+ assert.deepEqual(identity(layered), { apiKey: "sk-opencode", account: "acct-opencode", user: "usr-opencode" });
+ assert.equal(layered.peerId, "peer-opencode");
+ });
+});
+
+test("the root key ends every unpinned chain, and a pinned one only on request", async () => {
+ await withFiles({ ov: { server: { root_api_key: "root-key" } } }, async ({ env, write }) => {
+ const key = (rootKeyFallback) => resolveConnection("codex", { env, rootKeyFallback }).apiKey;
+ assert.equal(key(false), "root-key");
+ assert.equal(key(true), "root-key");
+
+ await write({ ovcli: { url: "http://127.0.0.1:1933" } });
+ assert.equal(key(false), "");
+ assert.equal(key(true), "root-key");
+ });
+});
+
+test("the auth mode walks host, env, plugin, harness section, server, then the identity", async () => {
+ const ovcli = {
+ api_key: "sk-cli",
+ account: "acct",
+ plugin: { auth_mode: "trusted", codex: { authMode: "api_key" } },
+ };
+ const ov = { server: { auth_mode: "trusted" }, codex: { authMode: "trusted" } };
+ await withFiles({ ovcli, ov }, async ({ env, write }) => {
+ const mode = (options = {}) => {
+ const c = resolveConnection("codex", { env, ...options });
+ assert.equal(c.sendIdentityHeaders, c.authMode === "trusted");
+ return c.authMode;
+ };
+ assert.equal(mode(), "api_key", "plugin.codex outranks the shared plugin key");
+ assert.equal(mode({ env: { ...env, OPENVIKING_AUTH_MODE: "TRUSTED" } }), "trusted");
+ assert.equal(
+ mode({ env: { ...env, OPENVIKING_AUTH_MODE: "trusted" }, hostInput: { authMode: "api_key" } }),
+ "api_key",
+ "a host's own answer outranks the environment",
+ );
+
+ await write({ ovcli: { ...ovcli, plugin: { auth_mode: "api_key" } } });
+ assert.equal(mode(), "api_key", "the snake_case spelling counts");
+
+ await write({ ovcli: { ...ovcli, plugin: {} }, ov: { ...ov, codex: { auth_mode: "api_key" } } });
+ assert.equal(mode(), "api_key", "ov.conf's harness section ranks over server.auth_mode");
+
+ await write({ ov: { server: { auth_mode: "api_key" } } });
+ assert.equal(mode(), "api_key");
+
+ await write({ ov: { server: { auth_mode: "bogus" } } });
+ assert.equal(mode(), "trusted", "an identity means the deployment expects one");
+
+ await write({ ovcli: { api_key: "sk-cli" } });
+ assert.equal(mode(), "api_key");
+ assert.equal(mode({ hostInput: { user: "host-user" } }), "trusted", "a host's identity counts too");
+ });
+});
+
+test("a host's endpoint outranks every URL, including an explicit MCP URL", async () => {
+ await withFiles({ ovcli: { url: "https://cli.example.com/" } }, async ({ env }) => {
+ assert.equal(resolveConnection("dsh", { env }).mcpUrl, "https://cli.example.com/mcp");
+
+ const withMcpUrl = { ...env, OPENVIKING_MCP_URL: "https://env.example.com/custom" };
+ assert.equal(resolveConnection("dsh", { env: withMcpUrl }).mcpUrl, "https://env.example.com/custom");
+
+ const hosted = resolveConnection("dsh", { env: withMcpUrl, hostInput: { baseUrl: "https://host.example.com/" } });
+ assert.equal(hosted.baseUrl, "https://host.example.com");
+ assert.equal(hosted.mcpUrl, "https://host.example.com/mcp");
+ });
+});
+
+// credentials.mjs reads these knobs out of the plugin section itself, so the
+// portable bundle does not have to ship the schema; every spelling the schema
+// accepts has to land.
+test("every spelling of a connection knob in the schema reaches the chain", async () => {
+ const values = { apiKey: ["apiKey", "sk-plugin"], accountId: ["account", "acct-plugin"], userId: ["user", "usr-plugin"], authMode: ["authMode", "trusted"] };
+ for (const [name, [field, value]] of Object.entries(values)) {
+ const knob = KNOB_BY_NAME.get(name);
+ assert.equal(knob.capability, "connection");
+ if (knob.env) assert.ok(CONNECTION_ENV_VARS.includes(knob.env), `${knob.env} is a connection variable`);
+ for (const spelling of [name, ...(knob.aliases || [])]) {
+ await withFiles({ ovcli: { plugin: { codex: { [spelling]: value } } }, ov: { server: { auth_mode: "api_key" } } }, async ({ env }) => {
+ assert.equal(resolveConnection("codex", { env })[field], value, `plugin.codex.${spelling}`);
+ });
+ }
}
});
diff --git a/examples/memory-plugin-shared/doctor-core.test.mjs b/examples/memory-plugin-shared/doctor-core.test.mjs
index 8f8cd4311..20f135fdc 100644
--- a/examples/memory-plugin-shared/doctor-core.test.mjs
+++ b/examples/memory-plugin-shared/doctor-core.test.mjs
@@ -285,6 +285,8 @@ const CREDENTIAL_ENV = [
"OPENVIKING_BEARER_TOKEN",
"OPENVIKING_ACCOUNT",
"OPENVIKING_USER",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
];
function withEnv(vars, fn) {
@@ -390,4 +392,13 @@ test("credentialSources ranks the identity the way the credential chain does", (
assert.equal(rows({ credentialSource: "auto" }, cliConf({})).account, `${OV_PATH} codex.accountId`);
assert.equal(rows({ credentialSource: "auto" }, cliConf({})).url, OV_PATH);
});
+
+ withEnv({ OPENVIKING_CREDENTIAL_SOURCE: "env", OPENVIKING_ACCOUNT: "acct-env" }, () => {
+ // Forced to the environment, no file answers, whatever it holds.
+ const envOnly = rows({ credentialSource: "env" }, full);
+ assert.equal(envOnly.url, "default (http://127.0.0.1:1933)");
+ assert.equal(envOnly.account, "env");
+ assert.equal(envOnly.user, "(unset)");
+ assert.equal(envOnly.apiKey, "(none — env mode reads no file)");
+ });
});
diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
index 77a7a1400..e7a415c35 100644
--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs
+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
@@ -363,7 +363,7 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", (
[join(home, ".openviking", "agent-integrations", "cursor", "scripts", "ov-memory-doctor.mjs"), "cursor", "--offline", "--no-color"],
{ env: { ...process.env, HOME: home }, encoding: "utf8" },
);
- assert.match(doctor.stdout, /version 0\.3\.1, client cursor/);
+ assert.match(doctor.stdout, /version 0\.3\.2, client cursor/);
// A hooks.json entry that names a script the install did not put on disk
// fails only when the host first runs it, so the rendered commands are
// checked against the tree they were rendered for.
diff --git a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
index dff433cc8..e42d16321 100644
--- a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
+++ b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
@@ -43,11 +43,12 @@ export function stableHash(...values) {
* file may not carry connection or credential keys, so the base URL and API key
* cannot move under a logger or fetch helper already built from the first load.
*/
-export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
+export function loadAgentHookConfig(clientId, cwd = process.cwd(), { env = process.env } = {}) {
return {
...buildPluginConfig(clientId, {
cwd,
- version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ env,
+ version: env.OPENVIKING_INTEGRATION_VERSION,
logFile: `${clientId}-hooks.log`,
}),
clientId,
diff --git a/examples/memory-plugin-shared/lib/credentials.d.mts b/examples/memory-plugin-shared/lib/credentials.d.mts
index e45ac93c4..a850161da 100644
--- a/examples/memory-plugin-shared/lib/credentials.d.mts
+++ b/examples/memory-plugin-shared/lib/credentials.d.mts
@@ -2,34 +2,54 @@ export function buildUserAgent(harness: string, version?: string): string;
export function readManifestVersion(manifest: string | URL): string;
-export function resolveAuthMode(input?: {
- settings?: Record<string, unknown>;
- ovFile?: Record<string, unknown>;
- account?: string;
- user?: string;
-}): { authMode: string; sendIdentityHeaders: boolean };
+export const CREDENTIAL_ENV_VARS: readonly string[];
-export function resolveOpenVikingCredentials(
- env?: Record<string, string | undefined>,
- harness?: string,
- plugin?: { apiKey?: string },
-): {
- credentialSource: string;
- apiKeySource: string;
- credentialPath: string;
+export const CONNECTION_ENV_VARS: readonly string[];
+
+export interface CredentialFiles {
+ cliFile: Record<string, unknown>;
cliPath: string;
cliPathCandidate: string;
- ovPath: string;
- cliFile: Record<string, unknown>;
ovFile: Record<string, unknown>;
+ ovPath: string;
+}
+
+export function loadCredentialFiles(env?: Record<string, string | undefined>): CredentialFiles;
+
+export interface ConnectionHostInput {
+ apiKey?: string;
+ account?: string;
+ user?: string;
+ baseUrl?: string;
+ authMode?: string;
+ peerId?: string;
+}
+
+export interface Connection extends CredentialFiles {
+ harness: string;
+ credentialSource: string;
baseUrl: string;
mcpUrl: string;
apiKey: string;
account: string;
user: string;
peerId: string;
+ authMode: string;
+ sendIdentityHeaders: boolean;
hasApiKey: boolean;
-};
+ apiKeySource: string;
+ credentialPath: string;
+}
+
+export function resolveConnection(
+ harness: string,
+ options?: {
+ env?: Record<string, string | undefined>;
+ files?: CredentialFiles | null;
+ hostInput?: ConnectionHostInput;
+ rootKeyFallback?: boolean;
+ },
+): Connection;
export function buildProxyConnection(
harness: string,
@@ -53,7 +73,8 @@ export function buildProxyConnection(
apiKeySource: string;
credentialPath: string;
hasApiKey: boolean;
- watchedPaths: string[];
+ cliPath: string;
+ ovPath: string;
timeoutMs: number;
debug: boolean;
debugLogPath: string;
diff --git a/examples/memory-plugin-shared/lib/credentials.mjs b/examples/memory-plugin-shared/lib/credentials.mjs
index 593bf08a4..d47a448ff 100644
--- a/examples/memory-plugin-shared/lib/credentials.mjs
+++ b/examples/memory-plugin-shared/lib/credentials.mjs
@@ -1,11 +1,9 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { fileURLToPath } from "node:url";
const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
-const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
const DEFAULT_TIMEOUT_MS = 15000;
const MIN_TIMEOUT_MS = 1000;
@@ -110,17 +108,74 @@ export function loadCredentialFiles(env = process.env) {
}
/**
- * The calling harness's own section of ov.conf.
- *
+ * The environment variables that name part of the connection. Any one of them
+ * set is what takes the chain off ovcli.conf in `auto` mode, so a variable
+ * that only tunes how the chain runs must not be on this list: an
+ * `OPENVIKING_AUTH_MODE` exported on its own would otherwise unpin the file.
+ */
+export const CREDENTIAL_ENV_VARS = [
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_MCP_URL",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+ "OPENVIKING_PEER_ID",
+];
+
+/** Every environment variable `resolveConnection` reads. */
+export const CONNECTION_ENV_VARS = [
+ ...CREDENTIAL_ENV_VARS,
+ "OPENVIKING_AUTH_MODE",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
+ "OPENVIKING_CLI_CONFIG_FILE",
+ "OPENVIKING_CONFIG_FILE",
+];
+
+function isSection(value) {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/**
* ov.conf spells its sections snake_case while a host may call itself
* `claude-code` or `trae-cn`, so both spellings land on the same block. The
* normalization stays inline rather than importing `config-schema.mjs`, which
* the portable agent-plugins bundle would then have to ship as well.
*/
+function sectionKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** The calling harness's own section of ov.conf. */
function harnessSection(ovFile, harness) {
- const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
- const section = key ? ovFile[key] : null;
- return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+ const section = ovFile[sectionKey(harness)];
+ return isSection(section) ? section : {};
+}
+
+/**
+ * ovcli.conf's `plugin` section as this harness sees it: the shared scalars,
+ * then `plugin.<harness>` over them in both spellings, the hyphenated one last.
+ * `loadPluginSettings` merges the same way for every other knob, and the two
+ * must agree or a key would win in the hooks and lose here.
+ */
+function pluginSection(cliFile, harness) {
+ const plugin = isSection(cliFile.plugin) ? cliFile.plugin : {};
+ const merged = {};
+ for (const [key, value] of Object.entries(plugin)) {
+ if (!isSection(value)) merged[key] = value;
+ }
+ const key = sectionKey(harness);
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ if (candidate && isSection(plugin[candidate])) Object.assign(merged, plugin[candidate]);
+ }
+ return merged;
+}
+
+/** A knob-file scalar as the schema coerces a string knob: `12345` is "12345". */
+function scalar(value) {
+ return value === undefined || value === null ? "" : String(value).trim();
}
const AUTH_MODES = ["trusted", "api_key"];
@@ -130,22 +185,8 @@ function normalizeAuthMode(value) {
return AUTH_MODES.includes(mode) ? mode : "";
}
-/**
- * Which auth mode the server is in, and with it whether the identity headers
- * may go on the wire.
- *
- * An `api_key` server reads the account and the user out of the key and ignores
- * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
- * every proxy on the path who the operator is and buys nothing. A named mode
- * wins; ov.conf's server block answers next; failing both, a credential layer
- * that supplied an identity at all means the deployment expects one.
- */
-export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
- const server = ovFile.server || {};
- const authMode = normalizeAuthMode(settings.authMode)
- || normalizeAuthMode(server.auth_mode)
- || ((account || user) ? "trusted" : "api_key");
- return { authMode, sendIdentityHeaders: authMode === "trusted" };
+function authModeIn(section) {
+ return normalizeAuthMode(section.authMode) || normalizeAuthMode(section.auth_mode);
}
function sourceMode(env) {
@@ -157,135 +198,130 @@ function sourceMode(env) {
}
function hasEnvCredentialFields(env) {
- return Boolean(
- str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
- str(env.OPENVIKING_MCP_URL, "") ||
- str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(env.OPENVIKING_USER, "") ||
- str(env.OPENVIKING_PEER_ID, ""),
- );
+ return CREDENTIAL_ENV_VARS.some((name) => str(env[name], ""));
}
-function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
- const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
- const cliUrl = str(cliFile.url, "");
-
- if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
- if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
- if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
-
- const server = ovFile.server || {};
- const ovUrl = str(server.url, "");
- if (ovUrl) return ovUrl.replace(/\/+$/, "");
+function trimSlash(value) {
+ return value.replace(/\/+$/, "");
+}
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
- return `http://${host}:${port}`;
+/** The first layer that holds a value, with the source label and file it names. */
+function firstLayer(layers) {
+ for (const [value, source, path = ""] of layers) {
+ if (value) return { value, source, path };
+ }
+ return { value: "", source: "none", path: "" };
}
/**
- * `harness` names whose ov.conf section supplies the legacy fallback. It sits
- * where it always did — after ovcli.conf, before `server.root_api_key` — but a
- * harness now reads its own section instead of every one of them reading
- * codex's. The default keeps codex, the only caller that never passes one.
+ * The one connection a harness has: which server, which key, whose identity,
+ * and whether that identity goes on the wire. Hooks reach it through
+ * `buildPluginConfig`, every MCP proxy through the same loader or through
+ * `buildProxyConnection`, so the two sides of one harness cannot disagree.
+ *
+ * Only three kinds of input count: what an embedding host named (`hostInput`),
+ * the environment, and the two files under `~/.openviking`. The working
+ * directory never does — an MCP proxy starts wherever its host launches it.
*
- * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
- * section named, which this module cannot read for itself: resolving that
- * section needs the knob schema, and the portable bundles would then have to
- * ship it. All three rank where the file they come from ranks — under
- * ovcli.conf's own fields, over ov.conf.
+ * ovcli.conf pins the chain when it names a url, key, identity or peer and the
+ * environment names none of those; pinned, the environment's credentials no
+ * longer apply. `OPENVIKING_CREDENTIAL_SOURCE` forces either side, and forced
+ * to `env` no file is read at all — which is what lets a parent process hand a
+ * resolved connection, including an empty key, to a child verbatim. Every chain
+ * runs host → env (unpinned) → ovcli.conf → its `plugin.<harness>` and
+ * `plugin` keys → ov.conf's harness section; the key then ends at
+ * `server.root_api_key`, which a pinned chain reaches only with
+ * `rootKeyFallback`, and the identity skips ov.conf's harness section when
+ * pinned. The auth mode reads the environment in either mode, then the
+ * `plugin` keys, the harness section and `server.auth_mode`; failing all of
+ * them, an identity from any layer means the deployment expects one.
*/
-export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
- const files = loadCredentialFiles(env);
+export function resolveConnection(harness, {
+ env = process.env,
+ files = null,
+ hostInput = {},
+ rootKeyFallback = false,
+} = {}) {
+ const name = str(harness, "");
+ const loaded = files || loadCredentialFiles(env);
+ const { cliFile, ovFile, cliPath, ovPath } = loaded;
+ const host = hostInput || {};
const mode = sourceMode(env);
const envHasCredentials = hasEnvCredentialFields(env);
- const useCli = mode === "cli" ||
- (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
- const cx = harnessSection(files.ovFile, harness);
- const server = files.ovFile.server || {};
-
- const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
-
- const pluginApiKey = str(plugin?.apiKey, "");
- const apiKey = useCli
- ? (str(files.cliFile.api_key, "") || pluginApiKey)
- : (
- str(env.OPENVIKING_BEARER_TOKEN, "") ||
- str(env.OPENVIKING_API_KEY, "") ||
- str(files.cliFile.api_key, "") ||
- pluginApiKey ||
- str(cx.apiKey, "") ||
- str(server.root_api_key, "")
- );
-
- const pluginAccount = str(plugin?.accountId, "");
- const account = useCli
- ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
- : (
- str(env.OPENVIKING_ACCOUNT, "") ||
- str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
- pluginAccount ||
- str(cx.accountId, "")
- );
-
- const pluginUser = str(plugin?.userId, "");
- const user = useCli
- ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
- : (
- str(env.OPENVIKING_USER, "") ||
- str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
- pluginUser ||
- str(cx.userId, "")
- );
-
- const peerId = useCli
- ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
- : (
- str(env.OPENVIKING_PEER_ID, "") ||
- str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
- str(cx.peerId, str(cx.peer_id, ""))
- );
-
- const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
- const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
-
- // Which layer actually supplied the api_key, following the same chain, and
- // the file behind it — empty when the key came from the environment or was
- // never found. `apiKeySource` is what a doctor and a 401 hint report; the
- // credential *source* beside it is the mode the chain ran in, not a file.
- let apiKeySource = "none";
- let credentialPath = "";
- if (apiKey) {
- if (useCli) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
- apiKeySource = "env";
- } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
- apiKeySource = "ovcli";
- credentialPath = files.cliPath;
- } else {
- apiKeySource = "ov";
- credentialPath = files.ovPath;
- }
- }
+ const pinned = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && Boolean(cliPath) && hasCredentialFields(cliFile));
+ const unpinned = (layer) => (pinned ? [] : [layer]);
+ const fromFiles = mode !== "env";
+ const filed = (...layers) => (fromFiles ? layers : []);
+ const plugin = pluginSection(cliFile, name);
+ const section = harnessSection(ovFile, name);
+ const server = isSection(ovFile.server) ? ovFile.server : {};
+
+ const key = firstLayer([
+ [str(host.apiKey, ""), "host"],
+ ...unpinned([str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")), "env"]),
+ ...filed(
+ [str(cliFile.api_key, ""), "ovcli", cliPath],
+ [scalar(plugin.apiKey), "ovcli", cliPath],
+ [scalar(section.apiKey), "ov", ovPath],
+ ),
+ ...((pinned && !rootKeyFallback) ? [] : filed([str(server.root_api_key, ""), "ov", ovPath])),
+ ]);
+
+ const identity = (hostValue, envName, cliValue, knob) => firstLayer([
+ [str(hostValue, ""), "host"],
+ ...unpinned([str(env[envName], ""), "env"]),
+ ...filed([cliValue, "ovcli", cliPath], [scalar(plugin[knob]), "ovcli", cliPath]),
+ ...(pinned ? [] : filed([str(section[knob], ""), "ov", ovPath])),
+ ]).value;
+ const account = identity(host.account, "OPENVIKING_ACCOUNT", str(cliFile.account, str(cliFile.account_id, "")), "accountId");
+ const user = identity(host.user, "OPENVIKING_USER", str(cliFile.user, str(cliFile.user_id, "")), "userId");
+
+ const peerId = firstLayer([
+ ...unpinned([str(env.OPENVIKING_PEER_ID, ""), "env"]),
+ ...filed([str(cliFile.actor_peer_id, str(cliFile.peer_id, "")), "ovcli"]),
+ ...(pinned ? [] : filed([str(section.peerId, str(section.peer_id, "")), "ov"])),
+ ]).value;
+
+ const authMode = normalizeAuthMode(host.authMode)
+ || normalizeAuthMode(env.OPENVIKING_AUTH_MODE)
+ || (fromFiles && (authModeIn(plugin) || authModeIn(section) || normalizeAuthMode(server.auth_mode)))
+ || ((account || user) ? "trusted" : "api_key");
+
+ const hostBaseUrl = trimSlash(str(host.baseUrl, ""));
+ const envUrl = pinned ? "" : str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const fileUrl = fromFiles ? (str(cliFile.url, "") || str(server.url, "")) : "";
+ const baseUrl = hostBaseUrl || trimSlash(envUrl || fileUrl) || serverAddress(fromFiles ? server : {});
+ const envMcpUrl = pinned ? "" : str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (!hostBaseUrl && envMcpUrl) ? envMcpUrl : `${baseUrl}/mcp`;
return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- apiKeySource,
- credentialPath,
+ ...loaded,
+ harness: name,
+ credentialSource: pinned ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
baseUrl,
mcpUrl,
- apiKey,
+ apiKey: key.value,
account,
user,
peerId,
- hasApiKey: Boolean(apiKey),
+ authMode,
+ sendIdentityHeaders: authMode === "trusted",
+ hasApiKey: Boolean(key.value),
+ // Which layer supplied the key and the file behind it, empty when the key
+ // came from the host or the environment. A doctor and a 401 hint report it;
+ // `credentialSource` is the mode the chain ran in, not a file.
+ apiKeySource: key.source,
+ credentialPath: key.path,
};
}
+function serverAddress(server) {
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
function envFlag(env, name) {
const raw = str(env[name], "").toLowerCase();
return raw === "1" || raw === "true" || raw === "yes";
@@ -303,9 +339,8 @@ function clampTimeout(value) {
* `buildPluginConfig` answers the same question one layer up, but reaching it
* means vendoring the knob schema and the workspace layers — a closure the
* portable agent-plugins bundle would carry in git to send one HTTP header.
- * This is the connection half alone: the credential chain, the auth mode that
- * decides whether the identity headers may go on the wire, the User-Agent, the
- * request timeout, and the debug log.
+ * This is the same connection plus what a proxy adds to it: the User-Agent,
+ * the request timeout, and the debug log.
*
* The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
* chain to itself. A portable package has no installer to migrate anyone, so
@@ -313,62 +348,27 @@ function clampTimeout(value) {
*/
export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
const name = str(harness);
- const credentials = resolveOpenVikingCredentials(env, name);
-
- let { apiKey, apiKeySource, credentialPath } = credentials;
- if (!apiKey) {
- apiKey = str(credentials.ovFile?.server?.root_api_key);
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
-
+ const connection = resolveConnection(name, { env, rootKeyFallback: true });
return {
harness: name,
userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
- baseUrl: credentials.baseUrl,
- mcpUrl: credentials.mcpUrl,
- apiKey,
- account: credentials.account,
- user: credentials.user,
- peerId: credentials.peerId,
- ...resolveAuthMode({
- settings: { authMode: env.OPENVIKING_AUTH_MODE },
- ovFile: credentials.ovFile,
- account: credentials.account,
- user: credentials.user,
- }),
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ baseUrl: connection.baseUrl,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
+ account: connection.account,
+ user: connection.user,
+ peerId: connection.peerId,
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
debug: envFlag(env, "OPENVIKING_DEBUG"),
debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
|| join(homedir(), ".openviking", "logs", `${name}.log`),
};
}
-
-function main() {
- const cmd = process.argv[2] || "";
- if (cmd === "mcp-url") {
- process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
- return;
- }
- if (cmd === "has-api-key") {
- process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
- return;
- }
- if (cmd === "has-peer-id") {
- process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
- return;
- }
- process.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
- process.exitCode = 2;
-}
-
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- main();
-}
diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjs
index 6d596af77..4c21b9f9c 100644
--- a/examples/memory-plugin-shared/lib/doctor-core.mjs
+++ b/examples/memory-plugin-shared/lib/doctor-core.mjs
@@ -1142,7 +1142,7 @@ export function inspectConfigFiles(report, { harness = "", launcherHint = "this
* block from `server.root_api_key`.
*
* The identity has no such answer to read, so account and user follow the chain
- * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * in `resolveConnection` step for step: pinned to ovcli.conf it ends
* at that file's `plugin` section, and otherwise the environment wins and
* ov.conf's harness block is last.
*/
@@ -1156,14 +1156,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
const scoped = (section && plugin[section]) || {};
const block = (section && ov[section]) || {};
const server = ov.server || {};
- // Pinned to ovcli.conf, the chain never looks at the environment.
+ // Pinned to ovcli.conf, the chain never looks at the environment; forced to
+ // the environment, it never looks at a file.
const pinned = cfg.credentialSource === "ovcli";
+ const envOnly = /^(env|environment)$/i.test(String(env.OPENVIKING_CREDENTIAL_SOURCE || env.OPENVIKING_CREDENTIALS_SOURCE || "").trim());
const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
const url = (!pinned && envUrl) ? "env"
- : cli.url ? cliShort
- : server.url ? ovShort
- : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+ : envOnly ? "default (http://127.0.0.1:1933)"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
let apiKey;
if (cfg.apiKeySource === "env") {
@@ -1178,15 +1181,17 @@ export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(c
} else if (cfg.apiKeySource === "host") {
apiKey = "the host application";
} else {
- apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)"
+ : envOnly ? "(none — env mode reads no file)" : "(none)";
}
const identity = (envName, cliValue, name) => (
(!pinned && env[envName]) ? "env"
- : cliValue ? cliShort
- : scoped[name] ? `${cliShort} plugin.${section}.${name}`
- : plugin[name] ? `${cliShort} plugin.${name}`
- : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ : envOnly ? "(unset)"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
);
return {
url,
diff --git a/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs b/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
index ffe695428..74573ff78 100644
--- a/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
+++ b/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
@@ -11,9 +11,56 @@
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
+import { CONNECTION_ENV_VARS, CREDENTIAL_ENV_VARS } from "./credentials.mjs";
+
export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
const MIN_PROXY_TIMEOUT_MS = 1000;
+/**
+ * Every variable that changes what an MCP proxy sends. Hooks inherit their
+ * host's whole environment; a host that hands its MCP servers an allowlist
+ * instead (Codex's `env_vars`) has to name each of these, or the proxy
+ * resolves a different connection from the hooks beside it.
+ */
+export const MCP_PROXY_ENV_VARS = [
+ ...CONNECTION_ENV_VARS,
+ "OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
+ "OPENVIKING_RECALL_PEER_SCOPE",
+ "OPENVIKING_TIMEOUT_MS",
+ "OPENVIKING_DEBUG",
+ "OPENVIKING_DEBUG_LOG",
+ "OPENVIKING_EXTRA_HEADERS",
+];
+
+/**
+ * A resolved connection as the environment of a child proxy process.
+ *
+ * The other way across the process boundary, for a host that cannot hand its
+ * MCP servers the inputs (DSH drops credential-shaped names from what a child
+ * inherits): the parent resolves once and the child reads the answer back. The
+ * forced `env` source makes that exact — the child reads no file, so a key the
+ * parent left empty stays empty instead of falling through to
+ * `server.root_api_key`. Every credential variable is written, the empty ones
+ * too, because the rest of the parent's environment still reaches the child:
+ * an `OPENVIKING_ACCOUNT` the parent's pinned chain ignored must not fill the
+ * gap there.
+ */
+export function forwardConnectionEnv(connection) {
+ const env = Object.fromEntries(CREDENTIAL_ENV_VARS.map((name) => [name, ""]));
+ return {
+ ...env,
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_URL: connection.baseUrl,
+ OPENVIKING_MCP_URL: connection.mcpUrl,
+ OPENVIKING_API_KEY: connection.apiKey || "",
+ OPENVIKING_ACCOUNT: connection.account || "",
+ OPENVIKING_USER: connection.user || "",
+ OPENVIKING_PEER_ID: connection.peerId || "",
+ OPENVIKING_AUTH_MODE: connection.authMode,
+ };
+}
+
export function trimSlash(value) {
return String(value || "").replace(/\/+$/, "");
}
@@ -54,7 +101,7 @@ export function defaultCredentialPaths(env = process.env) {
* start: the proxy is what carries every memory tool, and taking those away
* because a scope preference cannot be honoured costs the user far more than
* the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
+ * (dsh, `mcp-env.mjs`) can satisfy this without the user setting it.
*/
export function resolveMcpActorPeerId({
peerId = "",
@@ -191,3 +238,38 @@ export function buildMcpProxyConfig({
extraHeaders: resolvedExtraHeaders,
};
}
+
+/**
+ * The proxy config for a resolved harness config, mapped in one place.
+ *
+ * Every proxy used to copy fields out of its loader by hand, and the copies
+ * drifted: two dropped `mcpUrl`, so `OPENVIKING_MCP_URL` reached the hooks and
+ * not the tools. `cfg` is what `buildPluginConfig` or `buildProxyConnection`
+ * returned. `peerId` replaces the actor peer only for a harness whose parent
+ * process resolved it (dsh); everywhere else a long-lived proxy may send one
+ * only when actor-scoped recall asks for it.
+ */
+export function toMcpProxyConfig(cfg, {
+ env = process.env,
+ peerId = undefined,
+ debug = cfg.debug,
+ debugLogPath = cfg.debugLogPath,
+} = {}) {
+ return buildMcpProxyConfig({
+ baseUrl: cfg.baseUrl,
+ mcpUrl: cfg.mcpUrl,
+ apiKey: cfg.apiKey,
+ account: cfg.account,
+ user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
+ peerId: peerId === undefined ? resolveMcpActorPeerId(cfg) : peerId,
+ userAgent: cfg.userAgent,
+ timeoutMs: cfg.timeoutMs,
+ debug,
+ debugLogPath,
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.credentialPath || "",
+ watchedPaths: [cfg.cliPath, cfg.ovPath],
+ env,
+ });
+}
diff --git a/examples/memory-plugin-shared/lib/plugin-config.d.mts b/examples/memory-plugin-shared/lib/plugin-config.d.mts
index 0b3346ec6..f97e280b6 100644
--- a/examples/memory-plugin-shared/lib/plugin-config.d.mts
+++ b/examples/memory-plugin-shared/lib/plugin-config.d.mts
@@ -38,6 +38,7 @@ export function buildPluginConfig(
user?: string;
apiKey?: string;
baseUrl?: string;
+ authMode?: string;
};
logFile?: string;
rootKeyFallback?: boolean;
diff --git a/examples/memory-plugin-shared/lib/plugin-config.mjs b/examples/memory-plugin-shared/lib/plugin-config.mjs
index 99cbbea89..030fd52a3 100644
--- a/examples/memory-plugin-shared/lib/plugin-config.mjs
+++ b/examples/memory-plugin-shared/lib/plugin-config.mjs
@@ -33,8 +33,7 @@ import {
buildUserAgent,
loadCredentialFiles,
readManifestVersion,
- resolveAuthMode,
- resolveOpenVikingCredentials,
+ resolveConnection,
} from "./credentials.mjs";
import {
announcedOverrides,
@@ -164,15 +163,6 @@ function ovConfSection(ovFile, key) {
return section && typeof section === "object" && !Array.isArray(section) ? section : {};
}
-/**
- * A connection value ovcli.conf's `plugin` section supplied, as opposed to
- * ov.conf's harness block or the environment — the credential chain ranks
- * those two itself, and would rank a `plugin` value wrong.
- */
-function fromPluginSection(settings, sources, name) {
- return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
-}
-
/**
* One harness's whole configuration: the files, the knobs, the peer, and the
* handful of fields derived from them.
@@ -184,12 +174,16 @@ function fromPluginSection(settings, sources, name) {
* else. What is left in a loader after this call is what only that harness
* knows.
*
- * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
- * host hands it one of its own); `hostInput` is what an embedding host named
- * for this process, which is the more specific answer and outranks every file;
- * `logFile` is the log basename this harness has always used, and a harness
- * that never had a default log path does not get one invented for it;
- * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * The connection — server, key, identity, auth mode — is not a knob: it comes
+ * from `resolveConnection`, the same call an MCP proxy's connection comes
+ * from, and the `plugin` keys and ov.conf block that name it are read there.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get for its
+ * knobs (dsh's host hands it one of its own); `hostInput` is what an embedding
+ * host named for this process, which is the more specific answer and outranks
+ * every file; `logFile` is the log basename this harness has always used, and
+ * a harness that never had a default log path does not get one invented for
+ * it; `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
* pinning and has always ended at `server.root_api_key`.
*/
export function buildPluginConfig(harness, {
@@ -217,46 +211,15 @@ export function buildPluginConfig(harness, {
cliFile: files.cliFile,
clientVersion,
});
- const credentials = resolveOpenVikingCredentials(env, key, {
- apiKey: fromPluginSection(settings, sources, "apiKey"),
- accountId: fromPluginSection(settings, sources, "accountId"),
- userId: fromPluginSection(settings, sources, "userId"),
- });
-
- // Pinned to ovcli.conf, the credential chain stops at that file. The layers
- // under it still answer: ov.conf's harness block is where tuning used to
- // live, and `server.root_api_key` is where a harness that predates the
- // pinning has always ended its chain.
- let apiKey = credentials.apiKey;
- let apiKeySource = credentials.apiKeySource;
- let credentialPath = credentials.credentialPath;
- if (!apiKey) {
- apiKey = sources.apiKey === OV_CONF_LAYER
- ? str(settings.apiKey)
- : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
- if (apiKey) {
- apiKeySource = "ov";
- credentialPath = credentials.ovPath;
- }
- }
- const hostApiKey = str(hostInput.apiKey);
- if (hostApiKey) {
- apiKey = hostApiKey;
- apiKeySource = "host";
- credentialPath = "";
- }
-
- const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
- const baseUrl = hostBaseUrl || credentials.baseUrl;
- const account = str(hostInput.account) || credentials.account;
- const user = str(hostInput.user) || credentials.user;
+ const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback });
+ const { baseUrl, account, user } = connection;
const timeoutMs = settings.timeoutMs;
const peerId = resolvePluginPeerId({
settings,
configured,
sources,
- credentials,
- hostInput: hostInput.peerId,
+ credentials: connection,
+ hostInput: hostInput?.peerId,
env,
});
@@ -267,21 +230,22 @@ export function buildPluginConfig(harness, {
userAgent: buildUserAgent(name, clientVersion),
baseUrl,
- mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
- apiKey,
+ mcpUrl: connection.mcpUrl,
+ apiKey: connection.apiKey,
account,
user,
- ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+ authMode: connection.authMode,
+ sendIdentityHeaders: connection.sendIdentityHeaders,
- credentialSource: credentials.credentialSource,
- apiKeySource,
- credentialPath,
- hasApiKey: Boolean(apiKey),
- configPath: credentials.cliPath || credentials.ovPath || null,
- cliConfigPath: credentials.cliPath,
- ovConfigPath: credentials.ovPath,
- cliPath: credentials.cliPath,
- ovPath: credentials.ovPath,
+ credentialSource: connection.credentialSource,
+ apiKeySource: connection.apiKeySource,
+ credentialPath: connection.credentialPath,
+ hasApiKey: connection.hasApiKey,
+ configPath: connection.cliPath || connection.ovPath || null,
+ cliConfigPath: connection.cliPath,
+ ovConfigPath: connection.ovPath,
+ cliPath: connection.cliPath,
+ ovPath: connection.ovPath,
peerId,
explicitPeerId: peerId,
@@ -308,7 +272,7 @@ export function buildPluginConfig(harness, {
// it per session, against the directory the payload names, and an MCP proxy
// must not derive one from wherever it happened to be launched.
if (deriveEffectivePeer) {
- const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env });
config.effectivePeer = effectivePeer;
config.legacyPeerId = effectivePeer.legacyPeerId;
}
diff --git a/examples/memory-plugin-shared/mcp-hook-parity.test.mjs b/examples/memory-plugin-shared/mcp-hook-parity.test.mjs
new file mode 100644
index 000000000..63152588a
--- /dev/null
+++ b/examples/memory-plugin-shared/mcp-hook-parity.test.mjs
@@ -0,0 +1,234 @@
+/**
+ * A harness's hooks and its MCP proxy must reach the server as the same caller.
+ *
+ * They run in different processes, and the proxy's process sees only what its
+ * host hands it: Codex forwards the names in `.mcp.json`'s `env_vars`, DSH
+ * drops credential-shaped names and adds the bundle's forwarded connection,
+ * the others inherit everything. Each
+ * row below states that rule, and every scenario runs the hook loader on the
+ * full environment and the proxy on what that rule lets through, then compares
+ * what goes on the wire. Comparing the resolved connection alone would miss
+ * exactly the drift this exists for: a variable the proxy never receives.
+ */
+
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { join } from "node:path";
+import { after, before, test } from "node:test";
+
+import { loadAgentHookConfig } from "./lib/agent-hook-runtime.mjs";
+import { ROOT } from "./sync.mjs";
+import { scrubOpenVikingEnv, writeCredentialFiles } from "./testing/support.mjs";
+import { HOSTS } from "../agent-hook-plugin/hosts/index.mjs";
+import { readProxyConfig as agentHookProxy } from "../agent-hook-plugin/servers/mcp-proxy.mjs";
+import { loadConfig as loadClaudeCode } from "../claude-code-memory-plugin/scripts/config.mjs";
+import { readProxyConfig as claudeCodeProxy } from "../claude-code-memory-plugin/servers/mcp-proxy.mjs";
+import { loadConfig as loadCodex } from "../codex-memory-plugin/scripts/config.mjs";
+import { readProxyConfig as codexProxy } from "../codex-memory-plugin/servers/mcp-proxy.mjs";
+import { resolveConfig as loadDsh } from "../dsh-memory-plugin/config.mjs";
+import { buildMcpConfig as dshMcpConfig } from "../dsh-memory-plugin/mcp-env.mjs";
+import { readProxyConfig as dshProxy } from "../dsh-memory-plugin/servers/mcp-proxy.mjs";
+import { loadConfig as loadOpencode } from "../opencode-plugin/lib/config.mjs";
+import { readProxyConfig as opencodeProxy } from "../opencode-plugin/servers/mcp-proxy.mjs";
+
+const WIRE = ["mcpUrl", "apiKey", "account", "user", "sendIdentityHeaders"];
+const wire = (cfg) => Object.fromEntries(WIRE.map((field) => [field, cfg[field]]));
+const pick = (env, names) => Object.fromEntries(names.filter((name) => name in env).map((name) => [name, env[name]]));
+
+const CODEX_ENV_VARS = JSON.parse(readFileSync(join(ROOT, "examples", "codex-memory-plugin", ".mcp.json"), "utf-8"))
+ .mcpServers["openviking-memory"].env_vars;
+
+// What a DSH child inherits: the parent's environment minus the names
+// `@deepseek-ai/dsh-subprocess` treats as credentials.
+const DSH_SCRUBBED = /KEY|PASSWORD|SECRET|TOKEN/i;
+const dshInherited = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !DSH_SCRUBBED.test(name)));
+
+const HARNESSES = [
+ {
+ name: "codex",
+ dir: "codex-memory-plugin",
+ section: "codex",
+ hook: ({ env, cwd }) => loadCodex(cwd, { env }),
+ proxy: ({ env }) => codexProxy(pick(env, CODEX_ENV_VARS)),
+ },
+ {
+ name: "claude-code",
+ dir: "claude-code-memory-plugin",
+ section: "claude_code",
+ rootKeyFallback: true,
+ hook: ({ env, cwd }) => loadClaudeCode(cwd, { env }),
+ proxy: ({ env }) => claudeCodeProxy(env),
+ },
+ {
+ name: "opencode",
+ dir: "opencode-plugin",
+ section: "opencode",
+ hook: ({ env, cwd }) => loadOpencode("", cwd, { env }),
+ proxy: ({ env }) => opencodeProxy(env),
+ },
+ // The installer names the client in the MCP server's environment.
+ ...Object.keys(HOSTS).map((client) => ({
+ name: client,
+ dir: "agent-hook-plugin",
+ section: client.replace(/-/g, "_"),
+ hook: ({ env, cwd }) => loadAgentHookConfig(client, cwd, { env }),
+ proxy: ({ env }) => agentHookProxy({ ...env, OPENVIKING_HOOK_SOURCE: client }),
+ })),
+ // A hand-written MCP entry that names no client.
+ {
+ name: "agent-hook",
+ dir: "agent-hook-plugin",
+ section: "agent_hook",
+ hook: ({ env, cwd }) => loadAgentHookConfig("agent-hook", cwd, { env }),
+ proxy: ({ env }) => agentHookProxy(env),
+ },
+ {
+ name: "dsh",
+ dir: "dsh-memory-plugin",
+ section: "dsh",
+ hook: ({ env, cwd, host }) => loadDsh({ workspacePeer: false, ...host }, env, cwd),
+ proxy: ({ env, hook, otherDir }) => dshProxy({ ...dshInherited(env), ...dshMcpConfig(hook).env }, otherDir),
+ },
+];
+
+const URL = "https://ov.example.com";
+
+/**
+ * `ovcli` and `ov` are the two files, or a function of the harness for a
+ * section named after it; `env` is added to the hook's environment; `host` is
+ * what an embedding host passes (dsh reads it, the rest have none); `expect`
+ * pins the answer as well, so both sides cannot agree on a wrong one.
+ */
+const SCENARIOS = [
+ {
+ name: "ovcli.conf's own key and identity",
+ ovcli: { url: URL, api_key: "sk-cli", account: "acct-cli", user: "usr-cli" },
+ },
+ {
+ name: "the key and identity in plugin.<harness>",
+ ovcli: (h) => ({ url: URL, plugin: { [h.section]: { apiKey: "sk-plugin-h", accountId: "acct-plugin-h", userId: "usr-plugin-h" } } }),
+ expect: () => ({ apiKey: "sk-plugin-h", account: "acct-plugin-h", user: "usr-plugin-h", sendIdentityHeaders: true }),
+ },
+ {
+ name: "the shared plugin section",
+ ovcli: { url: URL, plugin: { apiKey: "sk-plugin", accountId: "acct-plugin", authMode: "api_key" } },
+ expect: () => ({ apiKey: "sk-plugin", sendIdentityHeaders: false }),
+ },
+ {
+ name: "a url-only ovcli.conf over ov.conf's harness key",
+ ovcli: { url: URL },
+ ov: (h) => ({ server: { root_api_key: "sk-root" }, [h.section]: { apiKey: "sk-ov-h" } }),
+ expect: () => ({ apiKey: "sk-ov-h" }),
+ },
+ {
+ name: "credential variables taking the chain off ovcli.conf",
+ ovcli: { url: URL, api_key: "sk-cli", account: "acct-cli" },
+ env: { OPENVIKING_URL: "https://env.example.com", OPENVIKING_API_KEY: "sk-env" },
+ expect: () => ({ mcpUrl: "https://env.example.com/mcp", apiKey: "sk-env" }),
+ },
+ {
+ name: "OPENVIKING_AUTH_MODE keeping the identity off the wire",
+ ovcli: { url: URL, api_key: "sk-cli", account: "acct-cli", user: "usr-cli" },
+ env: { OPENVIKING_AUTH_MODE: "api_key" },
+ expect: () => ({ sendIdentityHeaders: false }),
+ },
+ {
+ name: "a forced ovcli.conf source over stale credentials in the environment",
+ ovcli: { url: URL, api_key: "sk-cli" },
+ env: { OPENVIKING_CREDENTIAL_SOURCE: "cli", OPENVIKING_API_KEY: "sk-stale", OPENVIKING_ACCOUNT: "acct-stale" },
+ expect: () => ({ apiKey: "sk-cli", account: "", sendIdentityHeaders: false }),
+ },
+ {
+ name: "a url-only ovcli.conf over the root key",
+ ovcli: { url: URL },
+ ov: { server: { root_api_key: "sk-root" } },
+ expect: (h) => ({ apiKey: h.rootKeyFallback ? "sk-root" : "" }),
+ },
+ {
+ name: "an install with only ov.conf",
+ ov: (h) => ({ server: { url: URL, root_api_key: "sk-root", auth_mode: "trusted" }, [h.section]: { accountId: "acct-ov-h" } }),
+ },
+ {
+ name: "an explicit MCP URL",
+ ovcli: { url: URL, api_key: "sk-cli" },
+ env: { OPENVIKING_MCP_URL: "https://mcp.example.com/custom" },
+ expect: () => ({ mcpUrl: "https://mcp.example.com/custom" }),
+ },
+ {
+ name: "a connection the host named",
+ ovcli: { url: URL, api_key: "sk-cli", account: "acct-cli" },
+ host: { endpoint: "https://host.example.com", apiKey: "sk-host", user: "usr-host", authMode: "api_key" },
+ },
+ {
+ name: "a workspace file that tries to move the connection",
+ ovcli: { url: URL, api_key: "sk-cli", account: "acct-cli" },
+ workspace: {
+ version: 1,
+ url: "https://workspace.example.com",
+ api_key: "sk-workspace",
+ auth_mode: "api_key",
+ peer: { id: "team-a" },
+ recall: { max_items: 3, peer_scope: "actor" },
+ },
+ expect: () => ({ mcpUrl: `${URL}/mcp`, apiKey: "sk-cli", account: "acct-cli", sendIdentityHeaders: true }),
+ },
+];
+
+let restoreEnv;
+before(() => { restoreEnv = scrubOpenVikingEnv(); });
+after(() => restoreEnv());
+
+const resolveFile = (file, harness) => (typeof file === "function" ? file(harness) : file);
+
+async function runScenario(scenario, harness) {
+ const files = await writeCredentialFiles("ov-parity-", {
+ ovcli: resolveFile(scenario.ovcli, harness),
+ ov: resolveFile(scenario.ov, harness),
+ });
+ try {
+ // The hook runs in a workspace; the proxy runs wherever its host started it.
+ const cwd = join(files.dir, "workspace");
+ const otherDir = join(files.dir, "other");
+ mkdirSync(join(cwd, ".git"), { recursive: true });
+ mkdirSync(join(cwd, ".openviking"), { recursive: true });
+ mkdirSync(otherDir, { recursive: true });
+ if (scenario.workspace) {
+ writeFileSync(join(cwd, ".openviking", "config.json"), JSON.stringify(scenario.workspace));
+ }
+ const env = { ...files.env, ...scenario.env };
+ const hook = harness.hook({ env, cwd, host: scenario.host || {} });
+ const proxy = harness.proxy({ env, hook, otherDir });
+ return { hook: wire(hook), proxy: wire(proxy) };
+ } finally {
+ await rm(files.dir, { recursive: true, force: true });
+ }
+}
+
+for (const scenario of SCENARIOS) {
+ test(`hooks and MCP proxy agree: ${scenario.name}`, async () => {
+ for (const harness of HARNESSES) {
+ const { hook, proxy } = await runScenario(scenario, harness);
+ assert.deepEqual(proxy, hook, `${harness.name}: the MCP proxy would reach the server as someone else`);
+ if (scenario.expect) {
+ const expected = scenario.expect(harness);
+ assert.deepEqual(
+ Object.fromEntries(Object.keys(expected).map((field) => [field, hook[field]])),
+ expected,
+ `${harness.name}: both sides agree, on the wrong answer`,
+ );
+ }
+ }
+ });
+}
+
+test("every proxy that ships beside hooks has a row, and so does every hook client", () => {
+ const shipped = readdirSync(join(ROOT, "examples"), { withFileTypes: true })
+ .filter((entry) => entry.isDirectory() && existsSync(join(ROOT, "examples", entry.name, "servers", "mcp-proxy.mjs")))
+ .map((entry) => entry.name)
+ .sort();
+ assert.deepEqual([...new Set(HARNESSES.map((harness) => harness.dir))].sort(), shipped);
+
+ const names = new Set(HARNESSES.map((harness) => harness.name));
+ for (const client of Object.keys(HOSTS)) assert.ok(names.has(client), `${client} needs a row`);
+});
diff --git a/examples/memory-plugin-shared/mcp-proxy-config.test.mjs b/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
index ca74d1edc..617236571 100644
--- a/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
+++ b/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
@@ -1,21 +1,26 @@
import assert from "node:assert/strict";
import { existsSync, readdirSync, readFileSync } from "node:fs";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
-import { homedir, tmpdir } from "node:os";
+import { rm } from "node:fs/promises";
+import { homedir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { buildProxyConnection } from "./lib/credentials.mjs";
+import { KNOB_BY_NAME } from "./lib/config-schema.mjs";
+import { buildProxyConnection, CONNECTION_ENV_VARS, resolveConnection } from "./lib/credentials.mjs";
import {
buildMcpProxyConfig,
DEFAULT_PROXY_TIMEOUT_MS,
defaultCredentialPaths,
+ forwardConnectionEnv,
+ MCP_PROXY_ENV_VARS,
normalizeConfigPath,
parseExtraHeaders,
resolveMcpActorPeerId,
+ toMcpProxyConfig,
trimSlash,
} from "./lib/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "./lib/mcp-proxy-core.mjs";
import { ROOT } from "./sync.mjs";
+import { writeCredentialFiles } from "./testing/support.mjs";
const OVCLI = join(homedir(), ".openviking", "ovcli.conf");
const OV = join(homedir(), ".openviking", "ov.conf");
@@ -118,21 +123,125 @@ test("path and URL helpers stay exported for entrypoints that need them", () =>
assert.equal(defaultCredentialPaths({}).length, 2);
});
-test("every MCP proxy shapes its config through the shared builder", () => {
+test("the forwarded-env list names every variable a proxy's config reads", () => {
+ const knobEnv = ["recallPeerScope", "timeoutMs", "debug", "debugLogPath", "authMode"]
+ .map((name) => KNOB_BY_NAME.get(name).env);
+ const expected = new Set([
+ ...CONNECTION_ENV_VARS,
+ ...knobEnv,
+ "OPENVIKING_EXTRA_HEADERS",
+ "OPENVIKING_HOME",
+ "OPENVIKING_STATE_DIR",
+ ]);
+ assert.deepEqual(new Set(MCP_PROXY_ENV_VARS), expected);
+ assert.equal(MCP_PROXY_ENV_VARS.length, expected.size, "no name is listed twice");
+});
+
+test("a forwarded connection resolves back to itself, whatever the files hold", async () => {
+ const files = await writeCredentialFiles("ov-proxy-forward-", {
+ ovcli: { url: "https://cli.example.com", plugin: { codex: { accountId: "acct-plugin" } } },
+ ov: { server: { root_api_key: "root-key", auth_mode: "trusted" }, codex: { apiKey: "sk-ov" } },
+ });
+ const fields = (c) => ({
+ baseUrl: c.baseUrl,
+ mcpUrl: c.mcpUrl,
+ apiKey: c.apiKey,
+ account: c.account,
+ user: c.user,
+ authMode: c.authMode,
+ });
+ try {
+ for (const connection of [
+ resolveConnection("codex", { env: files.env }),
+ resolveConnection("codex", { env: { ...files.env, OPENVIKING_AUTH_MODE: "api_key" }, hostInput: { user: "host-user" } }),
+ resolveConnection("codex", { env: { ...files.env, OPENVIKING_MCP_URL: "https://mcp.example.com/x", OPENVIKING_API_KEY: "sk-env" } }),
+ ]) {
+ // Names a host lets a child inherit may not fill what the parent left empty.
+ const inherited = { ...files.env, OPENVIKING_ACCOUNT: "stale", OPENVIKING_USER: "stale", OPENVIKING_PEER_ID: "stale" };
+ const back = resolveConnection("codex", { env: { ...inherited, ...forwardConnectionEnv(connection) } });
+ assert.deepEqual(fields(back), fields(connection));
+ assert.equal(back.peerId, connection.peerId);
+ }
+ } finally {
+ await rm(files.dir, { recursive: true, force: true });
+ }
+});
+
+test("the shared mapper carries every connection field a loader resolved", () => {
+ const cfg = {
+ baseUrl: "https://ov.example.com",
+ mcpUrl: "https://ov.example.com/custom-mcp",
+ apiKey: "sk",
+ account: "acme",
+ user: "alice",
+ sendIdentityHeaders: true,
+ peerId: "workspace-a",
+ recallPeerScope: "all",
+ userAgent: "openviking-memory-codex/1.0.0",
+ timeoutMs: 30000,
+ debug: true,
+ debugLogPath: "/tmp/codex.log",
+ credentialSource: "ovcli",
+ credentialPath: "/cfg/ovcli.conf",
+ cliPath: "/cfg/ovcli.conf",
+ ovPath: "",
+ };
+ const proxy = toMcpProxyConfig(cfg, { env: {} });
+ assert.deepEqual(
+ { ...proxy, watchedPaths: proxy.watchedPaths.slice(0, 1) },
+ {
+ mcpUrl: "https://ov.example.com/custom-mcp",
+ apiKey: "sk",
+ account: "acme",
+ user: "alice",
+ sendIdentityHeaders: true,
+ peerId: "",
+ userAgent: "openviking-memory-codex/1.0.0",
+ timeoutMs: 30000,
+ debug: true,
+ debugLogPath: "/tmp/codex.log",
+ credentialSource: "ovcli",
+ credentialPath: "/cfg/ovcli.conf",
+ watchedPaths: ["/cfg/ovcli.conf"],
+ extraHeaders: {},
+ },
+ );
+
+ assert.equal(toMcpProxyConfig({ ...cfg, recallPeerScope: "actor" }, { env: {} }).peerId, "workspace-a");
+ assert.equal(toMcpProxyConfig(cfg, { env: {}, peerId: "from-parent" }).peerId, "from-parent");
+ const quiet = toMcpProxyConfig(cfg, { env: {}, debug: false, debugLogPath: "" });
+ assert.equal(quiet.debug, false);
+ assert.equal(quiet.debugLogPath, "");
+});
+
+test("every MCP proxy shapes its config through the shared mapper", () => {
assert.equal(
MCP_PROXIES.length,
MCP_PROXY_COUNT,
`expected ${MCP_PROXY_COUNT} proxies, found ${MCP_PROXIES.map((p) => p.rel).join(", ")}`,
);
for (const { rel, source } of MCP_PROXIES) {
+ assert.match(source, /toMcpProxyConfig\(/, `${rel} must map its config through toMcpProxyConfig`);
+ assert.doesNotMatch(source, /buildMcpProxyConfig\(/, `${rel} must not pick fields for the proxy by hand`);
assert.match(
source,
- /buildMcpProxyConfig\(/,
- `${rel} must shape its config through buildMcpProxyConfig`,
+ /export function readProxyConfig\(env = process\.env/,
+ `${rel} must export readProxyConfig(env) so the parity test can drive it`,
);
}
});
+test("a proxy shipped beside hooks takes its connection from the hook loader", () => {
+ // A proxy that resolves the connection itself runs without the options its
+ // harness's loader passes — the host input, the root-key fallback — and
+ // would authenticate as someone other than the hooks. Only the portable
+ // package, which has no hook loader, reads credentials.mjs directly.
+ for (const { rel, source } of MCP_PROXIES) {
+ if (rel.startsWith("agent-plugins/")) continue;
+ assert.doesNotMatch(source, /credentials\.mjs/, `${rel} must not resolve credentials on its own`);
+ }
+});
+
test("no MCP proxy derives its peer from the launch directory", () => {
// A proxy is long-lived and may start anywhere, so unlike a hook it cannot
// re-derive a peer per turn. Codex already had this rule; it holds for all.
@@ -212,25 +321,11 @@ test("the identity headers follow the auth mode, not a resolved account", async
assert.equal(sent[1]["X-OpenViking-User"], "alice");
});
-async function credentialFiles(prefix, { ovcli, ov }) {
- const dir = await mkdtemp(join(tmpdir(), prefix));
- const cliPath = join(dir, "ovcli.conf");
- const ovPath = join(dir, "ov.conf");
- await writeFile(cliPath, JSON.stringify(ovcli, null, 2) + "\n");
- await writeFile(ovPath, JSON.stringify(ov, null, 2) + "\n");
- return {
- dir,
- cliPath,
- ovPath,
- env: { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: ovPath },
- };
-}
-
// The portable bundle ships without an installer, so nobody moves a working
// install's key out of ov.conf for it. ovcli.conf naming only a url pins the
// credential chain to that file, and the chain has to keep going anyway.
test("a portable proxy keeps the server key when ovcli.conf names only a url", async () => {
- const files = await credentialFiles("ov-proxy-rootkey-", {
+ const files = await writeCredentialFiles("ov-proxy-rootkey-", {
ovcli: { url: "https://ov.example.com" },
ov: { server: { root_api_key: "root-key" } },
});
@@ -249,7 +344,7 @@ test("a portable proxy keeps the server key when ovcli.conf names only a url", a
});
test("a portable proxy reports the auth mode, its own log path, and the files to watch", async () => {
- const files = await credentialFiles("ov-proxy-shape-", {
+ const files = await writeCredentialFiles("ov-proxy-shape-", {
ovcli: { url: "https://ov.example.com", api_key: "cli-key", account: "acme", user: "alice" },
ov: {},
});
@@ -266,7 +361,7 @@ test("a portable proxy reports the auth mode, its own log path, and the files to
join(homedir(), ".openviking", "logs", "agent-plugins.log"),
);
assert.deepEqual(
- buildMcpProxyConfig({ watchedPaths: cfg.watchedPaths, env: files.env }).watchedPaths,
+ toMcpProxyConfig(cfg, { env: files.env }).watchedPaths,
[files.cliPath, files.ovPath, OVCLI, OV],
);
@@ -282,7 +377,7 @@ test("a portable proxy reports the auth mode, its own log path, and the files to
});
test("an api_key deployment keeps the operator's identity off the wire", async () => {
- const files = await credentialFiles("ov-proxy-apikey-", {
+ const files = await writeCredentialFiles("ov-proxy-apikey-", {
ovcli: { url: "https://ov.example.com", api_key: "cli-key", account: "acme" },
ov: { server: { auth_mode: "api_key" } },
});
diff --git a/examples/memory-plugin-shared/testing/support.mjs b/examples/memory-plugin-shared/testing/support.mjs
index 200ecf96e..c22dd8828 100644
--- a/examples/memory-plugin-shared/testing/support.mjs
+++ b/examples/memory-plugin-shared/testing/support.mjs
@@ -9,7 +9,7 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
import http from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -32,6 +32,44 @@ export function buildConfigForTest(harness) {
});
}
+/**
+ * An ovcli.conf / ov.conf pair in a fresh directory, and the env that points
+ * the credential chain at it. A file given as `null` is not written, so the
+ * chain sees it as absent rather than as a real ~/.openviking.
+ */
+export async function writeCredentialFiles(prefix, { ovcli = null, ov = null } = {}) {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ const cliPath = join(dir, "ovcli.conf");
+ const ovPath = join(dir, "ov.conf");
+ if (ovcli) await writeFile(cliPath, JSON.stringify(ovcli, null, 2) + "\n");
+ if (ov) await writeFile(ovPath, JSON.stringify(ov, null, 2) + "\n");
+ return {
+ dir,
+ cliPath,
+ ovPath,
+ env: { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: ovPath, OPENVIKING_HOME: join(dir, "home") },
+ };
+}
+
+const isOpenVikingVar = (name) => name.startsWith("OPENVIKING_") || name === "OV_DEBUG_LOG";
+
+/**
+ * Clear the developer shell's `OPENVIKING_*` out of process.env, and return
+ * the function that puts them back. A test that injects its env everywhere
+ * still runs under this, so a read that slips past the injection fails the
+ * same way on every machine instead of passing on the one with a config.
+ */
+export function scrubOpenVikingEnv() {
+ const saved = Object.entries(process.env).filter(([name]) => isOpenVikingVar(name));
+ for (const [name] of saved) delete process.env[name];
+ return () => {
+ for (const name of Object.keys(process.env)) {
+ if (isOpenVikingVar(name)) delete process.env[name];
+ }
+ for (const [name, value] of saved) process.env[name] = value;
+ };
+}
+
const PENDING_ENV_KEYS = [
"OPENVIKING_PENDING_DIR",
"OPENVIKING_PENDING_MAX_RETRIES",
diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjs
index f6e2152e6..4847d9631 100644
--- a/examples/opencode-plugin/lib/config.mjs
+++ b/examples/opencode-plugin/lib/config.mjs
@@ -23,9 +23,10 @@ function expandHome(value) {
return value
}
-export function loadConfig(pluginRoot, projectDirectory) {
+export function loadConfig(pluginRoot, projectDirectory, { env = process.env } = {}) {
const config = buildPluginConfig("opencode", {
cwd: projectDirectory,
+ env,
manifestUrl: MANIFEST_URL,
logFile: "opencode-plugin.log",
deriveEffectivePeer: true,
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index fa5184658..c4cb449a1 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.3.1",
+ "version": "0.3.2",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
diff --git a/examples/opencode-plugin/servers/mcp-proxy.mjs b/examples/opencode-plugin/servers/mcp-proxy.mjs
index 5523be8d4..81b33fb6b 100644
--- a/examples/opencode-plugin/servers/mcp-proxy.mjs
+++ b/examples/opencode-plugin/servers/mcp-proxy.mjs
@@ -3,8 +3,8 @@
/**
* stdio -> streamable-HTTP MCP proxy for the OpenViking OpenCode plugin.
*
- * OpenCode starts this process as a local MCP server. The proxy reads the same
- * OpenViking credential sources as the lifecycle hooks, forwards JSON-RPC
+ * OpenCode starts this process as a local MCP server. The proxy resolves its
+ * connection through the plugin's own `loadConfig()`, forwards JSON-RPC
* requests to the server's /mcp endpoint, and keeps stdout protocol-clean.
*/
@@ -12,27 +12,13 @@ import { resolve as resolvePath } from "node:path"
import { fileURLToPath } from "node:url"
import { loadConfig } from "../lib/config.mjs"
import { createLogger } from "../lib/shared/debug-log.mjs"
-import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../lib/shared/mcp-proxy-config.mjs"
+import { toMcpProxyConfig } from "../lib/shared/mcp-proxy-config.mjs"
import { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"
-function readProxyConfig() {
- const cfg = loadConfig(resolvePath(fileURLToPath(import.meta.url), "..", ".."))
- return buildMcpProxyConfig({
- baseUrl: cfg.endpoint,
- mcpUrl: cfg.mcpUrl,
- apiKey: cfg.apiKey,
- account: cfg.account,
- user: cfg.user,
- sendIdentityHeaders: cfg.sendIdentityHeaders,
- peerId: resolveMcpActorPeerId(cfg),
- userAgent: cfg.userAgent,
- timeoutMs: cfg.timeoutMs,
- debug: cfg.debug,
- debugLogPath: cfg.debugLogPath,
- credentialSource: cfg.credentialSource,
- credentialPath: cfg.credentialPath || cfg.configPath,
- watchedPaths: [cfg.credentialPath, cfg.configPath],
- })
+const PLUGIN_ROOT = resolvePath(fileURLToPath(import.meta.url), "..", "..")
+
+export function readProxyConfig(env = process.env) {
+ return toMcpProxyConfig(loadConfig(PLUGIN_ROOT, undefined, { env }), { env })
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.md
index b080e592e..9ad32c28e 100644
--- a/examples/pi-coding-agent-extension/DESIGN.md
+++ b/examples/pi-coding-agent-extension/DESIGN.md
@@ -42,7 +42,7 @@ pi-coding-agent-extension/
Defines `OVConfig` and resolves it once at load time. Knobs come from `resolveSettings("pi", { cwd })`: every one of them is declared in `shared/config-schema.mjs` and resolved through the same layers as every other harness — environment, the workspace's `.openviking/config.json` and machine registry entry, `ovcli.conf`'s `plugin.pi`, `ovcli.conf`'s `plugin`, then the schema default. The extension has no configuration file of its own. It used to ship one holding exactly the code defaults, which made an operator's choice indistinguishable from a factory setting.
-Credentials — server URL, API key, account, user — come from `resolveOpenVikingCredentials(process.env, "pi")`, and `resolveAuthMode` decides between `trusted` and `api_key`, which is what gates whether identity headers go on the wire at all. The peer identity is resolved twice on purpose: `resolvePluginPeerId` picks the id from the configured layers, then `resolveEffectivePeerId` maps it onto the workspace and also returns `legacyPeerId`, the pre-git workspace id that recall still has to reach.
+Credentials — server URL, API key, account, user — and the auth mode that gates whether identity headers go on the wire at all come from `resolveConnection("pi")`, the one connection resolver every harness's hooks and MCP proxy share. The peer identity is resolved twice on purpose: `resolvePluginPeerId` picks the id from the configured layers, then `resolveEffectivePeerId` maps it onto the workspace and also returns `legacyPeerId`, the pre-git workspace id that recall still has to reach.
Two older spellings are kept alive because setups depend on them: `bypassPatterns` holds the same list as the shared `bypassSessionPatterns`, and `OV_DEBUG_LOG` is read alongside the shared `OPENVIKING_DEBUG_LOG`. `EXTENSION_VERSION` reads `package.json`, the same manifest the release gate watches for a bump, and feeds the shared `User-Agent` builder.
diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json
index 1cb40086f..431b71d59 100644
--- a/examples/pi-coding-agent-extension/package.json
+++ b/examples/pi-coding-agent-extension/package.json
@@ -1,6 +1,6 @@
{
"name": "openviking-pi-extension",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "OpenViking memory and context extension for the pi coding agent",
"private": true,
"type": "module"