/**
 * provider.ts — Agent harness Promptfoo custom provider.
 *
 * Handles agent-harness evaluation tasks by calling the Anthropic API
 * with the task prompt and returning the response. Sandbox provisioning
 * and teardown are handled by lifecycle extensions (beforeEach/afterEach),
 * not by the provider itself.
 *
 * Promptfoo config usage:
 *
 *   providers:
 *     - id: file://dist/agent-harness/provider.js
 *       label: "Agent Harness: My Task"
 *       config:
 *         allowedTools: ["Bash", "Read", "Write"]
 *         sandbox: { type: "tempdir" }
 *
 * Promptfoo loads this file and instantiates the default export class.
 */
import { config as loadDotenv } from "dotenv";
loadDotenv({
    override: true,
    path: new URL("../../.env", import.meta.url).pathname,
});
// ---------------------------------------------------------------------------
// Provider implementation
// ---------------------------------------------------------------------------
export default class AgentHarnessProvider {
    config;
    providerId;
    constructor(options) {
        this.providerId = options.id ?? "agent-harness";
        this.config = options.config ?? {};
    }
    id() {
        return this.providerId;
    }
    /**
     * Main Promptfoo provider entry point. Called for each test case.
     *
     * Sends the task prompt to the Anthropic API and returns the response.
     * The sandbox working directory is available in context.vars.__workingDir
     * (set by the beforeEach extension).
     */
    async callApi(prompt, context) {
        const apiKey = process.env.ANTHROPIC_API_KEY;
        if (!apiKey) {
            return {
                error: "ANTHROPIC_API_KEY not set. Required for agent-harness evaluation.",
            };
        }
        const model = this.config.model ?? "claude-sonnet-4-20250514";
        const maxTokens = this.config.maxTokens ?? 4096;
        const workingDir = context?.vars?.__workingDir;
        const systemPrompt = workingDir
            ? `You are an AI coding agent. Your working directory is: ${workingDir}\nComplete the following task.`
            : "You are an AI coding agent. Complete the following task.";
        try {
            const response = await fetch("https://api.anthropic.com/v1/messages", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "x-api-key": apiKey,
                    "anthropic-version": "2023-06-01",
                },
                body: JSON.stringify({
                    model,
                    max_tokens: maxTokens,
                    system: systemPrompt,
                    messages: [{ role: "user", content: prompt }],
                }),
            });
            if (!response.ok) {
                const errorBody = await response.text();
                return {
                    error: `Anthropic API error (${response.status}): ${errorBody}`,
                };
            }
            const data = (await response.json());
            const output = data.content
                .filter((block) => block.type === "text")
                .map((block) => block.text)
                .join("\n");
            return {
                output,
                tokenUsage: {
                    prompt: data.usage?.input_tokens,
                    completion: data.usage?.output_tokens,
                    total: (data.usage?.input_tokens ?? 0) + (data.usage?.output_tokens ?? 0),
                },
                metadata: {
                    model,
                    workingDir,
                    allowedTools: this.config.allowedTools,
                    sandboxType: this.config.sandbox?.type ?? "none",
                },
            };
        }
        catch (err) {
            const error = err;
            return { error: `Agent harness provider error: ${error.message}` };
        }
    }
}
