Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import net from 'net';
import { logger } from '../../utils/logger.js';
import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js';
import { USER_SETTINGS_PATH } from '../../shared/paths.js';
import { isConnectionRefusedError, isUnbindablePortError } from '../../shared/connection-errors.js';
import { localApiTokenHeadersFor } from '../../shared/local-api-token.js';
function getWorkerHost(): string {
return SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_WORKER_HOST;
}
// Bracket IPv6 literals so a `CLAUDE_MEM_WORKER_HOST` of `::1` yields a valid
// `http://[::1]:port` URL instead of the malformed `http://::1:port`.
function formatHostForUrl(host: string): string {
if (host.startsWith('[') && host.endsWith(']')) return host;
return host.includes(':') ? `[${host}]` : host;
}
// Probes against a ghost listener (plan-15 #3603) can connect — the kernel
// completes handshakes on the inherited socket — but never receive a response,
// because no application is reading. An unbounded fetch would hang the probe
// forever, so every HTTP probe is aborted after this budget. 5s is above a
// healthy worker's sub-100ms response and below every caller's retry budget.
const HEALTH_PROBE_TIMEOUT_MS = 5_000;
function localWorkerOrigin(port: number): string {
return `http://${formatHostForUrl(getWorkerHost())}:${port}`;
}
/**
* The local API token (#5141) as headers for the probe this process makes. Read from
* settings.json alone, like the worker reads it, and decided by the one shared rule
* (localApiTokenHeadersFor): a host naming another machine never gets it, and neither
* does an explicit CLAUDE_MEM_WORKER_URL, unless the user names that host in
* CLAUDE_MEM_LOCAL_API_TOKEN_REMOTE_HOST (#6390).
*/
function localWorkerAuthHeaders(port: number, targetOrigin?: string): Record<string, string> {
const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH, false, { readOnly: true });
const localOrigin = localWorkerOrigin(port);
return localApiTokenHeadersFor({
token: settings.CLAUDE_MEM_LOCAL_API_TOKEN,
workerOrigin: targetOrigin ?? localOrigin,
// An explicit destination is somebody's configured CLAUDE_MEM_WORKER_URL, not this
// machine's worker: an empty local origin says so, so a loopback URL there (an SSH
// forward) never receives the token, while the https remote branch still can.
localOrigin: targetOrigin ? '' : localOrigin,
configuredHost: getWorkerHost(),
remoteTokenHost: settings.CLAUDE_MEM_LOCAL_API_TOKEN_REMOTE_HOST,
});
}
async function httpRequestToWorker(
workerOrigin: string,
endpointPath: string,
method: string = 'GET',
timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS,
headers: Record<string, string> = {},
): Promise<{ ok: boolean; statusCode: number; body: string }> {
const response = await fetch(`${workerOrigin}${endpointPath}`, {
method,
...(Object.keys(headers).length > 0 ? { headers } : {}),
signal: AbortSignal.timeout(Math.max(1, timeoutMs)),
});
let body = '';
try {
body = await response.text();
} catch {
// Body unavailable — health/readiness checks only need .ok
}
return { ok: response.ok, statusCode: response.status, body };
}
export async function isPortInUse(port: number, timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS): Promise<boolean> {
// One budget for the whole call: the Windows fetch and the bind probe after
// it share it, so a hung fetch cannot push the bind past the caller's wait.
const deadline = Date.now() + timeoutMs;
if (process.platform === 'win32') {
// Fast path: HTTP health check. A live claude-mem worker responds to
// /api/health, so this is the cheapest non-disruptive probe for the
// common case (worker is running and healthy).
//
// Bounded like every other probe (HEALTH_PROBE_TIMEOUT_MS): a ghost
// listener — the dead worker's inherited socket, held open by its chroma
// sidecar chain (plan-15 #3603) — completes the TCP handshake and then
// never answers. Unbounded, this fetch would hang forever, and with it
// ensureWorkerStarted(), which calls this BEFORE it can reach the reclaim:
// the very bug the reclaim exists to fix would instead wedge every
// launcher. On timeout the flow falls through to the socket probe below,
// which still reports a bound port as in use.
try {
const response = await fetch(`http://${formatHostForUrl(getWorkerHost())}:${port}/api/health`, {
signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),
});
if (response.ok) return true;
// Non-ok response: port is reachable but the worker is unhealthy.
// Fall through to the net.createServer check below so we still report
// the port as in-use rather than falsely claiming it is free.
logger.debug('SYSTEM', 'Windows health check returned non-ok; falling through to socket probe', {
port,
status: response.status,
});
} catch (error) {
// fetch threw (ECONNREFUSED, timeout, etc.): the port may still be in
// use by a non-HTTP process (zombie worker, foreign service, etc.).
// Fall through to the net.createServer probe — only a definitive bind
// attempt can tell whether the port is truly free.
if (error instanceof Error) {
logger.debug('SYSTEM', 'Windows health check threw; falling through to socket probe', {
port,
message: error.message,
});
} else {
logger.debug('SYSTEM', 'Windows health check threw; falling through to socket probe', {
port,
error: String(error),
});
}
}
// Fall through: the HTTP probe was inconclusive. Use the POSIX
// net.createServer() approach to definitively check port occupancy.
}
// An inconclusive bind counts as in use: waitForPortFree, the restart
// handoff and the daemon duplicate gate must never treat an unknown port
// state as free and start another worker onto it. An unbindable port is not
// in use: nothing holds it, and a worker that tries to listen there fails
// with that errno, which the daemon reports as a boot failure — never as a
// duplicate that exits 0.
const occupancy = await classifyPortOccupancy(port, Math.max(1, deadline - Date.now()));
return occupancy === 'occupied' || occupancy === 'indeterminate';
}
export type PortOccupancy = 'free' | 'occupied' | 'unbindable' | 'indeterminate';
export interface PortBindProbe {
occupancy: PortOccupancy;
/** The bind errno, set when `occupancy` is 'unbindable'. */
bindErrorCode?: string;
}
/**
* The one bind probe behind every port-occupancy decision, bounded by
* `timeoutMs`. 'free' only when a listener actually bound and closed cleanly,
* 'occupied' only on EADDRINUSE, 'unbindable' on EACCES / EADDRNOTAVAIL
* (isUnbindablePortError, with the errno); anything else (another bind error,
* a close failure, no answer before the deadline) is 'indeterminate'. The
* probe listener is always closed, even when it binds after the deadline
* settled.
*/
export async function classifyPortOccupancy(port: number, timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS): Promise<PortOccupancy> {
return (await probePortBind(port, timeoutMs)).occupancy;
}
/** classifyPortOccupancy with the bind errno, for launchers that report it. */
export function probePortBind(port: number, timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS): Promise<PortBindProbe> {
if (timeoutMs <= 0) return Promise.resolve({ occupancy: 'indeterminate' });
return new Promise((resolve) => {
let settled = false;
let listening = false;
let closeRequested = false;
let server: net.Server;
try {
server = net.createServer();
} catch {
resolve({ occupancy: 'indeterminate' });
return;
}
const closeServer = (callback?: (error?: Error) => void): void => {
if (closeRequested) {
callback?.();
return;
}
closeRequested = true;
try {
server.close(callback);
} catch (error: unknown) {
callback?.(error instanceof Error ? error : new Error(String(error)));
}
};
const timer = setTimeout(() => {
if (listening) {
closeServer();
} else {
try { server.close(); } catch { /* the listening handler retries cleanup */ }
}
settle({ occupancy: 'indeterminate' });
}, timeoutMs);
const settle = (result: PortBindProbe): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(result);
};
server.once('error', (err: NodeJS.ErrnoException) => {
if (listening) {
closeServer();
} else {
try { server.close(); } catch { /* the bind did not start */ }
}
if (err.code === 'EADDRINUSE') settle({ occupancy: 'occupied' });
else if (isUnbindablePortError(err)) settle({ occupancy: 'unbindable', bindErrorCode: err.code });
else settle({ occupancy: 'indeterminate' });
});
server.once('listening', () => {
listening = true;
if (settled) {
closeServer();
return;
}
try {
closeServer((error?: Error) => settle({ occupancy: error ? 'indeterminate' : 'free' }));
} catch {
settle({ occupancy: 'indeterminate' });
}
});
try {
server.listen(port, getWorkerHost());
} catch {
try { server.close(); } catch { /* the bind did not start */ }
settle({ occupancy: 'indeterminate' });
}
});
}
async function pollEndpointUntilOk(
workerOrigin: string,
endpointPath: string,
timeoutMs: number,
retryLogMessage: string,
headers: Record<string, string> = {},
): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const remainingMs = deadline - Date.now();
const result = await httpRequestToWorker(
workerOrigin,
endpointPath,
'GET',
Math.min(HEALTH_PROBE_TIMEOUT_MS, remainingMs),
headers,
);
if (result.ok) return true;
} catch (error) {
if (error instanceof Error) {
logger.debug('SYSTEM', retryLogMessage, {}, error);
} else {
logger.debug('SYSTEM', retryLogMessage, { error: String(error) });
}
}
const retryDelayMs = Math.min(500, deadline - Date.now());
if (retryDelayMs > 0) {
await new Promise(r => setTimeout(r, retryDelayMs));
}
}
return false;
}
/**
* `explicitWorkerOrigin` is the validated CLAUDE_MEM_WORKER_URL, for a caller
* reporting on a worker it does not run. Without it these probe host and port,
* which is what the daemon's duplicate gate and the port reclaim must ask about.
*/
export function waitForHealth(port: number, timeoutMs: number = 30000, explicitWorkerOrigin?: string): Promise<boolean> {
// /api/health is open in local API token mode (#5141): no token needed.
return pollEndpointUntilOk(explicitWorkerOrigin ?? localWorkerOrigin(port), '/api/health', timeoutMs, 'Service not ready yet, will retry');
}
export function waitForReadiness(port: number, timeoutMs: number = 30000, explicitWorkerOrigin?: string): Promise<boolean> {
// /api/readiness takes the local API token (#5141). An explicit origin is the worker the
// person configured in CLAUDE_MEM_WORKER_URL, so it is the one destination the shared
// rule (#6390) can authorize for a remote worker; without this, a ready remote worker
// answers /api/health and then 401s on every readiness poll, so callers report warming.
if (explicitWorkerOrigin) {
return pollEndpointUntilOk(explicitWorkerOrigin, '/api/readiness', timeoutMs, 'Worker not ready yet, will retry', localWorkerAuthHeaders(port, explicitWorkerOrigin));
}
return pollEndpointUntilOk(localWorkerOrigin(port), '/api/readiness', timeoutMs, 'Worker not ready yet, will retry', localWorkerAuthHeaders(port));
}
export async function waitForPortFree(port: number, timeoutMs: number = 10000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const remainingMs = deadline - Date.now();
if (!(await isPortInUse(port, Math.min(HEALTH_PROBE_TIMEOUT_MS, remainingMs)))) return true;
const retryDelayMs = Math.min(500, deadline - Date.now());
if (retryDelayMs > 0) {
await new Promise(r => setTimeout(r, retryDelayMs));
}
}
return false;
}
export async function httpShutdown(port: number, reason: 'stop' | 'restart' = 'stop'): Promise<boolean> {
try {
// The CLI restart path stops the worker through this same endpoint; the
// reason tag lets the worker report shutdown_reason: 'restart' on its
// worker_stopped telemetry instead of a generic 'stop'.
const endpointPath = reason === 'restart' ? '/api/admin/shutdown?reason=restart' : '/api/admin/shutdown';
const result = await httpRequestToWorker(localWorkerOrigin(port), endpointPath, 'POST', HEALTH_PROBE_TIMEOUT_MS, localWorkerAuthHeaders(port));
if (!result.ok) {
logger.warn('SYSTEM', 'Shutdown request returned error', { status: result.statusCode });
return false;
}
return true;
} catch (error) {
if (error instanceof Error && isConnectionRefusedError(error)) {
logger.debug('SYSTEM', 'Worker already stopped', {}, error);
return false;
}
logger.error('SYSTEM', 'Shutdown request failed unexpectedly', {}, error as Error);
return false;
}
}
export async function getRunningWorkerVersion(
port: number,
timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS,
): Promise<string | null> {
try {
const result = await httpRequestToWorker(localWorkerOrigin(port), '/api/health', 'GET', timeoutMs);
if (!result.ok) return null;
const data = JSON.parse(result.body) as { version: string };
return data.version;
} catch {
logger.debug('SYSTEM', 'Could not fetch worker version', {});
return null;
}
}
export interface VersionCheckResult {
matches: boolean;
pluginVersion: string;
workerVersion: string | null;
}
/**
* Compare the live worker's self-reported version against expectedVersion —
* the version of the script the caller's resolveWorkerScript() oracle would
* spawn. The caller supplies it so detection and respawn can never consult
* different oracles (the 2026-07-22 restart storm). Either side unknown →
* matches, since a recycle could not change the outcome deterministically.
*/
export async function checkVersionMatch(
port: number,
expectedVersion: string | null,
timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS,
): Promise<VersionCheckResult> {
const pluginVersion = expectedVersion ?? 'unknown';
// A caller spending a hook budget passes what is left of it (#3434). An
// expired probe reads as "version unknown", which already means no recycle.
const workerVersion = await getRunningWorkerVersion(port, timeoutMs);
if (!workerVersion || pluginVersion === 'unknown') {
return { matches: true, pluginVersion, workerVersion };
}
return { matches: pluginVersion === workerVersion, pluginVersion, workerVersion };
}