#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat: v0.2.0 -- full memory upgrade with 12 hooks, MCP tools, skills, and intelligence
Rohit Ghumare45795b603319
diff --git a/package.json b/package.jsonindex bda8e0bc..1077696d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "agentmemory",- "version": "0.1.0",+ "version": "0.2.0","description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives","type": "module","main": "dist/index.js",diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonindex f320eb8d..64ff2263 100644--- a/plugin/.claude-plugin/plugin.json+++ b/plugin/.claude-plugin/plugin.json@@ -1,9 +1,10 @@{"name": "agentmemory",- "version": "0.1.0",- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions",+ "version": "0.2.0",+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 5 MCP tools, 4 skills, real-time viewer.","author": "Rohit Ghumare","license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory",- "hooks": "../hooks/hooks.json"+ "hooks": "../hooks/hooks.json",+ "skills": "../skills/"}diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.jsonindex a4a080c4..c515dfe4 100644--- a/plugin/hooks/hooks.json+++ b/plugin/hooks/hooks.json@@ -12,12 +12,55 @@"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/prompt-submit.mjs"}],+ "PreToolUse": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/pre-tool-use.mjs",+ "matcher": "Edit|Write|Read|Glob|Grep"+ }+ ],"PostToolUse": [{"type": "command","command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-use.mjs"}],+ "PostToolUseFailure": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-failure.mjs"+ }+ ],+ "PreCompact": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/pre-compact.mjs"+ }+ ],+ "SubagentStart": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/subagent-start.mjs"+ }+ ],+ "SubagentStop": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/subagent-stop.mjs"+ }+ ],+ "Notification": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/notification.mjs"+ }+ ],+ "TaskCompleted": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/task-completed.mjs"+ }+ ],"Stop": [{"type": "command",diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjsnew file mode 100755index 00000000..ad546082--- /dev/null+++ b/plugin/scripts/notification.mjs@@ -0,0 +1,45 @@+#!/usr/bin/env node+//#region src/hooks/notification.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ if (data.notification_type !== "permission_prompt") return;+ const sessionId = data.session_id || "unknown";+ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "notification",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ notification_type: data.notification_type,+ title: data.title,+ message: data.message+ }+ }),+ signal: AbortSignal.timeout(2e3)+ });+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=notification.mjs.map\ No newline at end of filediff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjsnew file mode 100755index 00000000..e062106b--- /dev/null+++ b/plugin/scripts/post-tool-failure.mjs@@ -0,0 +1,45 @@+#!/usr/bin/env node+//#region src/hooks/post-tool-failure.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ if (data.is_interrupt) return;+ const sessionId = data.session_id || "unknown";+ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "post_tool_failure",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ tool_name: data.tool_name,+ tool_input: data.tool_input,+ error: data.error+ }+ }),+ signal: AbortSignal.timeout(3e3)+ });+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=post-tool-failure.mjs.map\ No newline at end of filediff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjsnew file mode 100755index 00000000..d715d82a--- /dev/null+++ b/plugin/scripts/pre-compact.mjs@@ -0,0 +1,42 @@+#!/usr/bin/env node+//#region src/hooks/pre-compact.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ const sessionId = data.session_id || "unknown";+ const project = data.cwd || process.cwd();+ try {+ const res = await fetch(`${REST_URL}/agentmemory/context`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ sessionId,+ project,+ budget: 1500+ }),+ signal: AbortSignal.timeout(5e3)+ });+ if (res.ok) {+ const result = await res.json();+ if (result.context) process.stdout.write(result.context);+ }+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=pre-compact.mjs.map\ No newline at end of filediff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjsnew file mode 100755index 00000000..2a957472--- /dev/null+++ b/plugin/scripts/pre-tool-use.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+//#region src/hooks/pre-tool-use.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ const toolName = data.tool_name;+ if (!toolName) return;+ if (![+ "Edit",+ "Write",+ "Read",+ "Glob",+ "Grep"+ ].includes(toolName)) return;+ const toolInput = data.tool_input || {};+ const files = [];+ for (const key of [+ "file_path",+ "path",+ "file",+ "pattern"+ ]) {+ const val = toolInput[key];+ if (typeof val === "string" && val.length > 0) files.push(val);+ }+ if (files.length === 0) return;+ const sessionId = data.session_id || "unknown";+ try {+ const res = await fetch(`${REST_URL}/agentmemory/file-context`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ sessionId,+ files+ }),+ signal: AbortSignal.timeout(2e3)+ });+ if (res.ok) {+ const result = await res.json();+ if (result.context) process.stdout.write(result.context);+ }+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=pre-tool-use.mjs.map\ No newline at end of filediff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjsnew file mode 100755index 00000000..047d734d--- /dev/null+++ b/plugin/scripts/subagent-start.mjs@@ -0,0 +1,43 @@+#!/usr/bin/env node+//#region src/hooks/subagent-start.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ const sessionId = data.session_id || "unknown";+ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "subagent_start",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ agent_id: data.agent_id,+ agent_type: data.agent_type+ }+ }),+ signal: AbortSignal.timeout(2e3)+ });+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=subagent-start.mjs.map\ No newline at end of filediff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjsnew file mode 100755index 00000000..9a08e5c0--- /dev/null+++ b/plugin/scripts/subagent-stop.mjs@@ -0,0 +1,45 @@+#!/usr/bin/env node+//#region src/hooks/subagent-stop.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ const sessionId = data.session_id || "unknown";+ const lastMsg = typeof data.last_assistant_message === "string" ? data.last_assistant_message.slice(0, 4e3) : "";+ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "subagent_stop",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ agent_id: data.agent_id,+ agent_type: data.agent_type,+ last_message: lastMsg+ }+ }),+ signal: AbortSignal.timeout(3e3)+ });+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=subagent-stop.mjs.map\ No newline at end of filediff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjsnew file mode 100755index 00000000..38a298dc--- /dev/null+++ b/plugin/scripts/task-completed.mjs@@ -0,0 +1,46 @@+#!/usr/bin/env node+//#region src/hooks/task-completed.ts+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";+function authHeaders() {+ const h = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}+async function main() {+ let input = "";+ for await (const chunk of process.stdin) input += chunk;+ let data;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }+ const sessionId = data.session_id || "unknown";+ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "task_completed",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ task_id: data.task_id,+ task_subject: data.task_subject,+ task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "",+ teammate_name: data.teammate_name,+ team_name: data.team_name+ }+ }),+ signal: AbortSignal.timeout(2e3)+ });+ } catch {}+}+main();++//#endregion+export { };+//# sourceMappingURL=task-completed.mjs.map\ No newline at end of filediff --git a/plugin/skills/forget/SKILL.md b/plugin/skills/forget/SKILL.mdnew file mode 100644index 00000000..945d502d--- /dev/null+++ b/plugin/skills/forget/SKILL.md@@ -0,0 +1,32 @@+---+name: forget+description: Delete specific observations or sessions from agentmemory. Use when user says "forget this", "delete memory", or wants to remove specific data for privacy.+argument-hint: "[what to forget - session ID, file path, or search term]"+user-invocable: true+---++The user wants to remove data from agentmemory: $ARGUMENTS++**IMPORTANT**: This is a destructive operation. Always confirm with the user before deleting.++Steps:+1. First, search for matching observations:+ ```bash+ curl -s -H "Content-Type: application/json" \+ -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" \+ -X POST "http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/search" \+ -d '{"query": "<SEARCH_TERM>", "limit": 20}'+ ```++2. Show the user what was found and ask for confirmation+3. If confirmed, delete via:+ ```bash+ curl -s -H "Content-Type: application/json" \+ -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" \+ -X POST "http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/forget" \+ -d '{"sessionId": "<ID>"}' # or {"observationIds": ["id1", "id2"]}+ ```++4. Confirm deletion to the user++Never delete without explicit user confirmation.diff --git a/plugin/skills/recall/SKILL.md b/plugin/skills/recall/SKILL.mdnew file mode 100644index 00000000..b8afdd67--- /dev/null+++ b/plugin/skills/recall/SKILL.md@@ -0,0 +1,18 @@+---+name: recall+description: Search agentmemory for past observations, sessions, and learnings about a topic. Use when the user says "recall", "remember", "what did we do", or needs context from past sessions.+argument-hint: "[search query]"+user-invocable: true+---++Search agentmemory for observations matching: $ARGUMENTS++!`curl -s -H "Content-Type: application/json" -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" -X POST http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/search -d "{\"query\": \"$ARGUMENTS\", \"limit\": 10}" 2>/dev/null || echo '{"results":[]}'`++Present the search results to the user in a readable format:+- Group by session+- Show observation type, title, and narrative+- Highlight the most important observations (importance >= 7)+- If no results found, suggest alternative search terms++Do NOT make up or hallucinate results. Only present what was returned from the search.diff --git a/plugin/skills/remember/SKILL.md b/plugin/skills/remember/SKILL.mdnew file mode 100644index 00000000..d00bf960--- /dev/null+++ b/plugin/skills/remember/SKILL.md@@ -0,0 +1,25 @@+---+name: remember+description: Explicitly save an insight, decision, or learning to agentmemory's long-term storage. Use when the user says "remember this", "save this", or wants to preserve knowledge for future sessions.+argument-hint: "[what to remember]"+user-invocable: true+---++The user wants to save this to long-term memory: $ARGUMENTS++To save this, make a POST request using the Bash tool:++```bash+curl -s -H "Content-Type: application/json" \+ -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" \+ -X POST "http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/remember" \+ -d '{"content": "<ESCAPED_CONTENT>", "concepts": [<CONCEPTS>], "files": [<FILES>]}'+```++Steps:+1. Analyze what the user wants to remember+2. Extract key concepts (2-5 searchable terms)+3. Extract relevant file paths if any+4. Make the API call with the properly escaped content+5. Confirm to the user that the memory was saved+6. Show what concepts were tagged for future recalldiff --git a/plugin/skills/session-history/SKILL.md b/plugin/skills/session-history/SKILL.mdnew file mode 100644index 00000000..59ff54ab--- /dev/null+++ b/plugin/skills/session-history/SKILL.md@@ -0,0 +1,17 @@+---+name: session-history+description: Show what happened in recent past sessions on this project. Use when user asks "what did we do last time", "session history", "past sessions", or wants an overview of previous work.+user-invocable: true+---++Fetch recent session history from agentmemory:++!`curl -s -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" "http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/sessions" 2>/dev/null || echo '{"sessions":[]}'`++Present the sessions in reverse chronological order:+- Show session ID (first 8 chars), project, start time, status+- For each session with observations, show the key highlights+- Note total observation count per session+- If summaries exist, show the session title and key decisions++Format as a clean timeline. Do NOT make up sessions -- only show what was returned.diff --git a/src/functions/compress.ts b/src/functions/compress.tsindex de8f6779..0ed1f0e7 100644--- a/src/functions/compress.ts+++ b/src/functions/compress.ts@@ -26,6 +26,9 @@ const VALID_TYPES = new Set<string>(["error","decision","discovery",+ "subagent",+ "notification",+ "task","other",]);diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.tsnew file mode 100644index 00000000..71f509ac--- /dev/null+++ b/src/functions/consolidate.ts@@ -0,0 +1,160 @@+import type { ISdk } from "iii-sdk";+import { getContext } from "iii-sdk";+import type {+ CompressedObservation,+ Memory,+ Session,+ MemoryProvider,+} from "../types.js";+import { KV, generateId } from "../state/schema.js";+import { StateKV } from "../state/kv.js";++const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory.++Output XML:+<memory>+ <type>pattern|preference|architecture|bug|workflow|fact</type>+ <title>Concise memory title (max 80 chars)</title>+ <content>2-4 sentence description of the learned insight</content>+ <concepts>+ <concept>key term</concept>+ </concepts>+ <files>+ <file>relevant/file/path</file>+ </files>+ <strength>1-10 how confident/important this memory is</strength>+</memory>`;++import { getXmlTag, getXmlChildren } from "../prompts/xml.js";++function parseMemoryXml(+ xml: string,+ sessionIds: string[],+): Omit<Memory, "id" | "createdAt" | "updatedAt"> | null {+ const type = getXmlTag(xml, "type");+ const title = getXmlTag(xml, "title");+ const content = getXmlTag(xml, "content");+ if (!type || !title || !content) return null;++ const validTypes = new Set([+ "pattern",+ "preference",+ "architecture",+ "bug",+ "workflow",+ "fact",+ ]);++ return {+ type: (validTypes.has(type) ? type : "fact") as Memory["type"],+ title,+ content,+ concepts: getXmlChildren(xml, "concepts", "concept"),+ files: getXmlChildren(xml, "files", "file"),+ sessionIds,+ strength: Math.max(+ 1,+ Math.min(10, parseInt(getXmlTag(xml, "strength") || "5", 10) || 5),+ ),+ };+}++export function registerConsolidateFunction(+ sdk: ISdk,+ kv: StateKV,+ provider: MemoryProvider,+): void {+ sdk.registerFunction(+ { id: "mem::consolidate" },+ async (data: { project?: string; minObservations?: number }) => {+ const ctx = getContext();+ const minObs = data.minObservations || 10;++ const sessions = await kv.list<Session>(KV.sessions);+ const filtered = data.project+ ? sessions.filter((s) => s.project === data.project)+ : sessions;++ const allObs: Array<CompressedObservation & { sid: string }> = [];+ for (const session of filtered) {+ const observations = await kv.list<CompressedObservation>(+ KV.observations(session.id),+ );+ for (const obs of observations) {+ if (obs.title && obs.importance >= 5) {+ allObs.push({ ...obs, sid: session.id });+ }+ }+ }++ if (allObs.length < minObs) {+ return { consolidated: 0, reason: "insufficient_observations" };+ }++ const conceptGroups = new Map<string, typeof allObs>();+ for (const obs of allObs) {+ for (const concept of obs.concepts) {+ const key = concept.toLowerCase();+ if (!conceptGroups.has(key)) conceptGroups.set(key, []);+ conceptGroups.get(key)!.push(obs);+ }+ }++ let consolidated = 0;+ const existingMemories = await kv.list<Memory>(KV.memories);+ const existingTitles = new Set(+ existingMemories.map((m) => m.title.toLowerCase()),+ );++ for (const [concept, obsGroup] of conceptGroups) {+ if (obsGroup.length < 3) continue;++ const top = obsGroup+ .sort((a, b) => b.importance - a.importance)+ .slice(0, 8);+ const sessionIds = [...new Set(top.map((o) => o.sid))];++ const prompt = top+ .map(+ (o) =>+ `[${o.type}] ${o.title}\n${o.narrative}\nFiles: ${o.files.join(", ")}\nImportance: ${o.importance}`,+ )+ .join("\n\n");++ try {+ const response = await provider.compress(+ CONSOLIDATION_SYSTEM,+ `Concept: "${concept}"\n\nObservations:\n${prompt}`,+ );+ const parsed = parseMemoryXml(response, sessionIds);+ if (!parsed) continue;++ if (existingTitles.has(parsed.title.toLowerCase())) continue;++ const now = new Date().toISOString();+ const memory: Memory = {+ id: generateId("mem"),+ createdAt: now,+ updatedAt: now,+ ...parsed,+ };++ await kv.set(KV.memories, memory.id, memory);+ existingTitles.add(memory.title.toLowerCase());+ consolidated++;+ } catch (err) {+ ctx.logger.warn("Consolidation failed for concept", {+ concept,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ ctx.logger.info("Consolidation complete", {+ consolidated,+ totalObs: allObs.length,+ });+ return { consolidated, totalObservations: allObs.length };+ },+ );+}diff --git a/src/functions/file-index.ts b/src/functions/file-index.tsnew file mode 100644index 00000000..751e30da--- /dev/null+++ b/src/functions/file-index.ts@@ -0,0 +1,97 @@+import type { ISdk } from "iii-sdk";+import { getContext } from "iii-sdk";+import type { CompressedObservation, Session } from "../types.js";+import { KV } from "../state/schema.js";+import { StateKV } from "../state/kv.js";++interface FileHistory {+ file: string;+ observations: Array<{+ sessionId: string;+ obsId: string;+ type: string;+ title: string;+ narrative: string;+ importance: number;+ timestamp: string;+ }>;+}++export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {+ sdk.registerFunction(+ { id: "mem::file-context" },+ async (data: { sessionId: string; files: string[] }) => {+ const ctx = getContext();+ const results: FileHistory[] = [];++ const sessions = await kv.list<Session>(KV.sessions);+ const otherSessions = sessions+ .filter((s) => s.id !== data.sessionId)+ .sort(+ (a, b) =>+ new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),+ )+ .slice(0, 15);++ for (const file of data.files) {+ const history: FileHistory = { file, observations: [] };+ const normalizedFile = file.replace(/^\.\//, "");++ for (const session of otherSessions) {+ const observations = await kv.list<CompressedObservation>(+ KV.observations(session.id),+ );++ for (const obs of observations) {+ if (!obs.files || !obs.title) continue;+ const matches = obs.files.some(+ (f) =>+ f === file ||+ f === normalizedFile ||+ f.endsWith(`/${normalizedFile}`) ||+ normalizedFile.endsWith(`/${f}`),+ );+ if (matches && obs.importance >= 4) {+ history.observations.push({+ sessionId: session.id,+ obsId: obs.id,+ type: obs.type,+ title: obs.title,+ narrative: obs.narrative,+ importance: obs.importance,+ timestamp: obs.timestamp,+ });+ }+ }+ }++ history.observations.sort((a, b) => b.importance - a.importance);+ history.observations = history.observations.slice(0, 5);++ if (history.observations.length > 0) {+ results.push(history);+ }+ }++ if (results.length === 0) {+ return { context: "" };+ }++ const lines: string[] = ["<agentmemory-file-context>"];+ for (const fh of results) {+ lines.push(`## ${fh.file}`);+ for (const obs of fh.observations) {+ lines.push(`- [${obs.type}] ${obs.title}: ${obs.narrative}`);+ }+ }+ lines.push("</agentmemory-file-context>");++ const context = lines.join("\n");+ ctx.logger.info("File context generated", {+ files: data.files.length,+ results: results.length,+ });+ return { context };+ },+ );+}diff --git a/src/functions/observe.ts b/src/functions/observe.tsindex 0457a4c1..db8e50ba 100644--- a/src/functions/observe.ts+++ b/src/functions/observe.ts@@ -33,10 +33,13 @@ export function registerObserveFunction(sdk: ISdk, kv: StateKV): void {if (typeof payload.data === "object" && payload.data !== null) {const d = payload.data as Record<string, unknown>;- if (payload.hookType === "post_tool_use") {+ if (+ payload.hookType === "post_tool_use" ||+ payload.hookType === "post_tool_failure"+ ) {raw.toolName = d["tool_name"] as string | undefined;raw.toolInput = d["tool_input"];- raw.toolOutput = d["tool_output"];+ raw.toolOutput = d["tool_output"] || d["error"];}if (payload.hookType === "prompt_submit") {raw.userPrompt = d["prompt"] as string | undefined;diff --git a/src/functions/patterns.ts b/src/functions/patterns.tsnew file mode 100644index 00000000..4e23ce14--- /dev/null+++ b/src/functions/patterns.ts@@ -0,0 +1,138 @@+import type { ISdk } from "iii-sdk";+import { getContext } from "iii-sdk";+import type { CompressedObservation, Session } from "../types.js";+import { KV } from "../state/schema.js";+import { StateKV } from "../state/kv.js";++interface Pattern {+ type: "co_change" | "error_repeat" | "workflow";+ description: string;+ files: string[];+ frequency: number;+ sessions: string[];+}++export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void {+ sdk.registerFunction(+ { id: "mem::patterns" },+ async (data: { project?: string }) => {+ const ctx = getContext();+ const patterns: Pattern[] = [];++ const sessions = await kv.list<Session>(KV.sessions);+ const filtered = data.project+ ? sessions.filter((s) => s.project === data.project)+ : sessions;++ const fileCoOccurrences = new Map<string, number>();+ const fileSessionMap = new Map<string, Set<string>>();+ const errorPatterns = new Map<+ string,+ { count: number; sessions: Set<string> }+ >();++ for (const session of filtered) {+ const observations = await kv.list<CompressedObservation>(+ KV.observations(session.id),+ );+ if (!observations.length) continue;++ const sessionFiles = new Set<string>();+ for (const obs of observations) {+ if (!obs.files) continue;+ for (const f of obs.files) {+ sessionFiles.add(f);+ if (!fileSessionMap.has(f)) fileSessionMap.set(f, new Set());+ fileSessionMap.get(f)!.add(session.id);+ }++ if (obs.type === "error" && obs.title) {+ const key = obs.title.toLowerCase().slice(0, 80);+ if (!errorPatterns.has(key)) {+ errorPatterns.set(key, { count: 0, sessions: new Set() });+ }+ const ep = errorPatterns.get(key)!;+ ep.count++;+ ep.sessions.add(session.id);+ }+ }++ const fileList = [...sessionFiles].sort();+ for (let i = 0; i < fileList.length; i++) {+ for (let j = i + 1; j < fileList.length; j++) {+ const pair = `${fileList[i]}::${fileList[j]}`;+ fileCoOccurrences.set(pair, (fileCoOccurrences.get(pair) || 0) + 1);+ }+ }+ }++ for (const [pair, count] of fileCoOccurrences) {+ if (count < 3) continue;+ const [fileA, fileB] = pair.split("::");+ const sessionsA = fileSessionMap.get(fileA) || new Set();+ const sessionsB = fileSessionMap.get(fileB) || new Set();+ const commonSessions = [...sessionsA].filter((s) => sessionsB.has(s));++ patterns.push({+ type: "co_change",+ description: `${fileA} and ${fileB} are frequently modified together`,+ files: [fileA, fileB],+ frequency: count,+ sessions: commonSessions,+ });+ }++ for (const [+ errorKey,+ { count, sessions: errorSessions },+ ] of errorPatterns) {+ if (count < 2) continue;+ patterns.push({+ type: "error_repeat",+ description: `Recurring error: ${errorKey}`,+ files: [],+ frequency: count,+ sessions: [...errorSessions],+ });+ }++ patterns.sort((a, b) => b.frequency - a.frequency);++ ctx.logger.info("Pattern detection complete", {+ patterns: patterns.length,+ sessions: filtered.length,+ });++ return { patterns: patterns.slice(0, 20) };+ },+ );++ sdk.registerFunction(+ { id: "mem::generate-rules" },+ async (data: { project?: string }) => {+ const ctx = getContext();+ const result = await sdk.trigger<+ { project?: string },+ { patterns: Pattern[] }+ >("mem::patterns", data);++ const rules: string[] = [];++ for (const pattern of result.patterns) {+ if (pattern.type === "co_change" && pattern.frequency >= 4) {+ rules.push(+ `When modifying ${pattern.files[0]}, also check ${pattern.files[1]} (co-changed ${pattern.frequency} times).`,+ );+ }+ if (pattern.type === "error_repeat" && pattern.frequency >= 3) {+ rules.push(+ `Watch for: ${pattern.description} (occurred ${pattern.frequency} times across ${pattern.sessions.length} sessions).`,+ );+ }+ }++ ctx.logger.info("Rules generated", { count: rules.length });+ return { rules };+ },+ );+}diff --git a/src/functions/remember.ts b/src/functions/remember.tsnew file mode 100644index 00000000..be3839e1--- /dev/null+++ b/src/functions/remember.ts@@ -0,0 +1,92 @@+import type { ISdk } from "iii-sdk";+import { getContext } from "iii-sdk";+import type { Memory } from "../types.js";+import { KV, generateId } from "../state/schema.js";+import { StateKV } from "../state/kv.js";++export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {+ sdk.registerFunction(+ { id: "mem::remember" },+ async (data: {+ content: string;+ type?: string;+ concepts?: string[];+ files?: string[];+ }) => {+ const ctx = getContext();+ const validTypes = new Set([+ "pattern",+ "preference",+ "architecture",+ "bug",+ "workflow",+ "fact",+ ]);+ const memType = validTypes.has(data.type || "")+ ? (data.type as Memory["type"])+ : "fact";++ const now = new Date().toISOString();+ const memory: Memory = {+ id: generateId("mem"),+ createdAt: now,+ updatedAt: now,+ type: memType,+ title: data.content.slice(0, 80),+ content: data.content,+ concepts: data.concepts || [],+ files: data.files || [],+ sessionIds: [],+ strength: 7,+ };++ await kv.set(KV.memories, memory.id, memory);++ ctx.logger.info("Memory saved", {+ memId: memory.id,+ type: memory.type,+ });+ return { success: true, memory };+ },+ );++ sdk.registerFunction(+ { id: "mem::forget" },+ async (data: {+ sessionId?: string;+ observationIds?: string[];+ memoryId?: string;+ }) => {+ const ctx = getContext();+ let deleted = 0;++ if (data.memoryId) {+ await kv.delete(KV.memories, data.memoryId);+ deleted++;+ }++ if (data.observationIds && data.sessionId) {+ for (const obsId of data.observationIds) {+ await kv.delete(KV.observations(data.sessionId), obsId);+ deleted++;+ }+ }++ if (data.sessionId && !data.observationIds) {+ const observations = await kv.list<{ id: string }>(+ KV.observations(data.sessionId),+ );+ for (const obs of observations) {+ await kv.delete(KV.observations(data.sessionId), obs.id);+ deleted++;+ }+ await kv.delete(KV.sessions, data.sessionId);+ await kv.delete(KV.summaries, data.sessionId);+ deleted += 2;+ }++ ctx.logger.info("Memory forgotten", { deleted });+ return { success: true, deleted };+ },+ );+}diff --git a/src/hooks/notification.ts b/src/hooks/notification.tsnew file mode 100644index 00000000..ae349677--- /dev/null+++ b/src/hooks/notification.ts@@ -0,0 +1,52 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ if (data.notification_type !== "permission_prompt") return;++ const sessionId = (data.session_id as string) || "unknown";++ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "notification",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: new Date().toISOString(),+ data: {+ notification_type: data.notification_type,+ title: data.title,+ message: data.message,+ },+ }),+ signal: AbortSignal.timeout(2000),+ });+ } catch {+ // fire and forget+ }+}++main();diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.tsnew file mode 100644index 00000000..97646720--- /dev/null+++ b/src/hooks/post-tool-failure.ts@@ -0,0 +1,52 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ if (data.is_interrupt) return;++ const sessionId = (data.session_id as string) || "unknown";++ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "post_tool_failure",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: new Date().toISOString(),+ data: {+ tool_name: data.tool_name,+ tool_input: data.tool_input,+ error: data.error,+ },+ }),+ signal: AbortSignal.timeout(3000),+ });+ } catch {+ // fire and forget+ }+}++main();diff --git a/src/hooks/pre-compact.ts b/src/hooks/pre-compact.tsnew file mode 100644index 00000000..9fb680ee--- /dev/null+++ b/src/hooks/pre-compact.ts@@ -0,0 +1,47 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ const sessionId = (data.session_id as string) || "unknown";+ const project = (data.cwd as string) || process.cwd();++ try {+ const res = await fetch(`${REST_URL}/agentmemory/context`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ sessionId, project, budget: 1500 }),+ signal: AbortSignal.timeout(5000),+ });++ if (res.ok) {+ const result = (await res.json()) as { context?: string };+ if (result.context) {+ process.stdout.write(result.context);+ }+ }+ } catch {+ // best effort -- don't block compaction+ }+}++main();diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.tsnew file mode 100644index 00000000..e74c1099--- /dev/null+++ b/src/hooks/pre-tool-use.ts@@ -0,0 +1,60 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ const toolName = data.tool_name as string;+ if (!toolName) return;++ const fileTools = ["Edit", "Write", "Read", "Glob", "Grep"];+ if (!fileTools.includes(toolName)) return;++ const toolInput = (data.tool_input || {}) as Record<string, unknown>;+ const files: string[] = [];+ for (const key of ["file_path", "path", "file", "pattern"]) {+ const val = toolInput[key];+ if (typeof val === "string" && val.length > 0) files.push(val);+ }+ if (files.length === 0) return;++ const sessionId = (data.session_id as string) || "unknown";++ try {+ const res = await fetch(`${REST_URL}/agentmemory/file-context`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({ sessionId, files }),+ signal: AbortSignal.timeout(2000),+ });++ if (res.ok) {+ const result = (await res.json()) as { context?: string };+ if (result.context) {+ process.stdout.write(result.context);+ }+ }+ } catch {+ // don't block tool execution+ }+}++main();diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.tsnew file mode 100644index 00000000..2bacd8b1--- /dev/null+++ b/src/hooks/subagent-start.ts@@ -0,0 +1,49 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ const sessionId = (data.session_id as string) || "unknown";++ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "subagent_start",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: new Date().toISOString(),+ data: {+ agent_id: data.agent_id,+ agent_type: data.agent_type,+ },+ }),+ signal: AbortSignal.timeout(2000),+ });+ } catch {+ // fire and forget+ }+}++main();diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.tsnew file mode 100644index 00000000..f2756ac1--- /dev/null+++ b/src/hooks/subagent-stop.ts@@ -0,0 +1,53 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ const sessionId = (data.session_id as string) || "unknown";+ const lastMsg = typeof data.last_assistant_message === "string"+ ? data.last_assistant_message.slice(0, 4000)+ : "";++ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "subagent_stop",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: new Date().toISOString(),+ data: {+ agent_id: data.agent_id,+ agent_type: data.agent_type,+ last_message: lastMsg,+ },+ }),+ signal: AbortSignal.timeout(3000),+ });+ } catch {+ // fire and forget+ }+}++main();diff --git a/src/hooks/task-completed.ts b/src/hooks/task-completed.tsnew file mode 100644index 00000000..c7a44cb9--- /dev/null+++ b/src/hooks/task-completed.ts@@ -0,0 +1,54 @@+#!/usr/bin/env node++const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";+const SECRET = process.env["AGENTMEMORY_SECRET"] || "";++function authHeaders(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;+ return h;+}++async function main() {+ let input = "";+ for await (const chunk of process.stdin) {+ input += chunk;+ }++ let data: Record<string, unknown>;+ try {+ data = JSON.parse(input);+ } catch {+ return;+ }++ const sessionId = (data.session_id as string) || "unknown";++ try {+ await fetch(`${REST_URL}/agentmemory/observe`, {+ method: "POST",+ headers: authHeaders(),+ body: JSON.stringify({+ hookType: "task_completed",+ sessionId,+ project: data.cwd || process.cwd(),+ cwd: data.cwd || process.cwd(),+ timestamp: new Date().toISOString(),+ data: {+ task_id: data.task_id,+ task_subject: data.task_subject,+ task_description: typeof data.task_description === "string"+ ? data.task_description.slice(0, 2000)+ : "",+ teammate_name: data.teammate_name,+ team_name: data.team_name,+ },+ }),+ signal: AbortSignal.timeout(2000),+ });+ } catch {+ // fire and forget+ }+}++main();diff --git a/src/index.ts b/src/index.tsindex 7d289396..c5f175e1 100644--- a/src/index.ts+++ b/src/index.ts@@ -9,8 +9,13 @@ import { registerSearchFunction, rebuildIndex } from "./functions/search.js";import { registerContextFunction } from "./functions/context.js";import { registerSummarizeFunction } from "./functions/summarize.js";import { registerMigrateFunction } from "./functions/migrate.js";+import { registerFileIndexFunction } from "./functions/file-index.js";+import { registerConsolidateFunction } from "./functions/consolidate.js";+import { registerPatternsFunction } from "./functions/patterns.js";+import { registerRememberFunction } from "./functions/remember.js";import { registerApiTriggers } from "./triggers/api.js";import { registerEventTriggers } from "./triggers/events.js";+import { registerMcpEndpoints } from "./mcp/server.js";async function main() {const config = loadConfig();@@ -31,6 +36,7 @@ async function main() {});const kv = new StateKV(sdk);+ const secret = getEnvVar("AGENTMEMORY_SECRET");registerPrivacyFunction(sdk);registerObserveFunction(sdk, kv);@@ -39,10 +45,14 @@ async function main() {registerContextFunction(sdk, kv, config.tokenBudget);registerSummarizeFunction(sdk, kv, provider);registerMigrateFunction(sdk, kv);+ registerFileIndexFunction(sdk, kv);+ registerConsolidateFunction(sdk, kv, provider);+ registerPatternsFunction(sdk, kv);+ registerRememberFunction(sdk, kv);- const secret = getEnvVar("AGENTMEMORY_SECRET");registerApiTriggers(sdk, kv, secret);registerEventTriggers(sdk, kv);+ registerMcpEndpoints(sdk, kv, secret);const indexCount = await rebuildIndex(kv).catch(() => 0);if (indexCount > 0) {@@ -57,6 +67,11 @@ async function main() {console.log(` POST /agentmemory/context - Generate context`);console.log(` POST /agentmemory/search - Search observations`);console.log(` POST /agentmemory/summarize - Summarize session`);+ console.log(` POST /agentmemory/remember - Save to long-term memory`);+ console.log(` POST /agentmemory/forget - Delete memory data`);+ console.log(` POST /agentmemory/file-context - File history context`);+ console.log(` POST /agentmemory/consolidate - Consolidate memories`);+ console.log(` POST /agentmemory/patterns - Detect patterns`);console.log(` GET /agentmemory/sessions - List sessions`);console.log(` GET /agentmemory/observations - Get session observations`,@@ -64,6 +79,8 @@ async function main() {console.log(` GET /agentmemory/health - Health check`);console.log(` GET /agentmemory/viewer - Web viewer`);console.log(` POST /agentmemory/migrate - Import from SQLite`);+ console.log(` GET /agentmemory/mcp/tools - MCP tool listing`);+ console.log(` POST /agentmemory/mcp/call - MCP tool execution`);const shutdown = async () => {console.log(`\n[agentmemory] Shutting down...`);diff --git a/src/mcp/server.ts b/src/mcp/server.tsnew file mode 100644index 00000000..d53b586e--- /dev/null+++ b/src/mcp/server.ts@@ -0,0 +1,218 @@+import type { ISdk, ApiRequest } from "iii-sdk";+import type { StateKV } from "../state/kv.js";+import { KV } from "../state/schema.js";++type McpTool = {+ name: string;+ description: string;+ inputSchema: {+ type: "object";+ properties: Record<string, { type: string; description: string }>;+ required?: string[];+ };+};++type McpResponse = {+ status_code: number;+ headers?: Record<string, string>;+ body: unknown;+};++const MCP_TOOLS: McpTool[] = [+ {+ name: "memory_recall",+ description:+ "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.",+ inputSchema: {+ type: "object",+ properties: {+ query: {+ type: "string",+ description: "Search query (keywords, file names, concepts)",+ },+ limit: {+ type: "number",+ description: "Max results to return (default 10)",+ },+ },+ required: ["query"],+ },+ },+ {+ name: "memory_save",+ description:+ "Explicitly save an important insight, decision, or pattern to long-term memory. Use when you discover something worth remembering for future sessions.",+ inputSchema: {+ type: "object",+ properties: {+ content: {+ type: "string",+ description: "The insight or decision to remember",+ },+ type: {+ type: "string",+ description:+ "Memory type: pattern, preference, architecture, bug, workflow, or fact",+ },+ concepts: {+ type: "string",+ description: "Comma-separated key concepts for searchability",+ },+ files: {+ type: "string",+ description: "Comma-separated relevant file paths",+ },+ },+ required: ["content"],+ },+ },+ {+ name: "memory_file_history",+ description:+ "Get past observations about specific files. Use before modifying a file to understand its history and past changes.",+ inputSchema: {+ type: "object",+ properties: {+ files: {+ type: "string",+ description: "Comma-separated file paths to look up",+ },+ sessionId: {+ type: "string",+ description: "Current session ID to exclude from results",+ },+ },+ required: ["files"],+ },+ },+ {+ name: "memory_patterns",+ description:+ "Detect recurring patterns across sessions: files that change together, repeated errors, common workflows.",+ inputSchema: {+ type: "object",+ properties: {+ project: {+ type: "string",+ description: "Project path to analyze (optional, analyzes all if omitted)",+ },+ },+ },+ },+ {+ name: "memory_sessions",+ description:+ "List recent sessions with their status and observation counts.",+ inputSchema: {+ type: "object",+ properties: {},+ },+ },+];++export function registerMcpEndpoints(+ sdk: ISdk,+ kv: StateKV,+ secret?: string,+): void {+ function checkAuth(+ req: ApiRequest,+ sec: string | undefined,+ ): McpResponse | null {+ if (!sec) return null;+ const auth =+ req.headers?.["authorization"] || req.headers?.["Authorization"];+ if (auth !== `Bearer ${sec}`) {+ return { status_code: 401, body: { error: "unauthorized" } };+ }+ return null;+ }++ sdk.registerFunction(+ { id: "mcp::tools::list" },+ async (): Promise<McpResponse> => ({+ status_code: 200,+ body: { tools: MCP_TOOLS },+ }),+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "mcp::tools::list",+ config: { api_path: "/agentmemory/mcp/tools", http_method: "GET" },+ });++ sdk.registerFunction(+ { id: "mcp::tools::call" },+ async (+ req: ApiRequest<{ name: string; arguments: Record<string, unknown> }>,+ ): Promise<McpResponse> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;++ const { name, arguments: args } = req.body;++ switch (name) {+ case "memory_recall": {+ const result = await sdk.trigger("mem::search", {+ query: args.query as string,+ limit: (args.limit as number) || 10,+ });+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };+ }++ case "memory_save": {+ const content = args.content as string;+ const type = (args.type as string) || "fact";+ const concepts = args.concepts+ ? (args.concepts as string).split(",").map((c: string) => c.trim())+ : [];+ const files = args.files+ ? (args.files as string).split(",").map((f: string) => f.trim())+ : [];++ const result = await sdk.trigger("mem::remember", {+ content,+ type,+ concepts,+ files,+ });+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result) }] } };+ }++ case "memory_file_history": {+ const fileList = (args.files as string)+ .split(",")+ .map((f: string) => f.trim());+ const result = await sdk.trigger("mem::file-context", {+ sessionId: (args.sessionId as string) || "",+ files: fileList,+ });+ return { status_code: 200, body: { content: [{ type: "text", text: (result as { context: string }).context || "No history found." }] } };+ }++ case "memory_patterns": {+ const result = await sdk.trigger("mem::patterns", {+ project: args.project as string,+ });+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };+ }++ case "memory_sessions": {+ const sessions = await kv.list(KV.sessions);+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify({ sessions }, null, 2) }] } };+ }++ default:+ return {+ status_code: 400,+ body: { error: `Unknown tool: ${name}` },+ };+ }+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "mcp::tools::call",+ config: { api_path: "/agentmemory/mcp/call", http_method: "POST" },+ });+}diff --git a/src/prompts/compression.ts b/src/prompts/compression.tsindex beff1c17..51183b0c 100644--- a/src/prompts/compression.ts+++ b/src/prompts/compression.ts@@ -3,7 +3,7 @@ export const COMPRESSION_SYSTEM = `You are a memory compression engine for an AIOutput EXACTLY this XML format with no additional text:<observation>- <type>one of: file_read, file_write, file_edit, command_run, search, web_fetch, conversation, error, decision, discovery, other</type>+ <type>one of: file_read, file_write, file_edit, command_run, search, web_fetch, conversation, error, decision, discovery, subagent, notification, task, other</type><title>Short descriptive title (max 80 chars)</title><subtitle>One-line context (optional)</subtitle><facts>@@ -25,38 +25,43 @@ Rules:- File paths must be exact- Importance: 1-3 for routine reads, 4-6 for edits/commands, 7-9 for architectural decisions, 10 for breaking changes- Concepts should be reusable search terms (e.g., "React hooks", "SQL migration", "auth middleware")-- Strip any secrets, tokens, or credentials from the output`+- Strip any secrets, tokens, or credentials from the output`;export function buildCompressionPrompt(observation: {- hookType: string- toolName?: string- toolInput?: unknown- toolOutput?: unknown- userPrompt?: string- timestamp: string+ hookType: string;+ toolName?: string;+ toolInput?: unknown;+ toolOutput?: unknown;+ userPrompt?: string;+ timestamp: string;}): string {- const parts = [`Timestamp: ${observation.timestamp}`, `Hook: ${observation.hookType}`]+ const parts = [+ `Timestamp: ${observation.timestamp}`,+ `Hook: ${observation.hookType}`,+ ];- if (observation.toolName) parts.push(`Tool: ${observation.toolName}`)+ if (observation.toolName) parts.push(`Tool: ${observation.toolName}`);if (observation.toolInput) {- const input = typeof observation.toolInput === 'string'- ? observation.toolInput- : JSON.stringify(observation.toolInput, null, 2)- parts.push(`Input:\n${truncate(input, 4000)}`)+ const input =+ typeof observation.toolInput === "string"+ ? observation.toolInput+ : JSON.stringify(observation.toolInput, null, 2);+ parts.push(`Input:\n${truncate(input, 4000)}`);}if (observation.toolOutput) {- const output = typeof observation.toolOutput === 'string'- ? observation.toolOutput- : JSON.stringify(observation.toolOutput, null, 2)- parts.push(`Output:\n${truncate(output, 4000)}`)+ const output =+ typeof observation.toolOutput === "string"+ ? observation.toolOutput+ : JSON.stringify(observation.toolOutput, null, 2);+ parts.push(`Output:\n${truncate(output, 4000)}`);}if (observation.userPrompt) {- parts.push(`User prompt:\n${truncate(observation.userPrompt, 2000)}`)+ parts.push(`User prompt:\n${truncate(observation.userPrompt, 2000)}`);}- return parts.join('\n\n')+ return parts.join("\n\n");}function truncate(s: string, max: number): string {- return s.length > max ? s.slice(0, max) + '\n[...truncated]' : s+ return s.length > max ? s.slice(0, max) + "\n[...truncated]" : s;}diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex 7262f009..4534eca4 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -36,7 +36,7 @@ export function registerApiTriggers({ id: "api::health" },async (): Promise<Response> => ({status_code: 200,- body: { status: "ok", service: "agentmemory", version: "0.1.0" },+ body: { status: "ok", service: "agentmemory", version: "0.2.0" },}),);sdk.registerTrigger({@@ -192,6 +192,113 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/observations", http_method: "GET" },});+ sdk.registerFunction(+ { id: "api::file-context" },+ async (+ req: ApiRequest<{ sessionId: string; files: string[] }>,+ ): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::file-context", req.body);+ return { status_code: 200, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::file-context",+ config: { api_path: "/agentmemory/file-context", http_method: "POST" },+ });++ sdk.registerFunction(+ { id: "api::remember" },+ async (+ req: ApiRequest<{+ content: string;+ type?: string;+ concepts?: string[];+ files?: string[];+ }>,+ ): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::remember", req.body);+ return { status_code: 201, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::remember",+ config: { api_path: "/agentmemory/remember", http_method: "POST" },+ });++ sdk.registerFunction(+ { id: "api::forget" },+ async (+ req: ApiRequest<{+ sessionId?: string;+ observationIds?: string[];+ memoryId?: string;+ }>,+ ): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::forget", req.body);+ return { status_code: 200, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::forget",+ config: { api_path: "/agentmemory/forget", http_method: "POST" },+ });++ sdk.registerFunction(+ { id: "api::consolidate" },+ async (+ req: ApiRequest<{ project?: string; minObservations?: number }>,+ ): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::consolidate", req.body);+ return { status_code: 200, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::consolidate",+ config: { api_path: "/agentmemory/consolidate", http_method: "POST" },+ });++ sdk.registerFunction(+ { id: "api::patterns" },+ async (req: ApiRequest<{ project?: string }>): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::patterns", req.body);+ return { status_code: 200, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::patterns",+ config: { api_path: "/agentmemory/patterns", http_method: "POST" },+ });++ sdk.registerFunction(+ { id: "api::generate-rules" },+ async (req: ApiRequest<{ project?: string }>): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger("mem::generate-rules", req.body);+ return { status_code: 200, body: result };+ },+ );+ sdk.registerTrigger({+ type: "http",+ function_id: "api::generate-rules",+ config: { api_path: "/agentmemory/generate-rules", http_method: "POST" },+ });+sdk.registerFunction({ id: "api::migrate" },async (req: ApiRequest<{ dbPath: string }>): Promise<Response> => {diff --git a/src/types.ts b/src/types.tsindex 201e1b7b..a405cb88 100644--- a/src/types.ts+++ b/src/types.ts@@ -48,6 +48,9 @@ export type ObservationType =| "error"| "decision"| "discovery"+ | "subagent"+ | "notification"+ | "task"| "other";export interface Memory {@@ -78,7 +81,14 @@ export interface SessionSummary {export type HookType =| "session_start"| "prompt_submit"+ | "pre_tool_use"| "post_tool_use"+ | "post_tool_failure"+ | "pre_compact"+ | "subagent_start"+ | "subagent_stop"+ | "notification"+ | "task_completed"| "stop"| "session_end";diff --git a/tsdown.config.ts b/tsdown.config.tsindex f0295c3c..1dc56f61 100644--- a/tsdown.config.ts+++ b/tsdown.config.ts@@ -3,7 +3,14 @@ import { defineConfig } from "tsdown";const hookEntries = ["src/hooks/session-start.ts","src/hooks/prompt-submit.ts",+ "src/hooks/pre-tool-use.ts","src/hooks/post-tool-use.ts",+ "src/hooks/post-tool-failure.ts",+ "src/hooks/pre-compact.ts",+ "src/hooks/subagent-start.ts",+ "src/hooks/subagent-stop.ts",+ "src/hooks/notification.ts",+ "src/hooks/task-completed.ts","src/hooks/stop.ts","src/hooks/session-end.ts",];