"use strict";
// =============================================================================
// Pure Agent - Todo Tool
// Ported from Hermes tools/todo_tool.py
// =============================================================================
Object.defineProperty(exports, "__esModule", { value: true });
exports.TodoStore = void 0;
exports.clearTodoStore = clearTodoStore;
const tool_registry_1 = require("./tool-registry");
const result_types_1 = require("./result-types");
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const VALID_STATUSES = new Set(['pending', 'in_progress', 'completed', 'cancelled']);
class TodoStore {
    _items = [];
    write(todos, merge = false) {
        if (merge) {
            return this._mergeWrite(todos);
        }
        return this._replaceWrite(todos);
    }
    read() {
        return [...this._items];
    }
    hasItems() {
        return this._items.length > 0;
    }
    formatForInjection() {
        const active = this._items.filter(i => i.status === 'pending' || i.status === 'in_progress');
        if (active.length === 0)
            return null;
        const markers = {
            completed: '[x]',
            in_progress: '[>]',
            pending: '[ ]',
            cancelled: '[~]',
        };
        const lines = active.map(i => `${markers[i.status] || '[ ]'} ${i.id}: ${i.content}`);
        return `## Active TODO\n${lines.join('\n')}`;
    }
    _replaceWrite(todos) {
        // Dedupe by id (keep last occurrence)
        const seen = new Map();
        const order = [];
        for (const t of todos) {
            const id = String(t.id || '?');
            if (!seen.has(id))
                order.push(id);
            seen.set(id, t);
        }
        this._items = order.map(id => this._validate(seen.get(id)));
        return [...this._items];
    }
    _mergeWrite(todos) {
        const existingById = new Map();
        for (const item of this._items) {
            existingById.set(item.id, { ...item });
        }
        for (const t of todos) {
            const id = String(t.id || '?');
            const existing = existingById.get(id);
            if (existing) {
                // Update only provided fields
                if (t.content !== undefined)
                    existing.content = String(t.content);
                if (t.status !== undefined) {
                    existing.status = VALID_STATUSES.has(t.status) ? t.status : 'pending';
                }
            }
            else {
                // New item - add at end
                const validated = this._validate(t);
                existingById.set(id, validated);
                this._items.push(validated);
            }
        }
        // Rebuild preserving original order for existing items
        const merged = [];
        for (const item of this._items) {
            const updated = existingById.get(item.id);
            if (updated)
                merged.push(updated);
            existingById.delete(item.id);
        }
        // Append truly new items
        for (const [, item] of existingById) {
            if (!merged.find(m => m.id === item.id))
                merged.push(item);
        }
        this._items = merged;
        return [...this._items];
    }
    _validate(item) {
        return {
            id: String(item.id || '?'),
            content: String(item.content || '(no description)'),
            status: VALID_STATUSES.has(item.status) ? item.status : 'pending',
        };
    }
}
exports.TodoStore = TodoStore;
// ---------------------------------------------------------------------------
// Todo tool handler
// ---------------------------------------------------------------------------
const _stores = new Map();
function getStore(sessionId) {
    let store = _stores.get(sessionId);
    if (!store) {
        store = new TodoStore();
        _stores.set(sessionId, store);
    }
    return store;
}
async function todoHandler(args, context) {
    const { todos, merge = false } = args;
    const store = getStore(context.sessionId);
    if (todos && Array.isArray(todos)) {
        store.write(todos, merge);
    }
    const items = store.read();
    const summary = {
        total: items.length,
        pending: items.filter(i => i.status === 'pending').length,
        in_progress: items.filter(i => i.status === 'in_progress').length,
        completed: items.filter(i => i.status === 'completed').length,
        cancelled: items.filter(i => i.status === 'cancelled').length,
    };
    return (0, result_types_1.toolResult)({ todos: items, summary });
}
function clearTodoStore(sessionId) {
    if (sessionId)
        _stores.delete(sessionId);
    else
        _stores.clear();
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
tool_registry_1.registry.register({
    name: 'todo',
    toolset: 'todo',
    schema: {
        description: 'Manage your task list for the current session. Use this to track multi-step work, plan before acting, and show the user your progress. Write todos to create a plan; read by omitting todos.',
        parameters: {
            type: 'object',
            properties: {
                todos: {
                    type: 'array',
                    description: 'Task items to write. Omit to read current list.',
                    items: {
                        type: 'object',
                        properties: {
                            id: { type: 'string', description: 'Unique task identifier' },
                            content: { type: 'string', description: 'Task description' },
                            status: {
                                type: 'string',
                                enum: ['pending', 'in_progress', 'completed', 'cancelled'],
                                description: 'Task status',
                            },
                        },
                        required: ['id', 'content', 'status'],
                    },
                },
                merge: {
                    type: 'boolean',
                    description: 'If true, merge with existing todos (update by id, append new). If false (default), replace all.',
                    default: false,
                },
            },
            required: [],
        },
    },
    handler: todoHandler,
    isAsync: true,
    description: 'Manage task list',
    emoji: '📋',
});
//# sourceMappingURL=todo-tool.js.map