Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(clients): resolve the API secret the same way as the server and hooks

Rohit Ghumare525e8968d985
diff --git a/integrations/filesystem-watcher/watcher.mjs b/integrations/filesystem-watcher/watcher.mjs
index 919e5707..b0d37830 100644
--- a/integrations/filesystem-watcher/watcher.mjs
+++ b/integrations/filesystem-watcher/watcher.mjs
@@ -135,21 +135,59 @@ function redactSensitivePreview(preview) {
return redactPemBlocks(preview).split("\n").map(redactSensitiveLine).join("\n");
}
-function storedSecret(url) {
+function usableSecret(value) {
+ const trimmed = typeof value === "string" ? value.trim() : "";
+ if (!trimmed || (trimmed.startsWith("${") && trimmed.endsWith("}"))) return "";
+ return trimmed;
+}
+
+function readAgentmemoryFile(name) {
try {
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
- if (host !== "localhost" && host !== "::1" && !/^127\./.test(host)) return "";
- return readFileSync(join(homedir(), ".agentmemory", "secret"), "utf-8").trim();
+ return readFileSync(join(homedir(), ".agentmemory", name), "utf-8");
} catch {
return "";
}
}
+function envFileSecret() {
+ let found = "";
+ for (const line of readAgentmemoryFile(".env").split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("#")) continue;
+ const eq = trimmed.indexOf("=");
+ if (eq === -1) continue;
+ if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== "AGENTMEMORY_SECRET") continue;
+ let value = trimmed.slice(eq + 1).trim();
+ const quote = value[0];
+ const close = quote === '"' || quote === "'" ? value.indexOf(quote, 1) : -1;
+ if (close > 0) value = value.slice(1, close);
+ else if (value.includes(" #")) value = value.slice(0, value.indexOf(" #"));
+ found = usableSecret(value);
+ }
+ return found;
+}
+
+function isLoopbackUrl(url) {
+ try {
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ return host === "localhost" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
+ } catch {
+ return false;
+ }
+}
+
+export function resolveSecret(url, explicit) {
+ const configured = usableSecret(explicit);
+ if (configured) return configured;
+ if (!isLoopbackUrl(url)) return "";
+ return envFileSecret() || usableSecret(readAgentmemoryFile("secret"));
+}
+
export class FilesystemWatcher {
constructor(config = {}) {
this.roots = (config.roots || []).map((r) => resolve(r));
this.baseUrl = (config.baseUrl || "http://localhost:3111").replace(/\/+$/, "");
- this.secret = config.secret || storedSecret(this.baseUrl);
+ this.secret = resolveSecret(this.baseUrl, config.secret);
this.project =
config.project ||
(this.roots[0] ? deriveProjectName(this.roots[0]) : "filesystem-watcher");
diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py
index 968fddfe..33e1d598 100644
--- a/integrations/hermes/__init__.py
+++ b/integrations/hermes/__init__.py
@@ -174,14 +174,50 @@ def _reset_plaintext_bearer_guard_for_tests() -> None:
_plaintext_bearer_warned = False
+def _usable_secret(value: str | None) -> str:
+ trimmed = (value or "").strip()
+ if not trimmed or (trimmed.startswith("${") and trimmed.endswith("}")):
+ return ""
+ return trimmed
+
+
+def _read_agentmemory_file(name: str) -> str:
+ try:
+ return (Path.home() / ".agentmemory" / name).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return ""
+
+
+def _env_file_secret() -> str:
+ found = ""
+ for raw in _read_agentmemory_file(".env").splitlines():
+ line = raw.strip()
+ if line.startswith("#") or "=" not in line:
+ continue
+ key, _, value = line.partition("=")
+ key = key.strip()
+ if key.startswith("export "):
+ key = key[len("export "):].strip()
+ if key != "AGENTMEMORY_SECRET":
+ continue
+ value = value.strip()
+ close = value.find(value[0], 1) if value[:1] in ("'", '"') else -1
+ if close > 0:
+ value = value[1:close]
+ elif " #" in value:
+ value = value[: value.index(" #")]
+ found = _usable_secret(value)
+ return found
+
+
def _stored_secret(base: str) -> str:
try:
host = (urlparse(base).hostname or "").lower()
- if host not in ("localhost", "::1") and not host.startswith("127."):
- return ""
- return (Path.home() / ".agentmemory" / "secret").read_text(encoding="utf-8").strip()
- except (OSError, ValueError):
+ except ValueError:
+ return ""
+ if host not in ("localhost", "::1") and not host.startswith("127."):
return ""
+ return _env_file_secret() or _usable_secret(_read_agentmemory_file("secret"))
def _api(base: str, path: str, body: dict | None = None, method: str = "POST", secret: str = "") -> dict | None:
@@ -189,7 +225,7 @@ def _api(base: str, path: str, body: dict | None = None, method: str = "POST", s
return None
url = f"{base}/agentmemory/{path}"
headers = {"Content-Type": "application/json"}
- auth = secret or os.environ.get("AGENTMEMORY_SECRET", "") or _stored_secret(base)
+ auth = _usable_secret(secret) or _usable_secret(os.environ.get("AGENTMEMORY_SECRET")) or _stored_secret(base)
_check_plaintext_bearer_guard(base, auth)
if auth:
headers["Authorization"] = f"Bearer {auth}"
diff --git a/integrations/openclaw/plugin.mjs b/integrations/openclaw/plugin.mjs
index 2a4b0158..ffd5e664 100644
--- a/integrations/openclaw/plugin.mjs
+++ b/integrations/openclaw/plugin.mjs
@@ -109,21 +109,59 @@ export function createPlaintextBearerAuthGuard(warn, env) {
};
}
-function storedSecret(url) {
+function usableSecret(value) {
+ const trimmed = typeof value === "string" ? value.trim() : "";
+ if (!trimmed || (trimmed.startsWith("${") && trimmed.endsWith("}"))) return "";
+ return trimmed;
+}
+
+function readAgentmemoryFile(name) {
try {
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
- if (host !== "localhost" && host !== "::1" && !/^127\./.test(host)) return "";
- return readFileSync(join(homedir(), ".agentmemory", "secret"), "utf-8").trim();
+ return readFileSync(join(homedir(), ".agentmemory", name), "utf-8");
} catch {
return "";
}
}
+function envFileSecret() {
+ let found = "";
+ for (const line of readAgentmemoryFile(".env").split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("#")) continue;
+ const eq = trimmed.indexOf("=");
+ if (eq === -1) continue;
+ if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== "AGENTMEMORY_SECRET") continue;
+ let value = trimmed.slice(eq + 1).trim();
+ const quote = value[0];
+ const close = quote === '"' || quote === "'" ? value.indexOf(quote, 1) : -1;
+ if (close > 0) value = value.slice(1, close);
+ else if (value.includes(" #")) value = value.slice(0, value.indexOf(" #"));
+ found = usableSecret(value);
+ }
+ return found;
+}
+
+function isLoopbackUrl(url) {
+ try {
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ return host === "localhost" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
+ } catch {
+ return false;
+ }
+}
+
+export function resolveSecret(url, explicit) {
+ const configured = usableSecret(explicit);
+ if (configured) return configured;
+ if (!isLoopbackUrl(url)) return "";
+ return envFileSecret() || usableSecret(readAgentmemoryFile("secret"));
+}
+
function createClient(cfg, api) {
const baseUrl = String(cfg.base_url || DEFAULT_BASE_URL).replace(/\/+$/, "");
const timeoutMs = Number(cfg.timeout_ms || DEFAULT_TIMEOUT_MS);
const fallbackOnError = cfg.fallback_on_error !== false;
- const secret = process.env.AGENTMEMORY_SECRET || storedSecret(baseUrl);
+ const secret = resolveSecret(baseUrl, process.env.AGENTMEMORY_SECRET);
const guardPlaintextBearerAuth = createPlaintextBearerAuthGuard(
(message) => api.logger.warn?.(message),
);
diff --git a/integrations/pi/security.ts b/integrations/pi/security.ts
index 6e4956bf..786771bb 100644
--- a/integrations/pi/security.ts
+++ b/integrations/pi/security.ts
@@ -4,16 +4,54 @@ import { join } from "node:path";
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
-export function resolveSecret(baseUrl: string, explicit?: string): string {
- if (explicit) return explicit;
+function usableSecret(value: unknown): string {
+ const trimmed = typeof value === "string" ? value.trim() : "";
+ if (!trimmed || (trimmed.startsWith("${") && trimmed.endsWith("}"))) return "";
+ return trimmed;
+}
+
+function readAgentmemoryFile(name: string): string {
try {
- if (!LOOPBACK_HOSTS.has(normalizedHostname(new URL(baseUrl).hostname))) return "";
- return readFileSync(join(homedir(), ".agentmemory", "secret"), "utf-8").trim();
+ return readFileSync(join(homedir(), ".agentmemory", name), "utf-8");
} catch {
return "";
}
}
+function envFileSecret(): string {
+ let found = "";
+ for (const line of readAgentmemoryFile(".env").split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("#")) continue;
+ const eq = trimmed.indexOf("=");
+ if (eq === -1) continue;
+ if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== "AGENTMEMORY_SECRET") continue;
+ let value = trimmed.slice(eq + 1).trim();
+ const quote = value[0];
+ const close = quote === '"' || quote === "'" ? value.indexOf(quote, 1) : -1;
+ if (close > 0) value = value.slice(1, close);
+ else if (value.includes(" #")) value = value.slice(0, value.indexOf(" #"));
+ found = usableSecret(value);
+ }
+ return found;
+}
+
+function isLoopbackUrl(url: string): boolean {
+ try {
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ return host === "localhost" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
+ } catch {
+ return false;
+ }
+}
+
+export function resolveSecret(url: string, explicit?: string): string {
+ const configured = usableSecret(explicit);
+ if (configured) return configured;
+ if (!isLoopbackUrl(url)) return "";
+ return envFileSecret() || usableSecret(readAgentmemoryFile("secret"));
+}
+
function normalizedHostname(hostname: string): string {
return hostname.replace(/^\[|\]$/g, "").toLowerCase();
}
diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts
index c9e2a5fa..0465bd58 100644
--- a/plugin/opencode/agentmemory-capture.ts
+++ b/plugin/opencode/agentmemory-capture.ts
@@ -13,17 +13,55 @@ const FILE_KEYS = ["filePath", "file_path", "path", "file", "pattern"];
const MAX_STASHED_FILES = 20;
const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1";
-function storedSecret(url: string): string {
+function usableSecret(value: unknown): string {
+ const trimmed = typeof value === "string" ? value.trim() : "";
+ if (!trimmed || (trimmed.startsWith("${") && trimmed.endsWith("}"))) return "";
+ return trimmed;
+}
+
+function readAgentmemoryFile(name: string): string {
try {
- const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
- if (host !== "localhost" && host !== "::1" && !/^127\./.test(host)) return "";
- return readFileSync(join(homedir(), ".agentmemory", "secret"), "utf-8").trim();
+ return readFileSync(join(homedir(), ".agentmemory", name), "utf-8");
} catch {
return "";
}
}
-const SECRET = process.env.AGENTMEMORY_SECRET || storedSecret(API);
+function envFileSecret(): string {
+ let found = "";
+ for (const line of readAgentmemoryFile(".env").split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("#")) continue;
+ const eq = trimmed.indexOf("=");
+ if (eq === -1) continue;
+ if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== "AGENTMEMORY_SECRET") continue;
+ let value = trimmed.slice(eq + 1).trim();
+ const quote = value[0];
+ const close = quote === '"' || quote === "'" ? value.indexOf(quote, 1) : -1;
+ if (close > 0) value = value.slice(1, close);
+ else if (value.includes(" #")) value = value.slice(0, value.indexOf(" #"));
+ found = usableSecret(value);
+ }
+ return found;
+}
+
+function isLoopbackUrl(url: string): boolean {
+ try {
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ return host === "localhost" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
+ } catch {
+ return false;
+ }
+}
+
+function resolveSecret(url: string, explicit: string | undefined): string {
+ const configured = usableSecret(explicit);
+ if (configured) return configured;
+ if (!isLoopbackUrl(url)) return "";
+ return envFileSecret() || usableSecret(readAgentmemoryFile("secret"));
+}
+
+const SECRET = resolveSecret(API, process.env.AGENTMEMORY_SECRET);
function authHeaders(): Record<string, string> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
diff --git a/src/index.ts b/src/index.ts
index 10233ff5..3b711ec3 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -174,8 +174,6 @@ process.on("unhandledRejection", (reason) => {
});
function resolveWorkerSecret(): string {
- const configured = getEnvVar("AGENTMEMORY_SECRET")?.trim();
- if (configured) return configured;
try {
const { secret, source } = ensureServerSecret();
if (source === "generated") {
diff --git a/test/client-secret-resolution.test.ts b/test/client-secret-resolution.test.ts
new file mode 100644
index 00000000..bbf40cb4
--- /dev/null
+++ b/test/client-secret-resolution.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { FilesystemWatcher } from "../integrations/filesystem-watcher/watcher.mjs";
+import { resolveSecret as openclawSecret } from "../integrations/openclaw/plugin.mjs";
+import { resolveSecret as piSecret } from "../integrations/pi/security.ts";
+
+const KEY = "AGENTMEMORY_SECRET";
+const LOCAL = "http://127.0.0.1:3111";
+
+type Resolver = (url: string, explicit?: string) => string;
+
+const resolvers: Array<[string, Resolver]> = [
+ ["filesystem watcher", (url, explicit) => new FilesystemWatcher({ baseUrl: url, secret: explicit }).secret],
+ ["openclaw", openclawSecret as Resolver],
+ ["pi", piSecret],
+];
+
+function hasPython(): boolean {
+ return spawnSync("python3", ["--version"], { stdio: "ignore" }).status === 0;
+}
+
+function hermesSecret(home: string, url: string, explicit?: string): string {
+ const script = [
+ "import importlib.util, sys",
+ "spec = importlib.util.spec_from_file_location('hermes_plugin', sys.argv[1])",
+ "mod = importlib.util.module_from_spec(spec)",
+ "spec.loader.exec_module(mod)",
+ "import os",
+ "print(mod._usable_secret(os.environ.get('AGENTMEMORY_SECRET')) or mod._stored_secret(sys.argv[2]))",
+ ].join("\n");
+ const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: home, USERPROFILE: home };
+ if (explicit !== undefined) env[KEY] = explicit;
+ const result = spawnSync("python3", ["-c", script, join(process.cwd(), "integrations", "hermes", "__init__.py"), url], {
+ env,
+ encoding: "utf-8",
+ });
+ if (result.status !== 0) throw new Error(result.stderr);
+ return result.stdout.trim();
+}
+
+describe("client secret resolution", () => {
+ let home: string;
+ const saved = { home: process.env.HOME, profile: process.env.USERPROFILE, value: process.env[KEY] };
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "am-client-secret-"));
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ delete process.env[KEY];
+ mkdirSync(join(home, ".agentmemory"), { recursive: true });
+ });
+
+ afterEach(() => {
+ process.env.HOME = saved.home;
+ if (saved.profile === undefined) delete process.env.USERPROFILE;
+ else process.env.USERPROFILE = saved.profile;
+ if (saved.value === undefined) delete process.env[KEY];
+ else process.env[KEY] = saved.value;
+ rmSync(home, { recursive: true, force: true });
+ vi.unstubAllGlobals();
+ vi.resetModules();
+ });
+
+ function writeSecrets(envFile?: string) {
+ writeFileSync(join(home, ".agentmemory", "secret"), "generated-secret\n");
+ if (envFile !== undefined) writeFileSync(join(home, ".agentmemory", ".env"), envFile);
+ }
+
+ describe.each(resolvers)("%s", (_name, resolve) => {
+ it("prefers the explicit secret", () => {
+ writeSecrets('AGENTMEMORY_SECRET="from-env-file"\n');
+ expect(resolve(LOCAL, "explicit-value")).toBe("explicit-value");
+ });
+
+ it("reads ~/.agentmemory/.env before the generated secret", () => {
+ writeSecrets('AGENTMEMORY_SECRET="from-env-file"\n');
+ expect(resolve(LOCAL)).toBe("from-env-file");
+ });
+
+ it("treats placeholders as unset", () => {
+ writeSecrets("AGENTMEMORY_SECRET=${AGENTMEMORY_SECRET}\n");
+ expect(resolve(LOCAL, "${AGENTMEMORY_SECRET}")).toBe("generated-secret");
+ });
+
+ it("reads stored files for every loopback address only", () => {
+ writeSecrets();
+ expect(resolve("http://127.0.0.2:3111")).toBe("generated-secret");
+ expect(resolve("http://[::1]:3111")).toBe("generated-secret");
+ expect(resolve("http://localhost:3111")).toBe("generated-secret");
+ expect(resolve("https://memory.example.com")).toBe("");
+ expect(resolve("http://localhost.example.com:3111")).toBe("");
+ });
+ });
+
+ it("opencode plugin sends the secret from ~/.agentmemory/.env", async () => {
+ writeSecrets('AGENTMEMORY_SECRET="from-env-file"\n');
+ process.env[KEY] = "${AGENTMEMORY_SECRET}";
+ const seen: Array<Record<string, string>> = [];
+ vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => {
+ seen.push((init?.headers || {}) as Record<string, string>);
+ return new Response("{}", { status: 200, headers: { "Content-Type": "application/json" } });
+ });
+ vi.resetModules();
+ const mod = await import("../plugin/opencode/agentmemory-capture.ts");
+ const hooks = await mod.AgentmemoryCapturePlugin({ worktree: home } as never);
+ await hooks.event?.({ event: { type: "session.status", properties: { sessionID: "ses_x", status: { type: "busy" } } } } as never);
+ expect(seen.length).toBeGreaterThan(0);
+ expect(seen[0]?.Authorization).toBe("Bearer from-env-file");
+ });
+
+ it.skipIf(!hasPython())("hermes follows the same order and keeps its loopback restriction", () => {
+ writeSecrets('AGENTMEMORY_SECRET="from-env-file"\n');
+ expect(hermesSecret(home, LOCAL)).toBe("from-env-file");
+ expect(hermesSecret(home, LOCAL, "explicit-value")).toBe("explicit-value");
+ expect(hermesSecret(home, "https://memory.example.com", "${AGENTMEMORY_SECRET}")).toBe("");
+ writeFileSync(join(home, ".agentmemory", ".env"), "AGENTMEMORY_SECRET=${AGENTMEMORY_SECRET}\n");
+ expect(hermesSecret(home, LOCAL)).toBe("generated-secret");
+ expect(hermesSecret(home, "https://memory.example.com")).toBe("");
+ });
+});
diff --git a/test/secret-store.test.ts b/test/secret-store.test.ts
index 79575e80..4bfb71ac 100644
--- a/test/secret-store.test.ts
+++ b/test/secret-store.test.ts
@@ -17,17 +17,25 @@ const KEY = "AGENTMEMORY_SECRET";
describe("stored API secret", () => {
let home: string;
- const saved = { home: process.env.HOME, value: process.env[KEY], url: process.env.AGENTMEMORY_URL };
+ const saved = {
+ home: process.env.HOME,
+ profile: process.env.USERPROFILE,
+ value: process.env[KEY],
+ url: process.env.AGENTMEMORY_URL,
+ };
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "am-secret-"));
process.env.HOME = home;
+ process.env.USERPROFILE = home;
delete process.env[KEY];
delete process.env.AGENTMEMORY_URL;
});
afterEach(() => {
process.env.HOME = saved.home;
+ if (saved.profile === undefined) delete process.env.USERPROFILE;
+ else process.env.USERPROFILE = saved.profile;
if (saved.value === undefined) delete process.env[KEY];
else process.env[KEY] = saved.value;
if (saved.url === undefined) delete process.env.AGENTMEMORY_URL;
@@ -135,6 +143,7 @@ describe("stored API secret", () => {
const env: NodeJS.ProcessEnv = {
PATH: process.env.PATH,
HOME: home,
+ USERPROFILE: home,
AGENTMEMORY_URL: `http://127.0.0.1:${port}`,
};
await runHook(join(process.cwd(), "plugin", "scripts", "session-start.mjs"), env);