#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
import { resolveClientSecret } from "../secret-store.js";
const DEFAULT_URL = "http://localhost:3111";
const DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000;
const CALL_TIMEOUT_MS = 15_000;
const LOCAL_MODE_TTL_MS = 30_000;
function probeTimeoutMs(): number {
const raw = process.env["AGENTMEMORY_PROBE_TIMEOUT_MS"];
if (!raw) return DEFAULT_HEALTH_PROBE_TIMEOUT_MS;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_HEALTH_PROBE_TIMEOUT_MS;
}
export function isProxyRequired(): boolean {
const raw = process.env["AGENTMEMORY_FORCE_PROXY"];
return raw === "1" || raw === "true";
}
export interface ProxyHandle {
mode: "proxy";
baseUrl: string;
call: (path: string, init?: RequestInit) => Promise<unknown>;
}
export class ProxyCallError extends Error {
status: number;
body: unknown;
constructor(message: string, status: number, body: unknown) {
super(message);
this.name = "ProxyCallError";
this.status = status;
this.body = body;
}
}
export interface LocalHandle {
mode: "local";
}
export type Handle = ProxyHandle | LocalHandle;
let cached: Handle | null = null;
let cachedUrl: string | null = null;
let cachedAt = 0;
let probeInFlight: { url: string; forceProxy: boolean; promise: Promise<Handle> } | null = null;
// `${VAR}`-style placeholders ship in plugin/.mcp.json so MCP hosts that
// expand them (Claude Code, Cursor) substitute the user's shell value.
// Hosts that DON'T expand pass the literal string `"${AGENTMEMORY_URL}"`
// through to our subprocess — that string is truthy, defeats the `||`
// fallback, and would have us POST to `${AGENTMEMORY_URL}/agentmemory/...`
// (DNS failure). Strip any literal placeholder we see so the fallback
// engages instead.
export function resolveEnvOrEmpty(name: string): string {
const raw = process.env[name];
if (!raw) return "";
if (raw.startsWith("${") && raw.endsWith("}")) return "";
return raw;
}
function baseUrl(): string {
const value = resolveEnvOrEmpty("AGENTMEMORY_URL") || DEFAULT_URL;
try {
const parsed = new URL(value);
if (!["http:", "https:"].includes(parsed.protocol) || !parsed.hostname ||
parsed.username || parsed.password || /[?#\s]/.test(value)) {
throw new Error();
}
return value.replace(/\/+$/, "");
} catch {
throw new Error("AGENTMEMORY_URL must be an HTTP(S) URL without credentials, query, or fragment");
}
}
function authHeader(url: string): Record<string, string> {
const secret = resolveClientSecret(url);
return secret ? { authorization: `Bearer ${secret}` } : {};
}
export type LivezProbe = (
url: string,
timeoutMs: number,
headers: Record<string, string>,
) => Promise<{ ok: boolean; status?: number; statusText?: string }>;
const defaultLivezProbe: LivezProbe = async (url, timeoutMs, headers) => {
const res = await fetch(`${url}/agentmemory/livez`, {
method: "GET",
headers,
signal: AbortSignal.timeout(timeoutMs),
redirect: "error",
});
return { ok: res.ok, status: res.status, statusText: res.statusText };
};
let livezProbe: LivezProbe = defaultLivezProbe;
/**
* Override the livez probe. Intended for tests — production code should rely
* on the default fetch-based probe. Calling without an argument restores the
* default. Pair with {@link resetHandleForTests} so the cached handle is
* dropped before the next call.
*/
export function setLivezProbe(fn?: LivezProbe): void {
livezProbe = fn ?? defaultLivezProbe;
}
async function probe(url: string): Promise<boolean> {
const timeout = probeTimeoutMs();
try {
const res = await livezProbe(url, timeout, authHeader(url));
if (!res.ok) {
process.stderr.write(
`[@agentmemory/mcp] livez probe ${url}/agentmemory/livez -> ${res.status ?? "?"} ${res.statusText ?? ""}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe)\n`,
);
}
return res.ok;
} catch (err) {
process.stderr.write(
`[@agentmemory/mcp] livez probe ${url}/agentmemory/livez failed in ${timeout}ms: ${err instanceof Error ? err.message : String(err)}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe, or raise AGENTMEMORY_PROBE_TIMEOUT_MS)\n`,
);
return false;
}
}
export function invalidateHandle(): void {
cached = null;
cachedUrl = null;
cachedAt = 0;
}
export async function resolveHandle(): Promise<Handle> {
const now = Date.now();
const url = baseUrl();
if (cached && (cachedUrl !== url || (cached.mode === "local" && isProxyRequired()))) invalidateHandle();
if (cached) {
if (cached.mode === "local" && now - cachedAt >= LOCAL_MODE_TTL_MS) {
cached = null;
cachedAt = 0;
} else {
return cached;
}
}
const skipProbe = isProxyRequired();
if (probeInFlight?.url === url && probeInFlight.forceProxy === skipProbe) return probeInFlight.promise;
const pending = (async () => {
const up = skipProbe ? true : await probe(url);
if (baseUrl() !== url || isProxyRequired() !== skipProbe) return resolveHandle();
if (skipProbe) {
process.stderr.write(
`[@agentmemory/mcp] AGENTMEMORY_FORCE_PROXY set; skipping livez probe and trusting ${url}\n`,
);
}
if (up) {
const handle: ProxyHandle = {
mode: "proxy",
baseUrl: url,
call: async (path, init) => {
if (baseUrl() !== url) {
throw new Error("AgentMemory endpoint changed; resolve a new proxy handle before retrying.");
}
const res = await fetch(`${url}${path}`, {
...init,
headers: {
"content-type": "application/json",
...authHeader(url),
...(init?.headers as Record<string, string> | undefined),
},
signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
redirect: "error",
});
if (!res.ok) {
const errText = await res.text().catch(() => "");
let errBody: unknown = undefined;
if (errText) {
try {
errBody = JSON.parse(errText);
} catch {
errBody = undefined;
}
}
throw new ProxyCallError(
`${init?.method || "GET"} ${path} -> ${res.status} ${res.statusText}`,
res.status,
errBody,
);
}
const text = await res.text();
return text ? JSON.parse(text) : null;
},
};
cached = handle;
cachedUrl = url;
cachedAt = Date.now();
return handle;
}
const local: LocalHandle = { mode: "local" };
cached = local;
cachedUrl = url;
cachedAt = Date.now();
return local;
})();
probeInFlight = { url, forceProxy: skipProbe, promise: pending };
try {
return await pending;
} finally {
if (probeInFlight?.promise === pending) probeInFlight = null;
}
}
export function resetHandleForTests(): void {
cached = null;
cachedUrl = null;
cachedAt = 0;
probeInFlight = null;
livezProbe = defaultLivezProbe;
}