/**
 * OpenAI function calling adapter.
 *
 * Converts ToolDefinition[] into the format expected by OpenAI's
 * chat completions API `tools` parameter (type: "function" with parameters).
 */
/**
 * Transform tool definitions into OpenAI function calling format.
 */
export function toOpenAI(definitions) {
    const toolLookup = new Map();
    const tools = definitions.map((def) => {
        toolLookup.set(def.name, def);
        return {
            type: "function",
            function: {
                name: def.name,
                description: def.description,
                parameters: def.inputSchema,
            },
        };
    });
    const handleToolCall = async (name, args) => {
        const def = toolLookup.get(name);
        if (!def) {
            return JSON.stringify({ error: `Unknown tool: ${name}`, exitCode: 1 });
        }
        let parsed = Object.create(null);
        try {
            parsed = Object.assign(Object.create(null), JSON.parse(args));
        }
        catch {
            return JSON.stringify({ error: `Invalid JSON arguments for tool: ${name}`, exitCode: 1 });
        }
        const result = await def.execute(parsed);
        return JSON.stringify(result);
    };
    return { tools, handleToolCall };
}
