Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(memory): add persistent key-value storage for agents

Jiang Bohan8484ba6cb28c
diff --git a/src/agent/tools/memory/index.ts b/src/agent/tools/memory/index.ts
new file mode 100644
index 0000000000..f2d14e6eb2
--- /dev/null
+++ b/src/agent/tools/memory/index.ts
@@ -0,0 +1,6 @@
+/**
+ * Memory Tools Module
+ */
+
+export { createMemoryTools } from "./memory-tools.js";
+export type { MemoryEntry, MemoryStorageOptions, MemoryListResult } from "./types.js";
diff --git a/src/agent/tools/memory/memory-tools.ts b/src/agent/tools/memory/memory-tools.ts
new file mode 100644
index 0000000000..19fe580494
--- /dev/null
+++ b/src/agent/tools/memory/memory-tools.ts
@@ -0,0 +1,175 @@
+/**
+ * Memory Tools
+ *
+ * Provides persistent key-value storage for agents.
+ */
+
+import { Type } from "@sinclair/typebox";
+import type { AgentTool } from "@mariozechner/pi-agent-core";
+import { memoryDelete, memoryGet, memoryList, memorySet, validateKey } from "./storage.js";
+import type { MemoryStorageOptions } from "./types.js";
+
+// ============================================================================
+// Schemas
+// ============================================================================
+
+const MemoryGetSchema = Type.Object({
+ key: Type.String({ description: "The key to retrieve" }),
+});
+
+const MemorySetSchema = Type.Object({
+ key: Type.String({ description: "The key to set (alphanumeric, underscore, dot, hyphen)" }),
+ value: Type.Unknown({ description: "The value to store (will be JSON serialized)" }),
+ description: Type.Optional(
+ Type.String({ description: "Optional description of this memory entry" }),
+ ),
+});
+
+const MemoryDeleteSchema = Type.Object({
+ key: Type.String({ description: "The key to delete" }),
+});
+
+const MemoryListSchema = Type.Object({
+ prefix: Type.Optional(Type.String({ description: "Filter keys by prefix" })),
+ limit: Type.Optional(Type.Number({ description: "Maximum number of keys to return (default 100)" })),
+});
+
+// ============================================================================
+// Helper
+// ============================================================================
+
+function jsonResult<T>(data: T): {
+ content: Array<{ type: "text"; text: string }>;
+ details: T;
+} {
+ return {
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
+ details: data,
+ };
+}
+
+// ============================================================================
+// Tools
+// ============================================================================
+
+export function createMemoryGetTool(
+ options: MemoryStorageOptions,
+): AgentTool<typeof MemoryGetSchema> {
+ return {
+ name: "memory_get",
+ label: "Memory Get",
+ description: "Retrieve a value from persistent memory by key.",
+ parameters: MemoryGetSchema,
+ execute: async (_toolCallId, params) => {
+ const key = typeof params.key === "string" ? params.key.trim() : "";
+
+ const validation = validateKey(key);
+ if (!validation.valid) {
+ return jsonResult({ found: false, error: validation.error });
+ }
+
+ const result = memoryGet(key, options);
+ if (!result.found) {
+ return jsonResult({ found: false, key });
+ }
+
+ return jsonResult({
+ found: true,
+ key,
+ value: result.entry.value,
+ description: result.entry.description,
+ updatedAt: result.entry.updatedAt,
+ });
+ },
+ };
+}
+
+export function createMemorySetTool(
+ options: MemoryStorageOptions,
+): AgentTool<typeof MemorySetSchema> {
+ return {
+ name: "memory_set",
+ label: "Memory Set",
+ description:
+ "Store a value in persistent memory. The value will be JSON serialized. " +
+ "Keys can contain letters, numbers, underscores, dots, and hyphens.",
+ parameters: MemorySetSchema,
+ execute: async (_toolCallId, params) => {
+ const key = typeof params.key === "string" ? params.key.trim() : "";
+ const value = params.value;
+ const description = typeof params.description === "string" ? params.description : undefined;
+
+ const result = memorySet(key, value, description, options);
+ if (!result.success) {
+ return jsonResult({ success: false, error: result.error });
+ }
+
+ return jsonResult({ success: true, key });
+ },
+ };
+}
+
+export function createMemoryDeleteTool(
+ options: MemoryStorageOptions,
+): AgentTool<typeof MemoryDeleteSchema> {
+ return {
+ name: "memory_delete",
+ label: "Memory Delete",
+ description: "Delete a value from persistent memory by key.",
+ parameters: MemoryDeleteSchema,
+ execute: async (_toolCallId, params) => {
+ const key = typeof params.key === "string" ? params.key.trim() : "";
+
+ const validation = validateKey(key);
+ if (!validation.valid) {
+ return jsonResult({ success: false, error: validation.error });
+ }
+
+ const result = memoryDelete(key, options);
+ if (!result.success) {
+ return jsonResult({ success: false, error: result.error });
+ }
+
+ return jsonResult({ success: true, key, existed: result.existed });
+ },
+ };
+}
+
+export function createMemoryListTool(
+ options: MemoryStorageOptions,
+): AgentTool<typeof MemoryListSchema> {
+ return {
+ name: "memory_list",
+ label: "Memory List",
+ description:
+ "List all keys in persistent memory, sorted by most recently updated. " +
+ "Optionally filter by prefix.",
+ parameters: MemoryListSchema,
+ execute: async (_toolCallId, params) => {
+ const prefix = typeof params.prefix === "string" ? params.prefix : undefined;
+ const limit = typeof params.limit === "number" ? params.limit : undefined;
+
+ const result = memoryList(prefix, limit, options);
+
+ return jsonResult({
+ keys: result.keys,
+ total: result.total,
+ truncated: result.truncated,
+ });
+ },
+ };
+}
+
+/**
+ * Create all memory tools for a profile
+ */
+export function createMemoryTools(
+ options: MemoryStorageOptions,
+): Array<AgentTool<any>> {
+ return [
+ createMemoryGetTool(options),
+ createMemorySetTool(options),
+ createMemoryDeleteTool(options),
+ createMemoryListTool(options),
+ ];
+}
diff --git a/src/agent/tools/memory/storage.ts b/src/agent/tools/memory/storage.ts
new file mode 100644
index 0000000000..1bfd57cb08
--- /dev/null
+++ b/src/agent/tools/memory/storage.ts
@@ -0,0 +1,239 @@
+/**
+ * Memory Storage Layer
+ *
+ * Handles file-based storage for agent memory in the profile directory.
+ */
+
+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { getProfileDir } from "../../profile/storage.js";
+import {
+ DEFAULT_LIST_LIMIT,
+ KEY_PATTERN,
+ MAX_KEY_LENGTH,
+ MAX_LIST_LIMIT,
+ MAX_VALUE_SIZE,
+ type MemoryEntry,
+ type MemoryListResult,
+ type MemoryStorageOptions,
+} from "./types.js";
+
+/**
+ * Validate a memory key
+ */
+export function validateKey(key: string): { valid: true } | { valid: false; error: string } {
+ if (!key || typeof key !== "string") {
+ return { valid: false, error: "Key is required" };
+ }
+
+ const trimmed = key.trim();
+ if (trimmed.length === 0) {
+ return { valid: false, error: "Key cannot be empty" };
+ }
+
+ if (trimmed.length > MAX_KEY_LENGTH) {
+ return { valid: false, error: `Key exceeds maximum length of ${MAX_KEY_LENGTH}` };
+ }
+
+ if (!KEY_PATTERN.test(trimmed)) {
+ return {
+ valid: false,
+ error: "Key can only contain letters, numbers, underscores, dots, and hyphens",
+ };
+ }
+
+ return { valid: true };
+}
+
+/**
+ * Get the memory directory for a profile
+ */
+export function getMemoryDir(options: MemoryStorageOptions): string {
+ const profileDir = getProfileDir(options.profileId, { baseDir: options.baseDir });
+ return join(profileDir, "memory");
+}
+
+/**
+ * Ensure the memory directory exists
+ */
+export function ensureMemoryDir(options: MemoryStorageOptions): string {
+ const memoryDir = getMemoryDir(options);
+ if (!existsSync(memoryDir)) {
+ mkdirSync(memoryDir, { recursive: true });
+ }
+ return memoryDir;
+}
+
+/**
+ * Get the file path for a memory key
+ */
+function getKeyFilePath(key: string, options: MemoryStorageOptions): string {
+ const memoryDir = getMemoryDir(options);
+ // Sanitize key for filename (replace dots with double underscore to avoid extension issues)
+ const safeKey = key.replace(/\./g, "__DOT__");
+ return join(memoryDir, `${safeKey}.json`);
+}
+
+/**
+ * Decode a sanitized filename back to the original key
+ */
+function decodeKeyFromFilename(filename: string): string {
+ // Remove .json extension and decode
+ const base = filename.replace(/\.json$/, "");
+ return base.replace(/__DOT__/g, ".");
+}
+
+/**
+ * Get a memory value by key
+ */
+export function memoryGet(
+ key: string,
+ options: MemoryStorageOptions,
+): { found: true; entry: MemoryEntry } | { found: false } {
+ const validation = validateKey(key);
+ if (!validation.valid) {
+ return { found: false };
+ }
+
+ const filePath = getKeyFilePath(key.trim(), options);
+ if (!existsSync(filePath)) {
+ return { found: false };
+ }
+
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ const entry = JSON.parse(content) as MemoryEntry;
+ return { found: true, entry };
+ } catch {
+ return { found: false };
+ }
+}
+
+/**
+ * Set a memory value
+ */
+export function memorySet(
+ key: string,
+ value: unknown,
+ description: string | undefined,
+ options: MemoryStorageOptions,
+): { success: true } | { success: false; error: string } {
+ const validation = validateKey(key);
+ if (!validation.valid) {
+ return { success: false, error: validation.error };
+ }
+
+ // Check value size
+ const serialized = JSON.stringify(value);
+ if (serialized.length > MAX_VALUE_SIZE) {
+ return { success: false, error: `Value exceeds maximum size of ${MAX_VALUE_SIZE} bytes` };
+ }
+
+ const trimmedKey = key.trim();
+ ensureMemoryDir(options);
+
+ const now = Date.now();
+ const existing = memoryGet(trimmedKey, options);
+
+ const entry: MemoryEntry = {
+ value,
+ description: description?.trim() || undefined,
+ createdAt: existing.found ? existing.entry.createdAt : now,
+ updatedAt: now,
+ };
+
+ const filePath = getKeyFilePath(trimmedKey, options);
+
+ try {
+ writeFileSync(filePath, JSON.stringify(entry, null, 2), "utf-8");
+ return { success: true };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { success: false, error: `Failed to write memory: ${message}` };
+ }
+}
+
+/**
+ * Delete a memory key
+ */
+export function memoryDelete(
+ key: string,
+ options: MemoryStorageOptions,
+): { success: true; existed: boolean } | { success: false; error: string } {
+ const validation = validateKey(key);
+ if (!validation.valid) {
+ return { success: false, error: validation.error };
+ }
+
+ const filePath = getKeyFilePath(key.trim(), options);
+ const existed = existsSync(filePath);
+
+ if (existed) {
+ try {
+ rmSync(filePath);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { success: false, error: `Failed to delete memory: ${message}` };
+ }
+ }
+
+ return { success: true, existed };
+}
+
+/**
+ * List memory keys
+ */
+export function memoryList(
+ prefix: string | undefined,
+ limit: number | undefined,
+ options: MemoryStorageOptions,
+): MemoryListResult {
+ const memoryDir = getMemoryDir(options);
+
+ if (!existsSync(memoryDir)) {
+ return { keys: [], total: 0, truncated: false };
+ }
+
+ const effectiveLimit = Math.min(
+ Math.max(1, limit ?? DEFAULT_LIST_LIMIT),
+ MAX_LIST_LIMIT,
+ );
+
+ try {
+ const files = readdirSync(memoryDir).filter((f) => f.endsWith(".json"));
+ const entries: Array<{ key: string; description?: string; updatedAt: number }> = [];
+
+ for (const file of files) {
+ const key = decodeKeyFromFilename(file);
+
+ // Apply prefix filter
+ if (prefix && !key.startsWith(prefix)) {
+ continue;
+ }
+
+ const filePath = join(memoryDir, file);
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ const entry = JSON.parse(content) as MemoryEntry;
+ entries.push({
+ key,
+ description: entry.description,
+ updatedAt: entry.updatedAt,
+ });
+ } catch {
+ // Skip invalid files
+ }
+ }
+
+ // Sort by updatedAt descending (most recent first)
+ entries.sort((a, b) => b.updatedAt - a.updatedAt);
+
+ const total = entries.length;
+ const truncated = total > effectiveLimit;
+ const keys = entries.slice(0, effectiveLimit);
+
+ return { keys, total, truncated };
+ } catch {
+ return { keys: [], total: 0, truncated: false };
+ }
+}
diff --git a/src/agent/tools/memory/types.ts b/src/agent/tools/memory/types.ts
new file mode 100644
index 0000000000..81912eed95
--- /dev/null
+++ b/src/agent/tools/memory/types.ts
@@ -0,0 +1,67 @@
+/**
+ * Memory Tool Type Definitions
+ */
+
+/** Memory entry stored in JSON file */
+export interface MemoryEntry {
+ /** The stored value */
+ value: unknown;
+ /** Optional description of this memory entry */
+ description?: string;
+ /** Timestamp when created */
+ createdAt: number;
+ /** Timestamp when last updated */
+ updatedAt: number;
+}
+
+/** Memory index structure */
+export interface MemoryIndex {
+ /** Version for future migrations */
+ version: 1;
+ /** Map of key to metadata */
+ keys: Record<string, MemoryKeyMeta>;
+}
+
+/** Metadata for each key in the index */
+export interface MemoryKeyMeta {
+ /** Optional description */
+ description?: string;
+ /** Created timestamp */
+ createdAt: number;
+ /** Updated timestamp */
+ updatedAt: number;
+}
+
+/** Options for memory storage */
+export interface MemoryStorageOptions {
+ /** Profile ID (required for storage path) */
+ profileId: string;
+ /** Base directory for profiles */
+ baseDir?: string;
+}
+
+/** Result from memory_list */
+export interface MemoryListResult {
+ keys: Array<{
+ key: string;
+ description?: string;
+ updatedAt: number;
+ }>;
+ total: number;
+ truncated: boolean;
+}
+
+/** Valid key pattern: alphanumeric, underscore, dot, hyphen */
+export const KEY_PATTERN = /^[a-zA-Z0-9_.-]+$/;
+
+/** Maximum key length */
+export const MAX_KEY_LENGTH = 128;
+
+/** Maximum value size in bytes (1MB) */
+export const MAX_VALUE_SIZE = 1024 * 1024;
+
+/** Default list limit */
+export const DEFAULT_LIST_LIMIT = 100;
+
+/** Maximum list limit */
+export const MAX_LIST_LIMIT = 1000;