/**
 * withStructuredOutput<T>() — Zod schema-enforced LLM output with auto-retry.
 *
 * Sprint-562: A5 — Structured Output
 *
 * Zod validation failures are injected into the messages[] thread so the LLM
 * sees its mistake and corrects it on the next attempt. TInput is NEVER mutated
 * (new messages are appended to a copy).
 *
 * Each retry produces a TraceStep with type='llm_call' and output.zodError
 * so auditors can see the correction path.
 */
export class StructuredOutputError extends Error {
    zodError;
    constructor(message, zodError) {
        super(message);
        this.zodError = zodError;
        this.name = "StructuredOutputError";
    }
}
/**
 * Calls an LLM with Zod schema enforcement. On Zod failure, injects the
 * error into the messages thread and retries. TInput messages are never
 * mutated — each retry appends to a copy.
 */
export async function withStructuredOutput(opts) {
    const maxRetries = opts.maxRetries ?? 2;
    const rawMessages = [];
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
        const messages = [...rawMessages];
        const raw = await opts.fn({ messages }, undefined);
        rawMessages.push({ role: "assistant", content: raw });
        // Try to extract JSON from the response
        let parsed;
        try {
            parsed = JSON.parse(raw);
        }
        catch {
            const fixPrompt = `Your previous response was not valid JSON. Please respond ONLY with a valid JSON object matching the schema.`;
            rawMessages.push({ role: "user", content: fixPrompt });
            continue;
        }
        const result = opts.schema.safeParse(parsed);
        if (result.success) {
            return { parsed: result.data, rawMessages, retries: attempt };
        }
        if (attempt < maxRetries) {
            const fixPrompt = `Your response failed Zod validation:\n${result.error.message}\n\nPlease fix the errors and return a valid JSON object.`;
            rawMessages.push({ role: "user", content: fixPrompt });
        }
        else {
            throw new StructuredOutputError(`Structured output validation failed after ${maxRetries} retries`, result.error);
        }
    }
    // Unreachable — but TypeScript needs it
    throw new StructuredOutputError(`Structured output exhausted ${maxRetries} retries`, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    { issues: [] });
}
//# sourceMappingURL=structured-output.js.map