/**
 * Memory tool - allows the agent to save, update, delete, and recall
 * persistent memories about the user across sessions.
 */
import { Text } from "@dotkaio/avis-tui";
import { Type } from "@sinclair/typebox";
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
const memorySchema = Type.Object({
    action: Type.Union([
        Type.Literal("create"),
        Type.Literal("update"),
        Type.Literal("delete"),
        Type.Literal("list"),
        Type.Literal("search"),
    ], {
        description: "Action to perform: create (save new memory), update (modify existing), delete (remove), list (show all), search (find by query)",
    }),
    content: Type.Optional(Type.String({
        description: "Memory content (required for create/update). Keep concise and factual.",
    })),
    id: Type.Optional(Type.String({
        description: "Memory ID (required for update/delete)",
    })),
    tags: Type.Optional(Type.Array(Type.String(), {
        description: 'Optional tags for categorization (e.g., ["preference", "coding-style"])',
    })),
    query: Type.Optional(Type.String({
        description: "Search query (for search action)",
    })),
});
function ok(text) {
    return { content: [{ type: "text", text }], details: undefined };
}
function err(text) {
    return { content: [{ type: "text", text }], details: undefined, isError: true };
}
export function createMemoryToolDefinition(memoryManager) {
    return {
        name: "memory",
        label: "memory",
        description: "Save, update, delete, or recall persistent memories about the user. Use this to remember user preferences, project conventions, frequently used paths, coding style, and other facts that should persist across conversations. Proactively save memories when you learn something important about the user.",
        parameters: memorySchema,
        promptSnippet: "Save, update, delete, or search persistent user memories across sessions",
        promptGuidelines: [
            "When you learn important user preferences, project conventions, or patterns, proactively save them with the memory tool",
            "Keep memories concise, factual, and actionable - avoid storing transient task details",
        ],
        async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
            const { action, content, id, tags, query } = params;
            switch (action) {
                case "create": {
                    if (!content)
                        return err("Error: content is required for create action");
                    const memory = memoryManager.create(content, tags);
                    // Trigger async graph rebuild (non-blocking)
                    memoryManager.rebuildGraphIfNeeded().catch(() => { });
                    return ok(`Memory saved (id: ${memory.id}):\n${memory.content}`);
                }
                case "update": {
                    if (!id)
                        return err("Error: id is required for update action");
                    const updated = memoryManager.update(id, content, tags);
                    if (!updated)
                        return err(`Error: memory with id "${id}" not found`);
                    memoryManager.rebuildGraphIfNeeded().catch(() => { });
                    return ok(`Memory updated (id: ${updated.id}):\n${updated.content}`);
                }
                case "delete": {
                    if (!id)
                        return err("Error: id is required for delete action");
                    const deleted = memoryManager.delete(id);
                    if (!deleted)
                        return err(`Error: memory with id "${id}" not found`);
                    memoryManager.rebuildGraphIfNeeded().catch(() => { });
                    return ok(`Memory deleted (id: ${id})`);
                }
                case "list": {
                    const memories = memoryManager.list();
                    if (memories.length === 0)
                        return ok("No memories stored yet.");
                    const lines = memories.map((m) => {
                        const t = m.tags.length > 0 ? ` [${m.tags.join(", ")}]` : "";
                        return `${m.id}: ${m.content}${t}`;
                    });
                    return ok(`${memories.length} memories:\n\n${lines.join("\n")}`);
                }
                case "search": {
                    if (!query)
                        return err("Error: query is required for search action");
                    const results = memoryManager.search(query);
                    if (results.length === 0)
                        return ok(`No memories matching "${query}"`);
                    const lines = results.map((m) => {
                        const t = m.tags.length > 0 ? ` [${m.tags.join(", ")}]` : "";
                        return `${m.id}: ${m.content}${t}`;
                    });
                    return ok(`${results.length} memories found:\n\n${lines.join("\n")}`);
                }
                default:
                    return err(`Unknown action: ${action}`);
            }
        },
        renderCall(args, _theme, _context) {
            const text = `memory ${args.action}${args.content ? `: ${args.content.slice(0, 80)}` : ""}${args.id ? ` (id: ${args.id})` : ""}`;
            return new Text(text);
        },
        renderResult(result, _options, _theme, _context) {
            const text = result.content.map((c) => ("text" in c ? c.text : "")).join("");
            return new Text(text);
        },
    };
}
export function createMemoryTool(memoryManager) {
    return wrapToolDefinition(createMemoryToolDefinition(memoryManager));
}
//# sourceMappingURL=memory.js.map