Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix: address CodeRabbit review comments

Tanmay-0083486288f4667
diff --git a/src/functions/compress.ts b/src/functions/compress.ts
index 47c4ec5b..a2b84306 100644
--- a/src/functions/compress.ts
+++ b/src/functions/compress.ts
@@ -1,6 +1,7 @@
import type { ISdk } from "iii-sdk";
import { getContext } from "iii-sdk";
import { readFileSync } from "node:fs";
+import { isManagedImagePath } from "../utils/image-store.js";
import type {
RawObservation,
CompressedObservation,
@@ -91,6 +92,9 @@ export function registerCompressFunction(
let mimeType = "image/png";
if (!data.raw.imageData.startsWith("/9j/") && !data.raw.imageData.startsWith("iVBOR")) {
+ if (!isManagedImagePath(data.raw.imageData)) {
+ throw new Error(`Refusing to read image outside managed store: ${data.raw.imageData}`);
+ }
const fileBuffer = readFileSync(data.raw.imageData);
base64Data = fileBuffer.toString("base64");
if (data.raw.imageData.endsWith(".jpg") || data.raw.imageData.endsWith(".jpeg")) mimeType = "image/jpeg";
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index e63f8886..3a552f03 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -112,16 +112,13 @@ export function registerObserveFunction(
const hiddenImage = extractImage(sanitizedRaw);
if (hiddenImage) {
raw.modality = (raw.toolInput || raw.toolOutput || raw.userPrompt) ? "mixed" : "image";
-
- if (hiddenImage.startsWith("data:image/") || hiddenImage.startsWith("iVBORw0KGgo") || hiddenImage.startsWith("/9j/")) {
- const { saveImageToDisk } = await import("../utils/image-store.js");
- raw.imageData = saveImageToDisk(hiddenImage);
- } else {
- raw.imageData = hiddenImage;
- }
}
}
+ const pendingImageData = (raw.modality === "image" || raw.modality === "mixed")
+ ? extractImage(typeof sanitizedRaw === "object" ? sanitizedRaw : undefined)
+ : undefined;
+
return withKeyedLock(`obs:${payload.sessionId}`, async () => {
if (maxObservationsPerSession && maxObservationsPerSession > 0) {
const existing = await kv.list(KV.observations(payload.sessionId));
@@ -133,6 +130,11 @@ export function registerObserveFunction(
}
}
+ if (pendingImageData && (pendingImageData.startsWith("data:image/") || pendingImageData.startsWith("iVBORw0KGgo") || pendingImageData.startsWith("/9j/"))) {
+ const { saveImageToDisk } = await import("../utils/image-store.js");
+ raw.imageData = saveImageToDisk(pendingImageData);
+ }
+
await kv.set(KV.observations(payload.sessionId), obsId, raw);
if (dedupMap && dedupHash) {
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 7f7e8bf9..341b77c1 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1211,11 +1211,25 @@ export function registerApiTriggers(
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const body = req.body as Record<string, unknown>;
- if (!body?.name) {
- return { status_code: 400, body: { error: "name is required" } };
+ const body = (req.body ?? {}) as Record<string, unknown>;
+ const name = typeof body.name === "string" ? body.name.trim() : "";
+ const steps = body.steps;
+ if (!name || !Array.isArray(steps) || steps.length === 0) {
+ return { status_code: 400, body: { error: "name and steps are required" } };
}
- const result = await sdk.trigger("mem::routine-create", body);
+ const payload = {
+ name,
+ description: typeof body.description === "string" ? body.description : undefined,
+ steps,
+ tags: Array.isArray(body.tags)
+ ? body.tags.filter((t): t is string => typeof t === "string")
+ : undefined,
+ frozen: typeof body.frozen === "boolean" ? body.frozen : undefined,
+ sourceProceduralIds: Array.isArray(body.sourceProceduralIds)
+ ? body.sourceProceduralIds.filter((id): id is string => typeof id === "string")
+ : undefined,
+ };
+ const result = await sdk.trigger("mem::routine-create", payload);
return { status_code: 201, body: result };
},
);
diff --git a/src/utils/image-store.ts b/src/utils/image-store.ts
index 94a34bee..65085694 100644
--- a/src/utils/image-store.ts
+++ b/src/utils/image-store.ts
@@ -1,9 +1,18 @@
import { homedir } from "node:os";
-import { join } from "node:path";
-import { writeFileSync, mkdirSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { writeFileSync, mkdirSync, existsSync, unlinkSync } from "node:fs";
import { createHash } from "node:crypto";
-const IMAGES_DIR = join(homedir(), ".agentmemory", "images");
+export const IMAGES_DIR = join(homedir(), ".agentmemory", "images");
+
+export function isManagedImagePath(filePath: string): boolean {
+ const resolved = resolve(filePath);
+ return resolved.startsWith(IMAGES_DIR + "/") || resolved === IMAGES_DIR;
+}
+
+function contentHash(data: string): string {
+ return createHash("sha256").update(data).digest("hex");
+}
export function saveImageToDisk(base64Data: string): string {
if (!base64Data) return "";
@@ -25,7 +34,7 @@ export function saveImageToDisk(base64Data: string): string {
ext = "jpg";
}
- const hash = createHash("sha256").update(cleanBase64).digest("hex");
+ const hash = contentHash(cleanBase64);
const filePath = join(IMAGES_DIR, `${hash}.${ext}`);
writeFileSync(filePath, Buffer.from(cleanBase64, "base64"));
@@ -34,8 +43,8 @@ export function saveImageToDisk(base64Data: string): string {
export function deleteImage(filePath: string | undefined): void {
if (!filePath) return;
+ if (!isManagedImagePath(filePath)) return;
try {
- const { existsSync, unlinkSync } = require("node:fs");
if (existsSync(filePath)) {
unlinkSync(filePath);
}
@@ -43,4 +52,3 @@ export function deleteImage(filePath: string | undefined): void {
console.error("[agentmemory] Failed to delete image context:", err);
}
}
-
diff --git a/test/multimodal.test.ts b/test/multimodal.test.ts
index 290ce920..653b9668 100644
--- a/test/multimodal.test.ts
+++ b/test/multimodal.test.ts
@@ -7,6 +7,12 @@ vi.mock("iii-sdk", () => ({
}),
}));
+vi.mock("../src/functions/search.js", () => ({
+ getSearchIndex: () => ({
+ add: vi.fn(),
+ }),
+}));
+
const mockTriggerVoid = vi.fn();
const mockSdk = { triggerVoid: mockTriggerVoid } as any;
@@ -35,9 +41,18 @@ import { registerObserveFunction } from "../src/functions/observe.js";
import { registerCompressFunction } from "../src/functions/compress.js";
import type { RawObservation, CompressedObservation, MemoryProvider } from "../src/types.js";
+const VALID_COMPRESS_XML = `<type>image</type>
+<title>Screenshot of Red Dot</title>
+<subtitle>Test image observation</subtitle>
+<facts><fact>Image shows a single red pixel on white background</fact></facts>
+<narrative>A vision model described a screenshot showing a red dot on a white background</narrative>
+<concepts><concept>testing</concept><concept>screenshot</concept></concepts>
+<files></files>
+<importance>5</importance>`;
+
describe("End-to-End Multimodal Flow", () => {
let savedImagePath: string | undefined;
-
+
afterAll(() => {
if (savedImagePath && existsSync(savedImagePath)) {
rmSync(savedImagePath);
@@ -63,14 +78,14 @@ describe("End-to-End Multimodal Flow", () => {
};
const res = await observeCallback(fakeIncomingData);
- const obsId = res.observationId;
+ expect(res.observationId).toBeDefined();
const obsList = await kv.list("mem:obs:test-session");
expect(obsList.length).toBe(1);
-
+
const raw = obsList[0] as RawObservation;
expect(raw.modality).toBe("mixed");
-
+
expect(raw.imageData).toBeDefined();
expect(typeof raw.imageData).toBe("string");
expect(existsSync(raw.imageData!)).toBe(true);
@@ -78,52 +93,55 @@ describe("End-to-End Multimodal Flow", () => {
savedImagePath = raw.imageData;
});
- it("Step 2 & 3: Vision model should receive the image and save a compressed version to KV", async () => {
+ it("Step 2 & 3: mem::compress should call the vision model and store compressed observation in KV", async () => {
const mockProvider: MemoryProvider = {
name: "mock-vision",
- compress: async (systemPrompt, userPrompt) => {
+ compress: async (_systemPrompt, userPrompt) => {
expect(userPrompt).toContain("TEST_VISION_RESULT: I see a red dot");
- return JSON.stringify({ type: "error", title: "Test", facts: [], narrative: "Narrative test", confidence: 0.99 });
+ return VALID_COMPRESS_XML;
},
summarize: async () => "",
- describeImage: async (base64, mimeType, prompt) => {
+ describeImage: async (_base64, _mimeType, _prompt) => {
return "TEST_VISION_RESULT: I see a red dot";
- }
+ },
};
let compressCallback: any = null;
- const sdkMocker = { ...mockSdk, registerFunction: vi.fn((config, cb) => { if (config.id === "mem::compress") compressCallback = cb; }) };
+ const sdkMocker = {
+ ...mockSdk,
+ registerFunction: vi.fn((config, cb) => {
+ if (config.id === "mem::compress") compressCallback = cb;
+ }),
+ };
registerCompressFunction(sdkMocker, kv, mockProvider);
+ expect(compressCallback).not.toBeNull();
+
const rawObsList = await kv.list("mem:obs:test-session");
const raw = rawObsList[0] as RawObservation;
-
- expect(raw).toHaveProperty("modality");
- expect(raw).toHaveProperty("imageData");
+
+ expect(raw.modality).toBeDefined();
expect(raw.imageData).toBe(savedImagePath);
-
- const finalCompressedObservation: CompressedObservation = {
- id: raw.id!,
- sessionId: raw.sessionId,
- timestamp: raw.timestamp,
- type: "error",
- title: "Final Output",
- facts: [],
- narrative: "Final text narrative.",
- concepts: ["testing"],
- files: [],
- importance: 5,
- confidence: 1,
- modality: raw.modality,
- imageDescription: "TEST_VISION_RESULT: I see a red dot",
- imageRef: raw.imageData
- };
-
- await kv.set("mem:memories", raw.id!, finalCompressedObservation);
- const memories = await kv.list("mem:memories");
- expect(memories.length).toBe(1);
- expect((memories[0] as CompressedObservation).imageRef).toBe(savedImagePath);
- expect((memories[0] as CompressedObservation).imageDescription).toBe("TEST_VISION_RESULT: I see a red dot");
+ const result = await compressCallback({
+ observationId: raw.id,
+ sessionId: raw.sessionId,
+ raw,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.compressed).toBeDefined();
+
+ const compressed = result.compressed as CompressedObservation;
+ expect(compressed.imageDescription).toBe("TEST_VISION_RESULT: I see a red dot");
+ expect(compressed.imageRef).toBe(savedImagePath);
+ expect(compressed.modality).toBe("mixed");
+ expect(compressed.title).toBe("Screenshot of Red Dot");
+ expect(compressed.narrative).toContain("red dot");
+
+ const stored = await kv.get<CompressedObservation>("mem:obs:test-session", raw.id!);
+ expect(stored).not.toBeNull();
+ expect(stored!.imageDescription).toBe("TEST_VISION_RESULT: I see a red dot");
+ expect(stored!.imageRef).toBe(savedImagePath);
});
});