#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix: system audit -- 10 bugs found and resolved
Rohit Ghumare4c334b0a0ed4
diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjsindex 889cd644..f777112e 100755--- a/plugin/scripts/post-tool-use.mjs+++ b/plugin/scripts/post-tool-use.mjs@@ -1,6 +1,12 @@#!/usr/bin/env node//#region src/hooks/post-tool-use.tsconst 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;@@ -14,7 +20,7 @@ async function main() {try {await fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: authHeaders(),body: JSON.stringify({hookType: "post_tool_use",sessionId,@@ -35,7 +41,7 @@ function truncate(value, max) {if (typeof value === "string" && value.length > max) return value.slice(0, max) + "\n[...truncated]";if (typeof value === "object" && value !== null) {const str = JSON.stringify(value);- if (str.length > max) return JSON.parse(str.slice(0, max - 1) + "}");+ if (str.length > max) return str.slice(0, max) + "...[truncated]";return value;}return value;diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjsindex 3b54eed1..2623f65a 100755--- a/plugin/scripts/prompt-submit.mjs+++ b/plugin/scripts/prompt-submit.mjs@@ -1,6 +1,12 @@#!/usr/bin/env node//#region src/hooks/prompt-submit.tsconst 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;@@ -14,7 +20,7 @@ async function main() {try {await fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: authHeaders(),body: JSON.stringify({hookType: "prompt_submit",sessionId,diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjsindex 72ca9da4..c4b0fc4f 100755--- a/plugin/scripts/session-end.mjs+++ b/plugin/scripts/session-end.mjs@@ -1,6 +1,12 @@#!/usr/bin/env node//#region src/hooks/session-end.tsconst 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;@@ -14,7 +20,7 @@ async function main() {try {await fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: authHeaders(),body: JSON.stringify({ sessionId }),signal: AbortSignal.timeout(5e3)});diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjsindex a7ff150f..8c3bae85 100755--- a/plugin/scripts/session-start.mjs+++ b/plugin/scripts/session-start.mjs@@ -1,6 +1,12 @@#!/usr/bin/env node//#region src/hooks/session-start.tsconst 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;@@ -15,7 +21,7 @@ async function main() {try {const res = await fetch(`${REST_URL}/agentmemory/session/start`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: authHeaders(),body: JSON.stringify({sessionId,project,diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjsindex 44dbed60..02044233 100755--- a/plugin/scripts/stop.mjs+++ b/plugin/scripts/stop.mjs@@ -1,6 +1,12 @@#!/usr/bin/env node//#region src/hooks/stop.tsconst 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;@@ -14,7 +20,7 @@ async function main() {try {await fetch(`${REST_URL}/agentmemory/summarize`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: authHeaders(),body: JSON.stringify({ sessionId }),signal: AbortSignal.timeout(3e4)});diff --git a/src/functions/compress.ts b/src/functions/compress.tsindex be7c9bb4..de8f6779 100644--- a/src/functions/compress.ts+++ b/src/functions/compress.ts@@ -15,12 +15,27 @@ import {import { getXmlTag, getXmlChildren } from "../prompts/xml.js";import { getSearchIndex } from "./search.js";+const VALID_TYPES = new Set<string>([+ "file_read",+ "file_write",+ "file_edit",+ "command_run",+ "search",+ "web_fetch",+ "conversation",+ "error",+ "decision",+ "discovery",+ "other",+]);+function parseCompressionXml(xml: string,): Omit<CompressedObservation, "id" | "sessionId" | "timestamp"> | null {- const type = getXmlTag(xml, "type");+ const rawType = getXmlTag(xml, "type");const title = getXmlTag(xml, "title");- if (!type || !title) return null;+ if (!rawType || !title) return null;+ const type = VALID_TYPES.has(rawType) ? rawType : "other";return {type: type as ObservationType,@@ -30,7 +45,10 @@ function parseCompressionXml(narrative: getXmlTag(xml, "narrative"),concepts: getXmlChildren(xml, "concepts", "concept"),files: getXmlChildren(xml, "files", "file"),- importance: parseInt(getXmlTag(xml, "importance") || "5", 10),+ importance: Math.max(+ 1,+ Math.min(10, parseInt(getXmlTag(xml, "importance") || "5", 10) || 5),+ ),};}diff --git a/src/functions/context.ts b/src/functions/context.tsindex ace5ffae..ecc01222 100644--- a/src/functions/context.ts+++ b/src/functions/context.ts@@ -67,14 +67,15 @@ export function registerContextFunction();if (important.length > 0) {- const content = important+ const items = important.sort((a, b) => b.importance - a.importance).slice(0, 5).map((o) => `- [${o.type}] ${o.title}: ${o.narrative}`).join("\n");+ const content = `## Session ${session.id.slice(0, 8)} (${session.startedAt})\n${items}`;blocks.push({type: "observation",- content: `## Session ${session.id.slice(0, 8)} (${session.startedAt})\n${content}`,+ content,tokens: estimateTokens(content),recency: new Date(session.startedAt).getTime(),});diff --git a/src/functions/observe.ts b/src/functions/observe.tsindex 4c5e90d2..8ed895eb 100644--- a/src/functions/observe.ts+++ b/src/functions/observe.ts@@ -14,14 +14,21 @@ export function registerObserveFunction(sdk: ISdk, kv: StateKV): void {async (payload: HookPayload) => {const ctx = getContext();const obsId = generateId("obs");- const sanitizedData = stripPrivateData(JSON.stringify(payload.data));+ let sanitizedRaw: unknown = payload.data;+ try {+ const jsonStr = JSON.stringify(payload.data);+ const sanitized = stripPrivateData(jsonStr);+ sanitizedRaw = JSON.parse(sanitized);+ } catch {+ sanitizedRaw = stripPrivateData(String(payload.data));+ }const raw: RawObservation = {id: obsId,sessionId: payload.sessionId,timestamp: payload.timestamp,hookType: payload.hookType,- raw: JSON.parse(sanitizedData),+ raw: sanitizedRaw,};const d =diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.tsindex f674ef22..32ec8031 100644--- a/src/hooks/post-tool-use.ts+++ b/src/hooks/post-tool-use.ts@@ -1,28 +1,35 @@#!/usr/bin/env node-const REST_URL = process.env['AGENTMEMORY_URL'] || 'http://localhost:3111'+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 = ''+ let input = "";for await (const chunk of process.stdin) {- input += chunk+ input += chunk;}- let data: Record<string, unknown>+ let data: Record<string, unknown>;try {- data = JSON.parse(input)+ data = JSON.parse(input);} catch {- return+ return;}- const sessionId = (data.session_id as string) || 'unknown'+ const sessionId = (data.session_id as string) || "unknown";try {await fetch(`${REST_URL}/agentmemory/observe`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: authHeaders(),body: JSON.stringify({- hookType: 'post_tool_use',+ hookType: "post_tool_use",sessionId,project: data.cwd || process.cwd(),cwd: data.cwd || process.cwd(),@@ -34,22 +41,22 @@ async function main() {},}),signal: AbortSignal.timeout(3000),- })+ });} catch {// fire and forget}}function truncate(value: unknown, max: number): unknown {- if (typeof value === 'string' && value.length > max) {- return value.slice(0, max) + '\n[...truncated]'+ if (typeof value === "string" && value.length > max) {+ return value.slice(0, max) + "\n[...truncated]";}- if (typeof value === 'object' && value !== null) {- const str = JSON.stringify(value)- if (str.length > max) return JSON.parse(str.slice(0, max - 1) + '}')- return value+ if (typeof value === "object" && value !== null) {+ const str = JSON.stringify(value);+ if (str.length > max) return str.slice(0, max) + "...[truncated]";+ return value;}- return value+ return value;}-main()+main();diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.tsindex 6c631222..a959d80b 100644--- a/src/hooks/prompt-submit.ts+++ b/src/hooks/prompt-submit.ts@@ -1,28 +1,35 @@#!/usr/bin/env node-const REST_URL = process.env['AGENTMEMORY_URL'] || 'http://localhost:3111'+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 = ''+ let input = "";for await (const chunk of process.stdin) {- input += chunk+ input += chunk;}- let data: Record<string, unknown>+ let data: Record<string, unknown>;try {- data = JSON.parse(input)+ data = JSON.parse(input);} catch {- return+ return;}- const sessionId = (data.session_id as string) || 'unknown'+ const sessionId = (data.session_id as string) || "unknown";try {await fetch(`${REST_URL}/agentmemory/observe`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: authHeaders(),body: JSON.stringify({- hookType: 'prompt_submit',+ hookType: "prompt_submit",sessionId,project: data.cwd || process.cwd(),cwd: data.cwd || process.cwd(),@@ -30,10 +37,10 @@ async function main() {data: { prompt: data.prompt },}),signal: AbortSignal.timeout(3000),- })+ });} catch {// fire and forget}}-main()+main();diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.tsindex d409a04f..d5f088d5 100644--- a/src/hooks/session-end.ts+++ b/src/hooks/session-end.ts@@ -1,32 +1,39 @@#!/usr/bin/env node-const REST_URL = process.env['AGENTMEMORY_URL'] || 'http://localhost:3111'+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 = ''+ let input = "";for await (const chunk of process.stdin) {- input += chunk+ input += chunk;}- let data: Record<string, unknown>+ let data: Record<string, unknown>;try {- data = JSON.parse(input)+ data = JSON.parse(input);} catch {- return+ return;}- const sessionId = (data.session_id as string) || 'unknown'+ const sessionId = (data.session_id as string) || "unknown";try {await fetch(`${REST_URL}/agentmemory/session/end`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: authHeaders(),body: JSON.stringify({ sessionId }),signal: AbortSignal.timeout(5000),- })+ });} catch {// best-effort}}-main()+main();diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.tsindex 2a7032bd..8d5f6790 100644--- a/src/hooks/session-start.ts+++ b/src/hooks/session-start.ts@@ -1,35 +1,43 @@#!/usr/bin/env node-const REST_URL = process.env['AGENTMEMORY_URL'] || 'http://localhost:3111'+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 = ''+ let input = "";for await (const chunk of process.stdin) {- input += chunk+ input += chunk;}- let data: Record<string, unknown>+ let data: Record<string, unknown>;try {- data = JSON.parse(input)+ data = JSON.parse(input);} catch {- return+ return;}- const sessionId = (data.session_id as string) || `ses_${Date.now().toString(36)}`- const project = (data.cwd as string) || process.cwd()+ const sessionId =+ (data.session_id as string) || `ses_${Date.now().toString(36)}`;+ const project = (data.cwd as string) || process.cwd();try {const res = await fetch(`${REST_URL}/agentmemory/session/start`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: authHeaders(),body: JSON.stringify({ sessionId, project, cwd: project }),signal: AbortSignal.timeout(5000),- })+ });if (res.ok) {- const result = await res.json() as { context?: string }+ const result = (await res.json()) as { context?: string };if (result.context) {- process.stdout.write(result.context)+ process.stdout.write(result.context);}}} catch {@@ -37,4 +45,4 @@ async function main() {}}-main()+main();diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex 48bbb6b6..fb6cb5d6 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -1,32 +1,39 @@#!/usr/bin/env node-const REST_URL = process.env['AGENTMEMORY_URL'] || 'http://localhost:3111'+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 = ''+ let input = "";for await (const chunk of process.stdin) {- input += chunk+ input += chunk;}- let data: Record<string, unknown>+ let data: Record<string, unknown>;try {- data = JSON.parse(input)+ data = JSON.parse(input);} catch {- return+ return;}- const sessionId = (data.session_id as string) || 'unknown'+ const sessionId = (data.session_id as string) || "unknown";try {await fetch(`${REST_URL}/agentmemory/summarize`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: authHeaders(),body: JSON.stringify({ sessionId }),signal: AbortSignal.timeout(30000),- })+ });} catch {// summarize is best-effort}}-main()+main();diff --git a/src/index.ts b/src/index.tsindex 18216172..7d289396 100644--- a/src/index.ts+++ b/src/index.ts@@ -42,7 +42,7 @@ async function main() {const secret = getEnvVar("AGENTMEMORY_SECRET");registerApiTriggers(sdk, kv, secret);- registerEventTriggers(sdk);+ registerEventTriggers(sdk, kv);const indexCount = await rebuildIndex(kv).catch(() => 0);if (indexCount > 0) {diff --git a/src/triggers/events.ts b/src/triggers/events.tsindex e881dc34..5c9a7858 100644--- a/src/triggers/events.ts+++ b/src/triggers/events.ts@@ -1,74 +1,98 @@-import type { ISdk } from 'iii-sdk'-import { getContext } from 'iii-sdk'-import type { HookPayload } from '../types.js'--export function registerEventTriggers(sdk: ISdk): void {+import type { ISdk } from "iii-sdk";+import { getContext } from "iii-sdk";+import type { HookPayload, Session } from "../types.js";+import { KV } from "../state/schema.js";+import { StateKV } from "../state/kv.js";+export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {sdk.registerFunction(- { id: 'event::session::started', description: 'Handle session start event' },+ {+ id: "event::session::started",+ description: "Handle session start event",+ },async (data: { sessionId: string; project: string; cwd: string }) => {- const ctx = getContext()- ctx.logger.info('Session start event', { sessionId: data.sessionId })- return await sdk.trigger('api::session::start', {- body: data,- headers: {},- method: 'POST',- path_params: {},- query_params: {},- })- }- )+ const ctx = getContext();+ ctx.logger.info("Session start event", { sessionId: data.sessionId });+ const session: Session = {+ id: data.sessionId,+ project: data.project,+ cwd: data.cwd,+ startedAt: new Date().toISOString(),+ status: "active",+ observationCount: 0,+ };+ await kv.set(KV.sessions, data.sessionId, session);+ const contextResult = await sdk.trigger<+ { sessionId: string; project: string },+ { context: string }+ >("mem::context", { sessionId: data.sessionId, project: data.project });+ return { session, context: contextResult.context };+ },+ );sdk.registerTrigger({- type: 'queue',- function_id: 'event::session::started',- config: { topic: 'agentmemory.session.started' },- })+ type: "queue",+ function_id: "event::session::started",+ config: { topic: "agentmemory.session.started" },+ });sdk.registerFunction(- { id: 'event::observation', description: 'Handle new observation event' },+ { id: "event::observation", description: "Handle new observation event" },async (data: HookPayload) => {- const ctx = getContext()- ctx.logger.info('Observation event', { sessionId: data.sessionId, hook: data.hookType })- return await sdk.trigger('mem::observe', data)- }- )+ const ctx = getContext();+ ctx.logger.info("Observation event", {+ sessionId: data.sessionId,+ hook: data.hookType,+ });+ return await sdk.trigger("mem::observe", data);+ },+ );sdk.registerTrigger({- type: 'queue',- function_id: 'event::observation',- config: { topic: 'agentmemory.observation' },- })+ type: "queue",+ function_id: "event::observation",+ config: { topic: "agentmemory.observation" },+ });sdk.registerFunction(- { id: 'event::session::stopped', description: 'Handle stop event (trigger summarize)' },+ {+ id: "event::session::stopped",+ description: "Handle stop event (trigger summarize)",+ },async (data: { sessionId: string }) => {- const ctx = getContext()- ctx.logger.info('Session stop event, triggering summarize', { sessionId: data.sessionId })- return await sdk.trigger('mem::summarize', data)- }- )+ const ctx = getContext();+ ctx.logger.info("Session stop event, triggering summarize", {+ sessionId: data.sessionId,+ });+ return await sdk.trigger("mem::summarize", data);+ },+ );sdk.registerTrigger({- type: 'queue',- function_id: 'event::session::stopped',- config: { topic: 'agentmemory.session.stopped' },- })+ type: "queue",+ function_id: "event::session::stopped",+ config: { topic: "agentmemory.session.stopped" },+ });sdk.registerFunction(- { id: 'event::session::ended', description: 'Handle session end event' },+ {+ id: "event::session::ended",+ description: "Handle session end event",+ },async (data: { sessionId: string }) => {- const ctx = getContext()- ctx.logger.info('Session end event', { sessionId: data.sessionId })- return await sdk.trigger('api::session::end', {- body: data,- headers: {},- method: 'POST',- path_params: {},- query_params: {},- })- }- )+ const ctx = getContext();+ ctx.logger.info("Session end event", { sessionId: data.sessionId });+ const session = await kv.get<Session>(KV.sessions, data.sessionId);+ if (session) {+ await kv.set(KV.sessions, data.sessionId, {+ ...session,+ endedAt: new Date().toISOString(),+ status: "completed" as const,+ });+ }+ return { success: true };+ },+ );sdk.registerTrigger({- type: 'queue',- function_id: 'event::session::ended',- config: { topic: 'agentmemory.session.ended' },- })+ type: "queue",+ function_id: "event::session::ended",+ config: { topic: "agentmemory.session.ended" },+ });}diff --git a/src/viewer/index.html b/src/viewer/index.htmlindex 64b34d48..74110bf1 100644--- a/src/viewer/index.html+++ b/src/viewer/index.html@@ -104,7 +104,8 @@<script>const REST = window.location.origin;const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';- const wsPort = parseInt(window.location.port || '3111') + 1;+ const params = new URLSearchParams(window.location.search);+ const wsPort = params.get('wsPort') || String(parseInt(window.location.port || '3111') + 1);const WS_URL = `${wsProto}//${window.location.hostname}:${wsPort}`;const timeline = document.getElementById('timeline');const statusEl = document.getElementById('status');