"use strict";
// =============================================================================
// Pure Agent - Cronjob Tool
// Ported from Hermes tools/cronjob_tools.py
// =============================================================================
Object.defineProperty(exports, "__esModule", { value: true });
const tool_registry_1 = require("./tool-registry");
const result_types_1 = require("./result-types");
const jobs_1 = require("./cron/jobs");
const scheduler_1 = require("./cron/scheduler");
// ---------------------------------------------------------------------------
// Cron prompt injection scanning
// ---------------------------------------------------------------------------
const INJECTION_PATTERNS = [
    'ignore previous instructions',
    'ignore all previous',
    'you are now',
    'system prompt:',
    '<system>',
    ']]>',
    'cat .env',
    'rm -rf /',
];
function scanCronPrompt(prompt) {
    const lower = prompt.toLowerCase();
    for (const pattern of INJECTION_PATTERNS) {
        if (lower.includes(pattern)) {
            return `Prompt blocked: contains unsafe pattern "${pattern}"`;
        }
    }
    return null;
}
// ---------------------------------------------------------------------------
// Cronjob tool handler
// ---------------------------------------------------------------------------
async function cronjobHandler(args, context) {
    const { action, job_id, prompt, schedule, name, repeat, deliver, skills, model, script, no_agent, workdir, } = args;
    switch (action) {
        case 'create': {
            if (!prompt && !script)
                return (0, result_types_1.toolError)('Provide prompt or script');
            if (!schedule)
                return (0, result_types_1.toolError)('Missing required parameter: schedule');
            // Security scan
            if (prompt) {
                const threat = scanCronPrompt(prompt);
                if (threat)
                    return (0, result_types_1.toolError)(threat);
            }
            // Validate schedule
            const parsed = (0, jobs_1.parseSchedule)(schedule);
            if (!parsed)
                return (0, result_types_1.toolError)(`Invalid schedule: ${schedule}`);
            const job = (0, jobs_1.createJob)({
                prompt,
                schedule,
                name,
                repeat,
                deliver,
                skills: skills ? (Array.isArray(skills) ? skills : [skills]) : undefined,
                model,
                script,
                no_agent,
                workdir: workdir || context.workingDir,
            });
            return (0, result_types_1.toolResult)({
                success: true,
                action: 'created',
                job: {
                    id: job.id,
                    name: job.name,
                    schedule: job.schedule_display,
                    next_run_at: job.next_run_at,
                    enabled: job.enabled,
                },
            });
        }
        case 'list': {
            const jobs = (0, jobs_1.listJobs)(true);
            return (0, result_types_1.toolResult)({
                jobs: jobs.map(j => ({
                    id: j.id,
                    name: j.name,
                    schedule: j.schedule_display,
                    enabled: j.enabled,
                    state: j.state,
                    next_run_at: j.next_run_at,
                    last_run_at: j.last_run_at,
                    last_status: j.last_status,
                    repeat_completed: j.repeat.completed,
                    repeat_times: j.repeat.times,
                })),
                count: jobs.length,
            });
        }
        case 'update': {
            if (!job_id)
                return (0, result_types_1.toolError)('Missing job_id');
            const updates = {};
            if (prompt !== undefined)
                updates.prompt = prompt;
            if (schedule !== undefined)
                updates.schedule = (0, jobs_1.parseSchedule)(schedule);
            if (name !== undefined)
                updates.name = name;
            if (model !== undefined)
                updates.model = model;
            if (deliver !== undefined)
                updates.deliver = deliver;
            if (skills !== undefined)
                updates.skills = Array.isArray(skills) ? skills : [skills];
            const updated = (0, jobs_1.updateJob)(job_id, updates);
            if (!updated)
                return (0, result_types_1.toolError)(`Job not found: ${job_id}`);
            return (0, result_types_1.toolResult)({ success: true, action: 'updated', job_id: updated.id, name: updated.name });
        }
        case 'pause': {
            if (!job_id)
                return (0, result_types_1.toolError)('Missing job_id');
            const paused = (0, jobs_1.pauseJob)(job_id);
            if (!paused)
                return (0, result_types_1.toolError)(`Job not found: ${job_id}`);
            return (0, result_types_1.toolResult)({ success: true, action: 'paused', job_id: paused.id });
        }
        case 'resume': {
            if (!job_id)
                return (0, result_types_1.toolError)('Missing job_id');
            const resumed = (0, jobs_1.resumeJob)(job_id);
            if (!resumed)
                return (0, result_types_1.toolError)(`Job not found: ${job_id}`);
            return (0, result_types_1.toolResult)({ success: true, action: 'resumed', job_id: resumed.id, next_run_at: resumed.next_run_at });
        }
        case 'remove': {
            if (!job_id)
                return (0, result_types_1.toolError)('Missing job_id');
            const removed = (0, jobs_1.removeJob)(job_id);
            if (!removed)
                return (0, result_types_1.toolError)(`Job not found: ${job_id}`);
            return (0, result_types_1.toolResult)({ success: true, action: 'removed', job_id });
        }
        case 'run': {
            if (!job_id)
                return (0, result_types_1.toolError)('Missing job_id');
            const triggered = (0, jobs_1.triggerJob)(job_id);
            if (!triggered)
                return (0, result_types_1.toolError)(`Job not found: ${job_id}`);
            // Run tick to execute the triggered job
            const executed = await (0, scheduler_1.tick)();
            return (0, result_types_1.toolResult)({ success: true, action: 'triggered', job_id: triggered.id, executed });
        }
        default:
            return (0, result_types_1.toolError)(`Unknown action: ${action}. Valid: create, list, update, pause, resume, remove, run`);
    }
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
tool_registry_1.registry.register({
    name: 'cronjob',
    toolset: 'cronjob',
    schema: {
        description: `Manage scheduled cron jobs. Jobs can run prompts or scripts on a schedule (once, interval, or cron expression). Use action="create" to schedule, "list" to see all, "pause"/"resume" to control, "remove" to delete, "run" to trigger immediately.`,
        parameters: {
            type: 'object',
            properties: {
                action: {
                    type: 'string',
                    enum: ['create', 'list', 'update', 'pause', 'resume', 'remove', 'run'],
                    description: 'Action to perform',
                },
                job_id: { type: 'string', description: 'Job ID (for update/pause/resume/remove/run)' },
                prompt: { type: 'string', description: 'Prompt for the agent to execute' },
                schedule: {
                    type: 'string',
                    description: 'Schedule: "30m" (once after 30min), "every 2h" (interval), "0 9 * * *" (cron)',
                },
                name: { type: 'string', description: 'Job name' },
                repeat: { type: 'number', description: 'Max number of runs (null = infinite)' },
                deliver: { type: 'string', description: 'Delivery target: "local", "telegram", etc.' },
                skills: {
                    type: 'array',
                    items: { type: 'string' },
                    description: 'Skills to load for this job',
                },
                model: { type: 'string', description: 'Model override for this job' },
                script: { type: 'string', description: 'Script path to execute before the agent' },
                no_agent: { type: 'boolean', description: 'If true, only run the script (no LLM agent)' },
                workdir: { type: 'string', description: 'Working directory for the job' },
            },
            required: ['action'],
        },
    },
    handler: cronjobHandler,
    isAsync: true,
    description: 'Manage cron jobs',
    emoji: '⏰',
});
// Auto-register
//# sourceMappingURL=cron-tool.js.map