"use strict";
// =============================================================================
// Pure Agent - System Prompt Assembly (3-Tier)
// Ported from Hermes agent/system_prompt.py
// =============================================================================
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildSystemPromptParts = buildSystemPromptParts;
exports.buildSystemPrompt = buildSystemPrompt;
exports.invalidateSystemPrompt = invalidateSystemPrompt;
exports.formatToolsForSystemMessage = formatToolsForSystemMessage;
exports.buildChildSystemPrompt = buildChildSystemPrompt;
const prompt_builder_1 = require("./prompt-builder");
const memory_store_1 = require("./memory-store");
const skill_utils_1 = require("./skill-utils");
const constants_1 = require("./constants");
// ---------------------------------------------------------------------------
// Build system prompt parts (Hermes assembly order)
// ---------------------------------------------------------------------------
function buildSystemPromptParts(agent) {
    const toolNames = agent.validToolNames;
    // ==== STABLE TIER (same for entire session) ====
    const stableParts = [];
    // 1. Identity (SOUL.md or default)
    stableParts.push((0, prompt_builder_1.getAgentIdentity)());
    // 2. Task completion guidance (when tools are available)
    if (toolNames.size > 0) {
        stableParts.push(constants_1.TASK_COMPLETION_GUIDANCE);
    }
    // 3. Tool-aware behavioral guidance (joined as one block)
    const toolGuidanceParts = [];
    if (toolNames.has('memory')) {
        toolGuidanceParts.push(constants_1.MEMORY_GUIDANCE);
    }
    if (toolNames.has('skills_list')) {
        toolGuidanceParts.push(constants_1.SKILLS_GUIDANCE);
    }
    if (toolGuidanceParts.length > 0) {
        stableParts.push(toolGuidanceParts.join('\n\n'));
    }
    // 3b. Multimodal file handling guidance
    if (toolNames.has('access_file') || toolNames.has('vision_analyze') || toolNames.has('parse_document')) {
        stableParts.push(constants_1.MULTIMODAL_GUIDANCE);
    }
    // 4. Tool-use enforcement (for matching models)
    const modelLower = agent.model.toLowerCase();
    const shouldEnforce = constants_1.TOOL_USE_ENFORCEMENT_MODELS.some(m => modelLower.includes(m));
    if (shouldEnforce) {
        stableParts.push(constants_1.TOOL_USE_ENFORCEMENT_GUIDANCE);
        // 5. Model-family operational guidance
        if (modelLower.includes('gemini') || modelLower.includes('gemma')) {
            stableParts.push(constants_1.GOOGLE_MODEL_OPERATIONAL_GUIDANCE);
        }
        else if (modelLower.includes('gpt') ||
            modelLower.includes('codex') ||
            modelLower.includes('grok')) {
            stableParts.push(constants_1.OPENAI_MODEL_EXECUTION_GUIDANCE);
        }
    }
    // 6. Skills system prompt (dynamic index)
    if (toolNames.has('skills_list')) {
        const skillsPrompt = buildSkillsSystemPrompt();
        if (skillsPrompt) {
            stableParts.push(skillsPrompt);
        }
    }
    // 7. Environment hints
    stableParts.push((0, prompt_builder_1.buildEnvironmentHints)(agent.workingDir));
    // 8. Platform hint
    stableParts.push(constants_1.PLATFORM_HINTS.webui || '');
    // ==== CONTEXT TIER (session-level) ====
    const contextParts = [];
    // 1. System message (if provided)
    if (agent.systemMessage) {
        contextParts.push(agent.systemMessage);
    }
    // 2. Context files
    const contextFiles = (0, prompt_builder_1.buildContextFilesPrompt)(agent.workingDir);
    if (contextFiles) {
        contextParts.push(contextFiles);
    }
    // ==== VOLATILE TIER (changes per session) ====
    const volatileParts = [];
    // 1. Memory snapshot
    if (toolNames.has('memory')) {
        try {
            const memStore = (0, memory_store_1.getMemoryStore)();
            const memoryBlock = memStore.formatForSystemPrompt('memory');
            if (memoryBlock)
                volatileParts.push(memoryBlock);
            const userBlock = memStore.formatForSystemPrompt('user');
            if (userBlock)
                volatileParts.push(userBlock);
        }
        catch { /* not initialized */ }
    }
    // 2. Timestamp + session info (date only for cache stability)
    const dateStr = new Date().toISOString().split('T')[0];
    const dayOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date().getDay()];
    volatileParts.push(`Conversation started: ${dayOfWeek}, ${dateStr}\n` +
        `Session ID: ${agent.sessionId}\n` +
        `Model: ${agent.model}`);
    return {
        stable: stableParts.filter(Boolean).join('\n\n'),
        context: contextParts.filter(Boolean).join('\n\n'),
        volatile: volatileParts.filter(Boolean).join('\n\n'),
    };
}
// ---------------------------------------------------------------------------
// Build skills system prompt (dynamic index)
// ---------------------------------------------------------------------------
function buildSkillsSystemPrompt() {
    try {
        const skills = (0, skill_utils_1.discoverAllSkills)();
        if (skills.length === 0)
            return '';
        const indexLines = [];
        const byCategory = {};
        for (const s of skills) {
            const cat = s.category || 'general';
            if (!byCategory[cat])
                byCategory[cat] = [];
            byCategory[cat].push(`  - ${s.name}: ${s.description.slice(0, 80)}`);
        }
        for (const [cat, items] of Object.entries(byCategory)) {
            indexLines.push(`Category: ${cat}`);
            indexLines.push(...items);
        }
        return (constants_1.SKILLS_SYSTEM_PROMPT_PREAMBLE + '\n\n' +
            '<available_skills>\n' +
            indexLines.join('\n') + '\n' +
            '</available_skills>\n\n' +
            'Only proceed without loading a skill if genuinely none are relevant to the task.');
    }
    catch {
        return '';
    }
}
// ---------------------------------------------------------------------------
// Build complete system prompt
// ---------------------------------------------------------------------------
function buildSystemPrompt(agent) {
    if (agent._cachedSystemPrompt) {
        return agent._cachedSystemPrompt;
    }
    const parts = buildSystemPromptParts(agent);
    const sections = [parts.stable, parts.context, parts.volatile].filter(s => s.trim().length > 0);
    const prompt = sections.join('\n\n');
    agent._cachedSystemPrompt = prompt;
    return prompt;
}
// ---------------------------------------------------------------------------
// Invalidate cache
// ---------------------------------------------------------------------------
function invalidateSystemPrompt(agent) {
    agent._cachedSystemPrompt = null;
}
// ---------------------------------------------------------------------------
// Format tools for system message (compact list)
// ---------------------------------------------------------------------------
function formatToolsForSystemMessage(tools) {
    if (tools.length === 0)
        return '';
    return tools.map(t => `${t.function.name}: ${t.function.description?.slice(0, 100) || ''}`).join('\n');
}
// ---------------------------------------------------------------------------
// Build child system prompt (for sub-agents)
// ---------------------------------------------------------------------------
function buildChildSystemPrompt(parentAgent, task, role = 'assistant') {
    return [
        (0, prompt_builder_1.getAgentIdentity)(),
        '',
        `## Delegated Task`,
        `You are a sub-agent working on a delegated task. Complete it fully and report results.`,
        ``,
        `**Task:** ${task}`,
        `**Role:** ${role}`,
        ``,
        (0, prompt_builder_1.buildEnvironmentHints)(parentAgent.workingDir),
        '',
        constants_1.TASK_COMPLETION_GUIDANCE,
    ].join('\n');
}
//# sourceMappingURL=system-prompt.js.map