// The memory tool (lab 06). // // This is an Anthropic-defined tool: we send only {type: "memory_20250818", name: "memory"} and // the model already knows its commands (view, create, str_replace, insert, delete, rename). Our // job is the backend. We still validate every command with Zod, exactly like our own tools. import { z } from 'zod'; import { defineTool, type Tool } from '../tools/tool.ts'; import type { MemoryStore } from './memory-store.ts'; const MemoryCommand = z.discriminatedUnion('command', [ z.object({ command: z.literal('view'), path: z.string(), view_range: z.array(z.number().int()).length(2).optional(), }), z.object({ command: z.literal('create'), path: z.string(), file_text: z.string() }), z.object({ command: z.literal('str_replace'), path: z.string(), old_str: z.string().min(1), // Optional in the API's spec: leaving it out deletes old_str. new_str: z.string().default(''), }), z.object({ command: z.literal('insert'), path: z.string(), insert_line: z.number().int(), insert_text: z.string(), }), z.object({ command: z.literal('delete'), path: z.string() }), z.object({ command: z.literal('rename'), old_path: z.string(), new_path: z.string() }), ]); export function memoryTool(store: MemoryStore): Tool { return defineTool({ name: 'memory', description: 'Anthropic memory tool (schema defined by the API).', definition: { type: 'memory_20250818', name: 'memory' }, input: MemoryCommand, summarize: (cmd) => cmd.command === 'rename' ? `memory rename ${cmd.old_path} -> ${cmd.new_path}` : `memory ${cmd.command} ${cmd.path}`, run: (cmd) => { switch (cmd.command) { case 'view': return store.view(cmd.path, cmd.view_range); case 'create': return store.create(cmd.path, cmd.file_text); case 'str_replace': return store.strReplace(cmd.path, cmd.old_str, cmd.new_str); case 'insert': return store.insert(cmd.path, cmd.insert_line, cmd.insert_text); case 'delete': return store.delete(cmd.path); case 'rename': return store.rename(cmd.old_path, cmd.new_path); } }, }); }