import type { FlowError, OutputParser } from "./types.js"; export function structuredPrompt(prompt: string): string { return `${prompt}\n\nYour final response is parsed by a program. Return only one valid JSON value, without markdown fences or additional prose.`; } export function parseOutput( text: string, parser: OutputParser, ): { ok: true; value: T } | { ok: false; error: FlowError } { let json: unknown; try { json = extractJson(text); } catch (cause) { return { ok: false, error: { code: "invalid_json", message: cause instanceof Error ? cause.message : "Agent output was not valid JSON", cause, }, }; } try { return { ok: true, value: parser.parse(json) }; } catch (cause) { return { ok: false, error: { code: "invalid_output", message: cause instanceof Error ? cause.message : "Agent output failed validation", cause, }, }; } } function extractJson(text: string): unknown { const trimmed = text.trim(); try { return JSON.parse(trimmed); } catch { const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); if (fenced?.[1]) return JSON.parse(fenced[1]); throw new Error("Agent output was not a single valid JSON value"); } }