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
/**
* Framework-agnostic core of the OpenCode integration.
*
* Everything that decides WHAT gets remembered lives here: worker requests,
* the OpenCode-session -> content-session mapping, memory-context caching and
* the search client. The host-specific adapters (`index.ts`) translate their
* own hook shapes into calls on a `ClaudeMemCore`, so the v1 and the v2 plugin
* contracts cannot drift apart.
*
* Dependency-free (no worker-only imports) so it stays bundle-safe.
*/
import { join } from "node:path";
import { SettingsDefaultsManager } from "../../shared/SettingsDefaultsManager.js";
import { formatWorkerMcpResponse } from '../../servers/mcp-text-format.js';
import { parseSearchResponse } from "./contract.js";
import { normalizePlatformSource } from "../../shared/platform-source.js";
import { isConnectionRefusedError } from "../../shared/connection-errors.js";
import { formatHostForUrl, normalizeWorkerBaseUrl } from "../../shared/worker-url.js";
import { localApiTokenHeadersFor } from "../../shared/local-api-token.js";
import { stripMemoryTags } from "../../utils/tag-stripping.js";
import { deliverLiveObserverHandoff } from "../../shared/live-observer-handoff.js";
import {
SEMANTIC_CONTEXT_MAX_LIMIT,
SEMANTIC_CONTEXT_MIN_QUERY_CHARS,
} from "../../shared/semantic-context.js";
export type SemanticInjectionSettings = {
enabled: boolean;
limit: number;
format: string;
};
export function semanticInjectionSettings(raw: Record<string, unknown>): SemanticInjectionSettings {
const enabled = String(raw.CLAUDE_MEM_SEMANTIC_INJECT ?? "").trim().toLowerCase() === "true";
const parsedLimit = Number.parseInt(String(raw.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT ?? ""), 10);
const limit = Number.isFinite(parsedLimit)
? Math.min(Math.max(parsedLimit, 1), SEMANTIC_CONTEXT_MAX_LIMIT)
: 5;
const rawFormat = typeof raw.CLAUDE_MEM_SEMANTIC_INJECT_FORMAT === "string"
? raw.CLAUDE_MEM_SEMANTIC_INJECT_FORMAT.trim()
: "";
return {
enabled,
limit,
format: rawFormat || "narrative",
};
}
export interface OpenCodeClient {
session?: {
messages?(options: {
path: { id: string };
query?: { directory?: string };
}): Promise<{ data?: OpenCodeMessageSnapshot[] }>;
};
}
export interface OpenCodeMessageSnapshot {
info?: {
role?: string;
summary?: boolean;
time?: { completed?: number };
};
parts?: Array<{ type: string; text?: string; ignored?: boolean }>;
}
/** The bits of the host context claude-mem actually reads. */
export interface CoreContext {
directory: string;
client?: OpenCodeClient;
}
function resolveWorkerBaseUrl(): string {
const settingsPath = join(
SettingsDefaultsManager.get("CLAUDE_MEM_DATA_DIR"),
"settings.json",
);
const settings = SettingsDefaultsManager.loadFromFile(settingsPath);
// An explicit URL wins, as it does for every other client: a remote worker is reached at
// its https address, and deriving host and port would silently downgrade that to http
// and send the local API token in the clear (#6390).
return normalizeWorkerBaseUrl(settings.CLAUDE_MEM_WORKER_URL)
|| `http://${formatHostForUrl(settings.CLAUDE_MEM_WORKER_HOST)}:${settings.CLAUDE_MEM_WORKER_PORT}`;
}
const WORKER_BASE_URL = resolveWorkerBaseUrl();
const MAX_TOOL_RESPONSE_LENGTH = 1000;
// SessionStart context is source-scoped by default: the worker filters
// observations to the platform that recorded them, so a session started by one
// harness only sees that harness's memory. The Claude Code hook path honors
// CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES to opt out of that (#4251).
// The OpenCode plugin must honor the same switch, or a user who moves between
// harnesses sees their earlier memories disappear, and the setting silently
// does nothing for OpenCode.
//
// Read per request, not at module load: the worker URL is frozen at import,
// but this decides which memories a session can see, and the file is the
// user's own switch. A settings change should not need an OpenCode restart.
function includeAllSources(): boolean {
const settingsPath = join(
SettingsDefaultsManager.get("CLAUDE_MEM_DATA_DIR"),
"settings.json",
);
// readOnly: the plugin only reads the switch. loadFromFile would otherwise
// rewrite the settings file to migrate defaults, and the plugin must not
// mutate user settings as a side effect of rendering context.
const settings = SettingsDefaultsManager.loadFromFile(settingsPath, true, { readOnly: true });
return settings.CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES === "true";
}
// Identifies these POSTs as coming from OpenCode. Without it the worker
// attributes OpenCode sessions to its default platform source ("claude"), so
// viewer badges and source-scoped session lookups are wrong (#3678).
const PLATFORM_SOURCE = "opencode";
// Built-in OpenCode names differ from the shared file-evidence vocabulary.
// The worker's shell filter reads commands from `Bash`, so a lowercase `bash`
// left CLAUDE_MEM_SKIP_BASH_PATTERNS with nothing to match (#5666).
const CAPTURE_TOOL_NAMES = new Map([
["read", "Read"],
["write", "Write"],
["edit", "Edit"],
["bash", "Bash"],
]);
// Local API token mode (#5141): the worker refuses a request without the token. Read once, like the
// worker URL, and only for the worker this plugin talks to: another host is not ours to hand the
// token to. The one exception is the remote host the user names in
// CLAUDE_MEM_LOCAL_API_TOKEN_REMOTE_HOST (#6390), which must equal CLAUDE_MEM_WORKER_HOST exactly.
// The token comes from settings.json alone, as the worker reads it, so the environment cannot
// change what is sent.
function localApiHeaders(): Record<string, string> {
const settingsPath = join(SettingsDefaultsManager.get("CLAUDE_MEM_DATA_DIR"), "settings.json");
const settings = SettingsDefaultsManager.loadFromFile(settingsPath, false, { readOnly: true });
const host = settings.CLAUDE_MEM_WORKER_HOST;
return localApiTokenHeadersFor({
token: settings.CLAUDE_MEM_LOCAL_API_TOKEN,
workerOrigin: WORKER_BASE_URL,
localOrigin: `http://${formatHostForUrl(host)}:${settings.CLAUDE_MEM_WORKER_PORT}`,
configuredHost: host,
remoteTokenHost: settings.CLAUDE_MEM_LOCAL_API_TOKEN_REMOTE_HOST,
});
}
const JSON_HEADERS: Record<string, string> = { "Content-Type": "application/json", ...localApiHeaders() };
// Every worker request is bounded, so a hung worker can neither hold a hook
// open nor pile up pending requests inside OpenCode's process (plan-23 step 2).
const WORKER_REQUEST_TIMEOUT_MS = 5_000;
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
/** One POST attempt, with no replay after a refused connection. */
async function postToWorker(fetchImpl: typeof fetch, path: string, payload: string): Promise<void> {
try {
const response = await fetchImpl(`${WORKER_BASE_URL}${path}`, {
method: "POST",
headers: JSON_HEADERS,
body: payload,
signal: AbortSignal.timeout(WORKER_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
console.warn(`[claude-mem] Worker POST ${path} returned ${response.status}`);
}
await response.body?.cancel();
} catch (error: unknown) {
if (!isConnectionRefusedError(error)) {
console.warn(`[claude-mem] Worker POST ${path} failed: ${errorMessage(error)}`);
}
}
}
async function workerPost(path: string, body: Record<string, unknown>): Promise<void> {
const payload = JSON.stringify({
...body,
platformSource: normalizePlatformSource(PLATFORM_SOURCE),
});
const fetchImpl = fetch;
if (path === '/api/sessions/observations' || path === '/api/sessions/summarize') {
try {
await deliverLiveObserverHandoff(timeoutMs => fetchImpl(`${WORKER_BASE_URL}${path}`, {
method: 'POST', headers: JSON_HEADERS, body: payload,
signal: AbortSignal.timeout(timeoutMs),
}));
} catch (error) {
// Ambiguous or refused inference inputs are never retained for replay.
if (!isConnectionRefusedError(error)) {
console.warn(`[claude-mem] Live observer handoff ${path} skipped: ${errorMessage(error)}`);
}
}
return;
}
await postToWorker(fetchImpl, path, payload);
}
async function workerGetText(path: string): Promise<string | null> {
try {
const response = await fetch(`${WORKER_BASE_URL}${path}`, {
headers: JSON_HEADERS,
signal: AbortSignal.timeout(WORKER_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
console.warn(`[claude-mem] Worker GET ${path} returned ${response.status}`);
await response.body?.cancel();
return null;
}
return await response.text();
} catch (error: unknown) {
if (!isConnectionRefusedError(error)) {
console.warn(`[claude-mem] Worker GET ${path} failed: ${errorMessage(error)}`);
}
return null;
}
}
export async function fetchSemanticForPrompt(
promptText: string,
cwd: string,
settings: SemanticInjectionSettings,
platformSource: string,
): Promise<string> {
const query = stripMemoryTags(promptText).trim();
if (!settings.enabled || query.length < SEMANTIC_CONTEXT_MIN_QUERY_CHARS) {
return "";
}
try {
const response = await fetch(`${WORKER_BASE_URL}/api/context/semantic`, {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify({
q: query,
cwd,
limit: settings.limit,
format: settings.format,
platformSource: normalizePlatformSource(platformSource),
}),
signal: AbortSignal.timeout(WORKER_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
await response.body?.cancel();
return "";
}
const data = (await response.json()) as { context?: unknown } | null;
return typeof data?.context === "string" ? data.context : "";
} catch {
return "";
}
}
const MAX_SESSION_MAP_ENTRIES = 1000;
// Memory context per checkout and OpenCode session: fetched on the session's
// first system prompt build and reused for later turns. V1 also calls system
// transform without a session ID; that shared empty ID must never lend one
// checkout's memory to another. Compaction clears only its own checkout.
interface CachedMemoryContext {
request: Promise<string | null>;
/** When the fetch came back with nothing; set only for a failed fetch. */
failedAt?: number;
}
const contextByOpenCodeSessionId = new Map<string, CachedMemoryContext>();
interface SemanticCacheEntry {
prompt: string;
request: Promise<string>;
failedAt?: number;
}
const semanticByOpenCodeSessionId = new Map<string, SemanticCacheEntry>();
// A failed context fetch is remembered this long before the next build tries
// again: OpenCode builds a system prompt for every request, and a hung worker
// would otherwise add the full request timeout to each one (plan-17 contract).
const FAILED_CONTEXT_RETRY_MS = 60_000;
/**
* OpenCode retains its native ID when a session resumes. Use it directly,
* scoped by platformSource at the worker, so a restart or cache eviction cannot
* split later prompts and tools into a fresh memory session. Session init
* means "a user prompt happened", not "ensure a session
* row exists": observations and summarize create their own rows. Posting init
* without a prompt manufactures a "[media prompt]" at prompt #1 and attributes
* a preceding tool observation to it (#3803).
*/
function resolveContentSessionId(openCodeSessionId: string): string {
return openCodeSessionId;
}
/**
* Records a real user prompt with the worker. Every user prompt posts init,
* matching the Claude Code path; the worker de-duplicates identical prompts
* within its time window (#3803).
*
* The body carries the checkout, not a project key. `ctx.project?.name` is not
* the repository (it resolves to "opencode" for every project), and resolving
* the key here would mean a second copy of the identity rules (markers,
* environments, git-remote slugs, worktree and submodule composites) inside
* OpenCode's process. The worker keys the session with the same shared
* resolver it applies to this plugin's observations, so init and capture
* always agree.
*/
async function initializeSessionForUserPrompt(
openCodeSessionId: string,
cwd: string,
prompt: string,
observerModel?: string,
observerProvider?: string,
): Promise<void> {
// This helper is entered only from live v1/v2 user-prompt hooks.
const telemetryPromptEpochMs = Date.now();
const contentSessionId = resolveContentSessionId(openCodeSessionId);
await workerPost("/api/sessions/init", {
contentSessionId,
prompt,
cwd,
platform_source: PLATFORM_SOURCE,
telemetryPromptEpochMs,
// The host's chosen observer model rides with this live prompt only. It is
// not persisted, cached, or replayed: the worker reads it for this session.
...(observerModel ? { observerModel } : {}),
// The provider id rides with the prompt only; no key, no persistence. It
// selects a map entry in the session's endpoints, never a model name.
...(observerProvider ? { observerProvider } : {}),
});
}
function truncate(text: string): string {
// Strip tagged private sections before the length cap, not after: a cut
// through a block would drop its closing tag and the worker-side stripper
// then keeps the (now unbalanced) remainder verbatim.
const stripped = stripMemoryTags(text);
return stripped.length > MAX_TOOL_RESPONSE_LENGTH
? stripped.slice(0, MAX_TOOL_RESPONSE_LENGTH)
: stripped;
}
/**
* The text of the session's latest completed assistant reply, for summarize's
* last_assistant_message. OpenCode fires chat.message for the user's message,
* so the reply is read from OpenCode's own message list when the session idles
* or compacts. Empty when the client offers no message list or it fails.
*/
async function latestAssistantText(
client: unknown,
openCodeSessionId: string,
directory: string,
): Promise<string> {
const session = (client as OpenCodeClient | undefined)?.session;
if (typeof session?.messages !== "function") return "";
try {
const { data } = await session.messages({ path: { id: openCodeSessionId }, query: { directory } });
let latest: { completed: number; text: string } | null = null;
for (const message of data ?? []) {
const completed = message.info?.time?.completed;
if (message.info?.role !== "assistant" || message.info.summary === true || typeof completed !== "number") continue;
const text = (message.parts ?? [])
.filter((part) => part.type === "text" && part.ignored !== true && typeof part.text === "string")
.map((part) => part.text as string)
.join("\n")
.trim();
if (text && (!latest || completed >= latest.completed)) latest = { completed, text };
}
return latest?.text ?? "";
} catch (error: unknown) {
console.warn(`[claude-mem] OpenCode message list failed for ${openCodeSessionId}: ${errorMessage(error)}`);
return "";
}
}
export interface ClaudeMemCore {
/**
* Capture every tool execution as an observation. This is the primary
* capture path (#2419). `args` are the tool arguments; OpenCode passes them
* on the hook input, never on the output (#3678).
*/
captureTool(input: {
tool: string;
/** Actual host name when an adapter changes more than its case. */
nativeToolName?: string;
sessionID: string;
toolUseId?: string;
args?: Record<string, unknown>;
output: string;
failed?: boolean;
}): Promise<void>;
/** Capture a real user prompt with session init. */
captureUserPrompt(sessionID: string, promptText: string, observerModel?: string, observerProvider?: string): Promise<void>;
/** Capture an assistant message as an observation. */
captureAssistantMessage(sessionID: string, messageText: string): Promise<void>;
/**
* Summarize the session (compaction and idle both funnel here). The cached
* memory context is kept: only compaction drops it, through
* `forgetMemoryContext`. `lastAssistantMessage` is the reply when the host
* reports it; otherwise it is read back from the client's message list.
*/
captureSummary(sessionID: string, options?: { lastAssistantMessage?: string }): Promise<void>;
/** Drop the cached memory context so the next system prompt fetches it again (compaction). */
forgetMemoryContext(sessionID: string): void;
/** Forget everything about a session the user deleted. */
forgetSession(sessionID: string): void;
/**
* Memory context for a session's system prompt, cached once per session and
* re-fetched after a failure window. Returns null/empty when there is none.
*/
memoryContext(sessionID: string): Promise<string | null>;
/** Prime per-prompt semantic recall for the current turn, or clear stale cache when skipped. */
primeSemanticContext(sessionID: string, promptText: string): void;
/** Read the cached semantic block for the current turn without issuing a new request. */
semanticContext(sessionID: string): Promise<string>;
/** Drop the cached semantic block for this session. */
forgetSemanticContext(sessionID: string): void;
/** The `claude_mem_search` tool body. */
search(query: string): Promise<string>;
timeline(anchor: number): Promise<string>;
getObservations(ids: number[]): Promise<string>;
}
export function createCore(ctx: CoreContext): ClaudeMemCore {
const contextKeyFor = (sessionID: string): string => JSON.stringify([ctx.directory, sessionID]);
function memoryContextFor(openCodeSessionId: string, cwd: string): Promise<string | null> {
const key = contextKeyFor(openCodeSessionId);
const cached = contextByOpenCodeSessionId.get(key);
if (cached && (cached.failedAt === undefined || Date.now() - cached.failedAt < FAILED_CONTEXT_RETRY_MS)) {
return cached.request;
}
contextByOpenCodeSessionId.delete(key);
while (contextByOpenCodeSessionId.size >= MAX_SESSION_MAP_ENTRIES) {
const oldestKey = contextByOpenCodeSessionId.keys().next().value;
if (oldestKey === undefined) break;
contextByOpenCodeSessionId.delete(oldestKey);
}
// The worker resolves the project keys from the checkout, as it does for init.
// platformSource scopes the injected context to this harness's own
// observations; omitting it lets the worker return every source, which is
// what CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES asks for.
const platformSourceParam = includeAllSources() ? "" : `&platformSource=${PLATFORM_SOURCE}`;
const entry: CachedMemoryContext = {
request: workerGetText(
`/api/context/inject?cwd=${encodeURIComponent(cwd)}${platformSourceParam}`,
),
};
contextByOpenCodeSessionId.set(key, entry);
void entry.request.then((context) => {
if (!context) entry.failedAt = Date.now();
});
return entry.request;
}
async function captureSummary(
sessionID: string,
options: { lastAssistantMessage?: string } = {},
): Promise<void> {
const contentSessionId = resolveContentSessionId(sessionID);
await workerPost("/api/sessions/summarize", {
contentSessionId,
last_assistant_message:
options.lastAssistantMessage ?? await latestAssistantText(ctx.client, sessionID, ctx.directory),
// The worker skips an excluded checkout; the plugin cannot check it.
cwd: ctx.directory,
platform_source: PLATFORM_SOURCE,
});
}
return {
async captureTool({ tool, nativeToolName, sessionID, toolUseId, args, output, failed }) {
const telemetryToolEpochMs = Date.now();
const contentSessionId = resolveContentSessionId(sessionID);
// apply_patch carries its patch as `patchText`, and the worker's file
// evidence reads `patch`. Renamed rather than copied, so the observer
// is not sent the whole patch twice.
let toolInput: Record<string, unknown> = args || {};
if (tool === "apply_patch" && typeof toolInput.patchText === "string") {
const { patchText, ...otherArgs } = toolInput;
toolInput = { ...otherArgs, patch: patchText };
}
await workerPost("/api/sessions/observations", {
contentSessionId,
tool_name: CAPTURE_TOOL_NAMES.get(tool) ?? tool,
...(nativeToolName ? { native_tool_name: nativeToolName } : {}),
// Reading output.args instead shipped an empty tool_input for every
// observation, and the compressor dismissed them all — the "loads but
// captures nothing" symptom of #3678.
tool_input: toolInput,
tool_response: failed
? { is_error: true, error: truncate(output || "") }
: truncate(output || ""),
cwd: ctx.directory,
platform_source: PLATFORM_SOURCE,
telemetryToolEpochMs,
...(toolUseId ? { tool_use_id: toolUseId } : {}),
});
},
async captureUserPrompt(sessionID, promptText, observerModel, observerProvider) {
await initializeSessionForUserPrompt(sessionID, ctx.directory, promptText, observerModel, observerProvider);
},
async captureAssistantMessage(sessionID, messageText) {
const contentSessionId = resolveContentSessionId(sessionID);
if (!messageText) return;
await workerPost("/api/sessions/observations", {
contentSessionId,
tool_name: "assistant_message",
tool_input: {},
tool_response: truncate(messageText),
cwd: ctx.directory,
platform_source: PLATFORM_SOURCE,
});
},
captureSummary,
forgetMemoryContext(sessionID) {
contextByOpenCodeSessionId.delete(contextKeyFor(sessionID));
semanticByOpenCodeSessionId.delete(contextKeyFor(sessionID));
},
forgetSession(sessionID) {
contextByOpenCodeSessionId.delete(contextKeyFor(sessionID));
semanticByOpenCodeSessionId.delete(contextKeyFor(sessionID));
},
memoryContext(sessionID) {
return memoryContextFor(sessionID, ctx.directory);
},
primeSemanticContext(sessionID, promptText) {
const key = contextKeyFor(sessionID);
const settingsPath = join(SettingsDefaultsManager.get("CLAUDE_MEM_DATA_DIR"), "settings.json");
const rawSettings = SettingsDefaultsManager.loadFromFile(settingsPath, true, { readOnly: true });
const parsed = semanticInjectionSettings(rawSettings as unknown as Record<string, unknown>);
const query = stripMemoryTags(promptText).trim();
if (!parsed.enabled || query.length < SEMANTIC_CONTEXT_MIN_QUERY_CHARS) {
semanticByOpenCodeSessionId.delete(key);
return;
}
const cached = semanticByOpenCodeSessionId.get(key);
if (
cached &&
cached.prompt === query &&
cached.failedAt !== undefined &&
Date.now() - cached.failedAt < FAILED_CONTEXT_RETRY_MS
) {
return;
}
semanticByOpenCodeSessionId.delete(key);
while (semanticByOpenCodeSessionId.size >= MAX_SESSION_MAP_ENTRIES) {
const oldestKey = semanticByOpenCodeSessionId.keys().next().value;
if (oldestKey === undefined) break;
semanticByOpenCodeSessionId.delete(oldestKey);
}
const entry: SemanticCacheEntry = {
prompt: query,
request: fetchSemanticForPrompt(query, ctx.directory, parsed, PLATFORM_SOURCE),
};
semanticByOpenCodeSessionId.set(key, entry);
void entry.request.then((context) => {
if (!context) entry.failedAt = Date.now();
});
},
semanticContext(sessionID) {
return semanticByOpenCodeSessionId.get(contextKeyFor(sessionID))?.request ?? Promise.resolve("");
},
forgetSemanticContext(sessionID) {
semanticByOpenCodeSessionId.delete(contextKeyFor(sessionID));
},
async timeline(anchor) {
const text = await workerGetText(`/api/timeline?anchor=${encodeURIComponent(anchor)}`);
if (!text) return 'claude-mem worker is not running. Start it with: npx claude-mem start';
try { return formatWorkerMcpResponse('search', JSON.parse(text)).content[0].text; }
catch { return 'Failed to parse memory timeline.'; }
},
async getObservations(ids) {
if (!ids.length) return 'Select observation IDs from the search index and timeline first.';
try {
const response = await fetch(`${WORKER_BASE_URL}/api/observations/batch`, {
method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ ids }),
signal: AbortSignal.timeout(WORKER_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
await response.body?.cancel();
return 'The worker could not fetch the selected observations.';
}
return formatWorkerMcpResponse('observations', await response.json()).content[0].text;
} catch { return 'claude-mem worker is not running. Start it with: npx claude-mem start'; }
},
async search(query) {
if (!query) return "Please provide a search query.";
const text = await workerGetText(
`/api/search/observations?query=${encodeURIComponent(query)}&limit=10`,
);
if (!text) {
return "claude-mem worker is not running. Start it with: npx claude-mem start";
}
return parseSearchResponse(text, query);
},
};
}