import { executeLocalModel } from './local-model-provider.js';
import { getTool, executeTool, formatToolsForOpenAI } from './tools.js';
export const testAgent = {
    async execute(input) {
        const sleepMs = typeof input?.sleep_ms === 'number' ? input.sleep_ms : 0;
        if (sleepMs > 0) {
            await new Promise((resolve) => setTimeout(resolve, sleepMs));
        }
        return {
            message: 'Hello from test agent!',
            input: input,
            timestamp: new Date().toISOString(),
            status: 'success'
        };
    }
};
export const echoAgent = {
    async execute(input) {
        return {
            echo: input,
            timestamp: new Date().toISOString()
        };
    }
};
export const gpt4Assistant = {
    async execute(input) {
        const { prompt, systemPrompt, temperature, maxTokens, conversationHistory, topP, frequencyPenalty, presencePenalty, tools: toolNames, useLocalModel, localModelProvider, localModelName, localModelUrl } = input.data || {};
        if (!prompt && (!conversationHistory || conversationHistory.length === 0)) {
            throw new Error('prompt is required');
        }
        if (useLocalModel && localModelProvider && localModelName) {
            return executeLocalModelAgent({
                prompt,
                systemPrompt,
                temperature,
                maxTokens,
                conversationHistory,
                topP,
                frequencyPenalty,
                presencePenalty,
                tools: toolNames,
                localModelProvider,
                localModelName,
                localModelUrl
            });
        }
        const apiKey = process.env['OPENAI_API_KEY'];
        if (!apiKey) {
            throw new Error('OpenAI API key not configured. Run "config" in the OS terminal.');
        }
        const messages = [];
        if (systemPrompt) {
            messages.push({ role: 'system', content: systemPrompt });
        }
        if (conversationHistory && Array.isArray(conversationHistory)) {
            messages.push(...conversationHistory);
        }
        if (prompt) {
            messages.push({ role: 'user', content: prompt });
        }
        const tools = [];
        const toolMap = {};
        if (toolNames && Array.isArray(toolNames) && toolNames.length > 0) {
            for (const toolName of toolNames) {
                const tool = getTool(toolName);
                if (tool) {
                    tools.push(tool);
                    toolMap[tool.name] = tool;
                }
            }
        }
        const maxCompletionTokens = maxTokens ? Math.max(1, Math.min(maxTokens, 4096)) : 1000;
        const requestBody = {
            model: 'gpt-4',
            messages,
            temperature: temperature ?? 0.7,
            max_tokens: maxCompletionTokens
        };
        if (topP !== undefined)
            requestBody.top_p = topP;
        if (frequencyPenalty !== undefined)
            requestBody.frequency_penalty = frequencyPenalty;
        if (presencePenalty !== undefined)
            requestBody.presence_penalty = presencePenalty;
        if (tools.length > 0) {
            requestBody.tools = formatToolsForOpenAI(tools);
            requestBody.tool_choice = 'auto';
        }
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify(requestBody)
        });
        if (!response.ok) {
            const error = await response.text();
            throw new Error(`OpenAI API error: ${response.status} - ${error}`);
        }
        const data = await response.json();
        const usage = data.usage || {};
        const choice = data.choices?.[0];
        if (choice?.message?.tool_calls && toolMap) {
            const toolResults = [];
            for (const toolCall of choice.message.tool_calls) {
                const toolName = toolCall.function.name;
                const toolArgs = JSON.parse(toolCall.function.arguments || '{}');
                const tool = toolMap[toolName];
                if (tool) {
                    try {
                        const result = await executeTool(toolName, toolArgs);
                        toolResults.push({
                            tool_call_id: toolCall.id,
                            role: 'tool',
                            name: toolName,
                            content: JSON.stringify(result)
                        });
                    }
                    catch (error) {
                        toolResults.push({
                            tool_call_id: toolCall.id,
                            role: 'tool',
                            name: toolName,
                            content: JSON.stringify({ error: error.message })
                        });
                    }
                }
            }
            if (toolResults.length > 0) {
                const followUpMessages = [...messages, choice.message, ...toolResults];
                const followUpResponse = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'gpt-4',
                        messages: followUpMessages,
                        temperature: temperature ?? 0.7,
                        max_tokens: maxCompletionTokens
                    })
                });
                if (followUpResponse.ok) {
                    const followUpData = await followUpResponse.json();
                    const followUpUsage = followUpData.usage || {};
                    return {
                        result: followUpData.choices?.[0]?.message?.content || 'No response',
                        model: followUpData.model,
                        usage: {
                            totalTokens: (usage.total_tokens || 0) + (followUpUsage.total_tokens || 0),
                            promptTokens: (usage.prompt_tokens || 0) + (followUpUsage.prompt_tokens || 0),
                            completionTokens: (usage.completion_tokens || 0) + (followUpUsage.completion_tokens || 0)
                        },
                        cost: calculateCost('gpt-4', (usage.total_tokens || 0) + (followUpUsage.total_tokens || 0)),
                        toolsUsed: toolResults.map(tr => tr.name)
                    };
                }
            }
        }
        return {
            result: choice?.message?.content || 'No response',
            model: data.model,
            usage: {
                totalTokens: usage.total_tokens || 0,
                promptTokens: usage.prompt_tokens || 0,
                completionTokens: usage.completion_tokens || 0
            },
            cost: calculateCost('gpt-4', usage.total_tokens || 0),
            toolsUsed: tools.length > 0 ? tools.map(t => t.name) : undefined
        };
    }
};
export const gpt35Assistant = {
    async execute(input) {
        const { prompt, systemPrompt, temperature, maxTokens, conversationHistory, topP, frequencyPenalty, presencePenalty, tools: toolNames, useLocalModel, localModelProvider, localModelName, localModelUrl } = input.data || {};
        if (!prompt && (!conversationHistory || conversationHistory.length === 0)) {
            throw new Error('prompt is required');
        }
        if (useLocalModel && localModelProvider && localModelName) {
            return executeLocalModelAgent({
                prompt,
                systemPrompt,
                temperature,
                maxTokens,
                conversationHistory,
                topP,
                frequencyPenalty,
                presencePenalty,
                tools: toolNames,
                localModelProvider,
                localModelName,
                localModelUrl
            });
        }
        const apiKey = process.env['OPENAI_API_KEY'];
        if (!apiKey) {
            throw new Error('OpenAI API key not configured. Run "config" in the OS terminal.');
        }
        const messages = [];
        if (systemPrompt) {
            messages.push({ role: 'system', content: systemPrompt });
        }
        if (conversationHistory && Array.isArray(conversationHistory)) {
            messages.push(...conversationHistory);
        }
        if (prompt) {
            messages.push({ role: 'user', content: prompt });
        }
        const tools = [];
        const toolMap = {};
        if (toolNames && Array.isArray(toolNames) && toolNames.length > 0) {
            for (const toolName of toolNames) {
                const tool = getTool(toolName);
                if (tool) {
                    tools.push(tool);
                    toolMap[tool.name] = tool;
                }
            }
        }
        const maxCompletionTokens = maxTokens ? Math.max(1, Math.min(maxTokens, 4096)) : 1000;
        const requestBody = {
            model: 'gpt-3.5-turbo',
            messages,
            temperature: temperature ?? 0.7,
            max_tokens: maxCompletionTokens
        };
        if (topP !== undefined)
            requestBody.top_p = topP;
        if (frequencyPenalty !== undefined)
            requestBody.frequency_penalty = frequencyPenalty;
        if (presencePenalty !== undefined)
            requestBody.presence_penalty = presencePenalty;
        if (tools.length > 0) {
            requestBody.tools = formatToolsForOpenAI(tools);
            requestBody.tool_choice = 'auto';
        }
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify(requestBody)
        });
        if (!response.ok) {
            const error = await response.text();
            throw new Error(`OpenAI API error: ${response.status} - ${error}`);
        }
        const data = await response.json();
        const usage = data.usage || {};
        const choice = data.choices?.[0];
        if (choice?.message?.tool_calls && toolMap) {
            const toolResults = [];
            for (const toolCall of choice.message.tool_calls) {
                const toolName = toolCall.function.name;
                const toolArgs = JSON.parse(toolCall.function.arguments || '{}');
                const tool = toolMap[toolName];
                if (tool) {
                    try {
                        const result = await executeTool(toolName, toolArgs);
                        toolResults.push({
                            tool_call_id: toolCall.id,
                            role: 'tool',
                            name: toolName,
                            content: JSON.stringify(result)
                        });
                    }
                    catch (error) {
                        toolResults.push({
                            tool_call_id: toolCall.id,
                            role: 'tool',
                            name: toolName,
                            content: JSON.stringify({ error: error.message })
                        });
                    }
                }
            }
            if (toolResults.length > 0) {
                const followUpMessages = [...messages, choice.message, ...toolResults];
                const followUpResponse = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'gpt-3.5-turbo',
                        messages: followUpMessages,
                        temperature: temperature ?? 0.7,
                        max_tokens: maxCompletionTokens
                    })
                });
                if (followUpResponse.ok) {
                    const followUpData = await followUpResponse.json();
                    const followUpUsage = followUpData.usage || {};
                    return {
                        result: followUpData.choices?.[0]?.message?.content || 'No response',
                        model: followUpData.model,
                        usage: {
                            totalTokens: (usage.total_tokens || 0) + (followUpUsage.total_tokens || 0),
                            promptTokens: (usage.prompt_tokens || 0) + (followUpUsage.prompt_tokens || 0),
                            completionTokens: (usage.completion_tokens || 0) + (followUpUsage.completion_tokens || 0)
                        },
                        cost: calculateCost('gpt-3.5-turbo', (usage.total_tokens || 0) + (followUpUsage.total_tokens || 0)),
                        toolsUsed: toolResults.map(tr => tr.name)
                    };
                }
            }
        }
        return {
            result: choice?.message?.content || 'No response',
            model: data.model,
            usage: {
                totalTokens: usage.total_tokens || 0,
                promptTokens: usage.prompt_tokens || 0,
                completionTokens: usage.completion_tokens || 0
            },
            cost: calculateCost('gpt-3.5-turbo', usage.total_tokens || 0),
            toolsUsed: tools.length > 0 ? tools.map(t => t.name) : undefined
        };
    }
};
async function executeLocalModelAgent(params) {
    const { prompt, systemPrompt, temperature, maxTokens, conversationHistory, topP, frequencyPenalty, presencePenalty, localModelProvider, localModelName, localModelUrl } = params;
    const messages = [];
    if (systemPrompt) {
        messages.push({ role: 'system', content: systemPrompt });
    }
    if (conversationHistory && Array.isArray(conversationHistory)) {
        messages.push(...conversationHistory);
    }
    if (prompt) {
        messages.push({ role: 'user', content: prompt });
    }
    const localConfig = {
        provider: localModelProvider,
        model: localModelName,
        ...(localModelUrl && { baseUrl: localModelUrl }),
        ...(temperature !== undefined && { temperature }),
        ...(maxTokens !== undefined && { maxTokens }),
        ...(topP !== undefined && { topP }),
        ...(frequencyPenalty !== undefined && { frequencyPenalty }),
        ...(presencePenalty !== undefined && { presencePenalty })
    };
    const result = await executeLocalModel(localConfig, messages);
    return {
        result: result.result,
        model: result.model,
        usage: result.usage,
        cost: 0,
        localModel: true
    };
}
function calculateCost(model, totalTokens) {
    const pricing = {
        'gpt-4': 0.03 / 1000,
        'gpt-4-turbo': 0.01 / 1000,
        'gpt-3.5-turbo': 0.0015 / 1000
    };
    const pricePerToken = pricing[model] || 0.01 / 1000;
    return totalTokens * pricePerToken;
}
export const agentRegistry = {
    'test': testAgent,
    'test-agent': testAgent,
    'echo': echoAgent,
    'gpt4-assistant': gpt4Assistant,
    'gpt35-assistant': gpt35Assistant,
    'gpt-4': gpt4Assistant,
    'gpt-3.5-turbo': gpt35Assistant
};
export function getAgent(name) {
    return agentRegistry[name];
}
//# sourceMappingURL=definitions-simple.js.map