#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
import {
chmodSync,
closeSync,
linkSync,
mkdirSync,
openSync,
readFileSync,
renameSync,
unlinkSync,
writeSync,
} from "node:fs";
import { randomBytes } from "node:crypto";
import { homedir } from "node:os";
import { join } from "node:path";
const SECRET_KEY = "AGENTMEMORY_SECRET";
export function agentmemoryHomeDir(): string {
return process.env["AGENTMEMORY_DATA_DIR"] || join(homedir(), ".agentmemory");
}
export function secretFilePath(): string {
return join(agentmemoryHomeDir(), "secret");
}
function usable(value: string | undefined): string {
if (typeof value !== "string") return "";
const trimmed = value.trim();
if (!trimmed) return "";
if (trimmed.startsWith("${") && trimmed.endsWith("}")) return "";
return trimmed;
}
function unquote(value: string): string {
const quote = value[0];
if ((quote === '"' || quote === "'") && value.length > 1) {
const close = value.indexOf(quote, 1);
if (close !== -1) return value.slice(1, close);
}
const hash = value.indexOf(" #");
return hash === -1 ? value : value.slice(0, hash).trim();
}
export function readEnvFileSecret(): string {
let content: unknown;
try {
content = readFileSync(process.env["AGENTMEMORY_ENV_FILE"] || join(homedir(), ".agentmemory", ".env"), "utf-8");
} catch {
return "";
}
if (typeof content !== "string") return "";
let found = "";
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq === -1) continue;
const key = trimmed.slice(0, eq).replace(/^export\s+/, "").trim();
if (key !== SECRET_KEY) continue;
found = usable(unquote(trimmed.slice(eq + 1).trim()));
}
return found;
}
function readSecretFile(path: string): string {
try {
return usable(readFileSync(path, "utf-8"));
} catch {
return "";
}
}
function legacyDataDirSecretPaths(env: NodeJS.ProcessEnv = process.env): string[] {
const dataDir = env["AGENTMEMORY_DATA_DIR"];
if (!dataDir) return [];
const paths = [join(dataDir, "secret"), join(dataDir, ".hmac"), join(dataDir, "..", ".hmac")];
return [...new Set(paths.filter((path) => path !== secretFilePath()))];
}
export function readStoredSecret(env: NodeJS.ProcessEnv = process.env): string {
const canonicalPath = canonicalSecretPath();
const localPath = secretFilePath();
const legacyPaths = legacyDataDirSecretPaths(env);
return readSecretFile(canonicalPath) ||
(localPath === canonicalPath ? "" : readSecretFile(localPath)) ||
legacyPaths.map(readSecretFile).find(Boolean) || "";
}
export function explicitSecret(env: NodeJS.ProcessEnv = process.env): string {
return usable(env[SECRET_KEY]) || readEnvFileSecret();
}
export function isLoopbackUrl(url: string): boolean {
let hostname: string;
try {
hostname = new URL(url).hostname.toLowerCase();
} catch {
return false;
}
const bare = hostname.replace(/^\[|\]$/g, "");
return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare);
}
export function resolveClientSecret(
baseUrl: string,
env: NodeJS.ProcessEnv = process.env,
): string {
const fromEnv = usable(env[SECRET_KEY]);
if (fromEnv) return fromEnv;
if (env.AGENTMEMORY_CREDENTIAL_MODE === "explicit") return "";
if (!isLoopbackUrl(baseUrl)) return "";
return readEnvFileSecret() || readStoredSecret(env);
}
function canonicalSecretPath(): string {
return join(homedir(), ".agentmemory", "secret");
}
function writeSecretFile(path: string, secret: string): void {
mkdirSync(join(path, ".."), { recursive: true, mode: 0o700 });
const staging = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
const fd = openSync(staging, "wx", 0o600);
try {
writeSync(fd, `${secret}\n`);
} finally {
closeSync(fd);
}
try {
chmodSync(staging, 0o600);
renameSync(staging, path);
chmodSync(path, 0o600);
} finally {
try { unlinkSync(staging); } catch {}
}
}
function writeSecretIfAbsent(path: string, secret: string): string {
mkdirSync(join(path, ".."), { recursive: true, mode: 0o700 });
const staging = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
const fd = openSync(staging, "wx", 0o600);
try {
writeSync(fd, `${secret}\n`);
} finally {
closeSync(fd);
}
try {
chmodSync(staging, 0o600);
linkSync(staging, path);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
} finally {
try { unlinkSync(staging); } catch {}
}
const stored = readSecretFile(path);
if (!stored) throw new Error(`Could not read stored API secret at ${path}.`);
return stored;
}
export function ensureServerSecret(env: NodeJS.ProcessEnv = process.env): {
secret: string;
source: "env" | "file" | "generated";
} {
const configured = explicitSecret(env);
if (configured) return { secret: configured, source: "env" };
const localPath = secretFilePath();
const canonicalPath = canonicalSecretPath();
const canonical = localPath === canonicalPath ? "" : readSecretFile(canonicalPath);
if (canonical) {
if (localPath !== canonicalPath && readSecretFile(localPath) !== canonical) {
writeSecretFile(localPath, canonical);
}
return { secret: canonical, source: "file" };
}
const legacy = readSecretFile(localPath) || legacyDataDirSecretPaths(env).map(readSecretFile).find(Boolean) || "";
const candidate = legacy || randomBytes(32).toString("hex");
const localSecret = writeSecretIfAbsent(localPath, candidate);
const secret = localPath === canonicalPath
? localSecret
: writeSecretIfAbsent(canonicalPath, localSecret);
if (localPath !== canonicalPath && localSecret !== secret) writeSecretFile(localPath, secret);
return { secret, source: legacy ? "file" : "generated" };
}
export function bearerHeaders(
baseUrl: string,
env: NodeJS.ProcessEnv = process.env,
): Record<string, string> {
const secret = resolveClientSecret(baseUrl, env);
return secret ? { Authorization: `Bearer ${secret}` } : {};
}