{"version":3,"sources":["../src/index.ts","../src/dirty-parser/extract.ts","../src/dirty-parser/heuristics.ts","../src/dirty-parser/balance.ts","../src/dirty-parser/index.ts","../src/validation/index.ts","../src/retry/index.ts","../src/telemetry.ts","../src/guard.ts","../src/providers/forge.ts","../src/providers/fallback.ts"],"sourcesContent":["/**\r\n * # Reforge\r\n *\r\n * Raw LLM output reforged into clean data. Low-latency deterministic\r\n * validation and native JSON repair.\r\n *\r\n * ## Quick Start\r\n *\r\n * ```ts\r\n * import { z } from 'zod';\r\n * import { guard } from 'reforge-ai';\r\n *\r\n * const UserSchema = z.object({\r\n *   name: z.string(),\r\n *   age:  z.number(),\r\n * });\r\n *\r\n * // Raw LLM output — markdown-wrapped with a trailing comma:\r\n * const raw = '```json\\n{\"name\": \"Alice\", \"age\": 30,}\\n```';\r\n *\r\n * const result = guard(raw, UserSchema);\r\n *\r\n * if (result.success) {\r\n *   console.log(result.data);       // { name: \"Alice\", age: 30 }\r\n *   console.log(result.isRepaired); // true\r\n *   console.log(result.telemetry);  // { durationMs: 0.55, status: \"repaired_natively\" }\r\n * } else {\r\n *   // Append result.retryPrompt to your LLM message array for a corrective retry.\r\n *   console.log(result.retryPrompt);\r\n *   console.log(result.errors);     // ZodIssue[]\r\n * }\r\n * ```\r\n *\r\n * ## Exports\r\n *\r\n * | Export | Kind | Description |\r\n * |--------|------|-------------|\r\n * | {@link guard} | Function | The main entry-point — parse, repair, validate.  |\r\n * | {@link GuardResult} | Type | Discriminated union returned by `guard()`. |\r\n * | {@link GuardSuccess} | Type | The success branch of `GuardResult`. |\r\n * | {@link GuardFailure} | Type | The failure branch of `GuardResult`. |\r\n * | {@link TelemetryData} | Type | Timing and status metadata. |\r\n *\r\n * @packageDocumentation\r\n */\r\n\r\nexport { guard } from \"./guard.js\";\r\nexport { forge } from \"./providers/forge.js\";\r\nexport { ForgeNetworkError } from \"./providers/forge.js\";\r\nexport { forgeWithFallback } from \"./providers/fallback.js\";\r\nexport type {\r\n  GuardResult,\r\n  GuardSuccess,\r\n  GuardFailure,\r\n  TelemetryData,\r\n  GuardOptions,\r\n  GuardProfile,\r\n  GuardHeuristicOptions,\r\n  GuardSemanticResolution,\r\n  GuardSemanticResolutionInput,\r\n  GuardSemanticResolver,\r\n  GuardDebugArtifacts,\r\n  RetryPromptOptions,\r\n  RetryPromptMode,\r\n  RetryPromptContextBlock,\r\n  RetryPromptStrategy,\r\n  RetryPromptStrategyInput,\r\n} from \"./types.js\";\r\nexport type {\r\n  Message,\r\n  MessageContent,\r\n  MessageContentBlock,\r\n  MessageTextBlock,\r\n  MessageImageUrlBlock,\r\n  ReforgeToolCall,\r\n  ReforgeToolResponse,\r\n  ProviderCallOptions,\r\n  ReforgeProvider,\r\n  ReforgeTool,\r\n  ForgeOptions,\r\n  ForgeRetryPolicy,\r\n  ForgeEvent,\r\n  ForgeFailurePayload,\r\n  ForgeFallbackProvider,\r\n  ForgeFallbackOptions,\r\n  ForgeTelemetry,\r\n  ForgeAttemptDetail,\r\n  ForgeProviderHop,\r\n  ForgeResult,\r\n  ForgeSuccess,\r\n  ForgeFailure,\r\n} from \"./providers/types.js\";\r\nexport type { OpenAICompatibleCallOptions } from \"./providers/openai-compatible.js\";\r\nexport type { AnthropicCallOptions } from \"./providers/anthropic.js\";\r\nexport type { GoogleCallOptions } from \"./providers/google.js\";\r\nexport type { OpenRouterCallOptions } from \"./providers/openrouter.js\";\r\nexport type { GroqCallOptions } from \"./providers/groq.js\";\r\nexport type { TogetherCallOptions } from \"./providers/together.js\";\r\n\r\n","import type { ExtractionResult } from \"../types.js\";\r\n\r\n/**\r\n * Extract a JSON string from raw LLM output.\r\n *\r\n * LLMs frequently wrap JSON inside markdown code fences (` ```json ... ``` `)\r\n * or surround it with conversational text (\"Here is the data: …\"). This\r\n * function locates the outermost JSON object or array and returns it.\r\n *\r\n * ### Strategy\r\n * 1. Try to extract content from a markdown code fence.\r\n * 2. Otherwise, find the first `{` or `[` and walk to its matching closer.\r\n * 3. If neither strategy yields content, return the original input unchanged.\r\n *\r\n * @param input - The raw string produced by an LLM.\r\n * @returns The extracted JSON substring and whether extraction was needed.\r\n *\r\n * @example\r\n * ```ts\r\n * extractJsonString('Here is your data: ```json\\n{\"a\":1}\\n```');\r\n * // => { extracted: '{\"a\":1}', wasExtracted: true }\r\n * ```\r\n */\r\nexport function extractJsonString(input: string): ExtractionResult {\r\n  if (input.length === 0) {\r\n    return { extracted: input, wasExtracted: false };\r\n  }\r\n\r\n  // --- Strategy 1: Markdown code fence ---\r\n  const fenceResult = extractFromCodeFence(input);\r\n  if (fenceResult !== null) {\r\n    return { extracted: fenceResult, wasExtracted: true };\r\n  }\r\n\r\n  // --- Strategy 2: Find outermost { or [ ---\r\n  const bracketResult = extractFromBrackets(input);\r\n  if (bracketResult !== null) {\r\n    return { extracted: bracketResult, wasExtracted: true };\r\n  }\r\n\r\n  // Nothing found — return original.\r\n  return { extracted: input, wasExtracted: false };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Internal helpers\r\n// ---------------------------------------------------------------------------\r\n\r\nconst FENCE_OPEN = /(```|~~~)(?:json|JSON|js|javascript)?\\s*\\n?/;\r\n\r\n/**\r\n * Attempt to pull content from the first markdown code fence that contains\r\n * a JSON-like structure (`{` or `[`).\r\n */\r\nfunction extractFromCodeFence(input: string): string | null {\r\n  let searchStart = 0;\r\n\r\n  while (searchStart < input.length) {\r\n    const openMatch = FENCE_OPEN.exec(input.slice(searchStart));\r\n    if (!openMatch) return null;\r\n\r\n    const fence = openMatch[1] ?? \"```\";\r\n    const contentStart = searchStart + openMatch.index + openMatch[0].length;\r\n    const closeIdx = input.indexOf(fence, contentStart);\r\n    if (closeIdx === -1) {\r\n      // Unclosed fence — treat everything after the open as content.\r\n      const content = input.slice(contentStart).trim();\r\n      if (looksLikeJson(content)) return content;\r\n      return null;\r\n    }\r\n\r\n    const content = input.slice(contentStart, closeIdx).trim();\r\n    if (looksLikeJson(content)) return content;\r\n\r\n    // This fence didn't contain JSON — keep searching after it.\r\n    searchStart = closeIdx + fence.length;\r\n  }\r\n\r\n  return null;\r\n}\r\n\r\n/**\r\n * Find the first `{` or `[` in the input and walk forward (tracking nesting\r\n * and string context) to find its matching closer.\r\n *\r\n * If the closer is not found (truncated output), return everything from the\r\n * opener to the end — bracket balancing will fix it later.\r\n */\r\nfunction extractFromBrackets(input: string): string | null {\r\n  // Find the first character that starts a JSON structure.\r\n  let startIdx = -1;\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n    if (ch === \"{\" || ch === \"[\") {\r\n      startIdx = i;\r\n      break;\r\n    }\r\n  }\r\n\r\n  if (startIdx === -1) return null;\r\n\r\n  // Walk forward to find the matching closer.\r\n  const opener = input[startIdx]!;\r\n  let inString = false;\r\n  const stack: string[] = [opener];\r\n  let lastMatchedCloserIdx = -1;\r\n\r\n  for (let i = startIdx + 1; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    if (inString) {\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++; // skip escaped char\r\n        continue;\r\n      }\r\n      if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"{\" || ch === \"[\") {\r\n      stack.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"}\" || ch === \"]\") {\r\n      const top = stack[stack.length - 1]!;\r\n\r\n      const expectedCloser = top === \"{\" ? \"}\" : \"]\";\r\n      if (ch !== expectedCloser) {\r\n        // Ignore mismatched closers; keep current nesting state intact.\r\n        continue;\r\n      }\r\n\r\n      stack.pop();\r\n      lastMatchedCloserIdx = i;\r\n\r\n      if (stack.length === 0) {\r\n        // Found exact match for the first opener — return the substring.\r\n        const extracted = input.slice(startIdx, i + 1);\r\n        if (extracted !== input) return extracted;\r\n        return null; // Already the full input, no extraction needed.\r\n      }\r\n    }\r\n  }\r\n\r\n  // Truncated — return from opener to last closer or end of input.\r\n  // Let the balance stage handle fixing it.\r\n  const end = lastMatchedCloserIdx > startIdx ? lastMatchedCloserIdx + 1 : input.length;\r\n  const extracted = input.slice(startIdx, end);\r\n  if (extracted !== input) return extracted;\r\n  return null;\r\n}\r\n\r\nfunction looksLikeJson(s: string): boolean {\r\n  return s.startsWith(\"{\") || s.startsWith(\"[\");\r\n}\r\n","import type { HeuristicResult } from \"../types.js\";\r\n\r\nexport interface HeuristicPassOptions {\r\n  escapedQuotes?: boolean;\r\n  singleQuotes?: boolean;\r\n  stripComments?: boolean;\r\n  normalizePythonLiterals?: boolean;\r\n  unquotedKeys?: boolean;\r\n  trailingCommas?: boolean;\r\n}\r\n\r\n/**\r\n * Apply common syntactic heuristics to repair malformed JSON strings.\r\n *\r\n * LLMs produce predictable classes of JSON errors. This module fixes the most\r\n * frequent ones via a single character-by-character scan that is aware of\r\n * string-literal context (so it never mutates content _inside_ quoted values).\r\n *\r\n * ### Fixes Applied\r\n * | Issue | Example | Result |\r\n * |---|---|---|\r\n * | Trailing commas | `{\"a\":1,}` | `{\"a\":1}` |\r\n * | Unquoted keys | `{name: \"John\"}` | `{\"name\": \"John\"}` |\r\n * | Single-quoted strings | `{'key': 'val'}` | `{\"key\": \"val\"}` |\r\n * | JS comments | `{\"a\":1 // note}` | `{\"a\":1}` |\r\n * | Python literals | `{\"active\": True}` | `{\"active\": true}` |\r\n * | Escaped-quote wrappers | `{\\\"key\\\": \\\"val\\\"}` | `{\"key\": \"val\"}` |\r\n *\r\n * @param input - A JSON-like string (after markdown extraction).\r\n * @returns The repaired string and whether any fix was applied.\r\n *\r\n * @example\r\n * ```ts\r\n * applyHeuristics(\"{name: 'John',}\");\r\n * // => { result: '{\"name\": \"John\"}', applied: true }\r\n * ```\r\n */\r\nexport function applyHeuristics(\r\n  input: string,\r\n  options?: HeuristicPassOptions,\r\n): HeuristicResult {\r\n  if (input.length === 0) {\r\n    return { result: input, applied: false };\r\n  }\r\n\r\n  let current = input;\r\n  let anyApplied = false;\r\n  const appliedRepairs: string[] = [];\r\n\r\n  const passes: Required<HeuristicPassOptions> = {\r\n    escapedQuotes: options?.escapedQuotes ?? true,\r\n    singleQuotes: options?.singleQuotes ?? true,\r\n    stripComments: options?.stripComments ?? true,\r\n    normalizePythonLiterals: options?.normalizePythonLiterals ?? true,\r\n    unquotedKeys: options?.unquotedKeys ?? true,\r\n    trailingCommas: options?.trailingCommas ?? true,\r\n  };\r\n\r\n  // --- Pass 1: Fix escaped-quote wrappers (must run first) ---\r\n  if (passes.escapedQuotes) {\r\n    const unescaped = fixEscapedQuotes(current);\r\n    if (unescaped !== current) {\r\n      current = unescaped;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"fix_escaped_quotes\");\r\n      if (canParseJson(current)) {\r\n        return { result: current, applied: true, appliedRepairs };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Pass 2: Fix single-quoted strings → double-quoted ---\r\n  if (passes.singleQuotes) {\r\n    const dqResult = fixSingleQuotes(current);\r\n    if (dqResult !== current) {\r\n      current = dqResult;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"fix_single_quotes\");\r\n      if (canParseJson(current)) {\r\n        return { result: current, applied: true, appliedRepairs };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Pass 3: Strip JS-style comments ---\r\n  if (passes.stripComments) {\r\n    const commentResult = stripJsComments(current);\r\n    if (commentResult !== current) {\r\n      current = commentResult;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"strip_js_comments\");\r\n      if (canParseJson(current)) {\r\n        return { result: current, applied: true, appliedRepairs };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Pass 4: Normalize Python literals ---\r\n  if (passes.normalizePythonLiterals) {\r\n    const pyResult = normalizePythonLiterals(current);\r\n    if (pyResult !== current) {\r\n      current = pyResult;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"normalize_python_literals\");\r\n      if (canParseJson(current)) {\r\n        return { result: current, applied: true, appliedRepairs };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Pass 5: Fix unquoted keys ---\r\n  if (passes.unquotedKeys) {\r\n    const uqResult = fixUnquotedKeys(current);\r\n    if (uqResult !== current) {\r\n      current = uqResult;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"fix_unquoted_keys\");\r\n      if (canParseJson(current)) {\r\n        return { result: current, applied: true, appliedRepairs };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Pass 6: Strip trailing commas ---\r\n  if (passes.trailingCommas) {\r\n    const tcResult = fixTrailingCommas(current);\r\n    if (tcResult !== current) {\r\n      current = tcResult;\r\n      anyApplied = true;\r\n      appliedRepairs.push(\"fix_trailing_commas\");\r\n    }\r\n  }\r\n\r\n  return {\r\n    result: current,\r\n    applied: anyApplied,\r\n    appliedRepairs: appliedRepairs.length > 0 ? appliedRepairs : undefined,\r\n  };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: Escaped-quote wrappers\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Detect and fix `{\\\"key\\\": \\\"value\\\"}` patterns that appear when an LLM\r\n * wraps a JSON object in escaped quotes (common when JSON is embedded in\r\n * another string context and then incorrectly extracted).\r\n *\r\n * Only activates when the input starts with `{` or `[` but contains `\\\"`\r\n * patterns outside of properly quoted strings.\r\n */\r\nfunction fixEscapedQuotes(input: string): string {\r\n  // Quick exit: if there are no escaped quotes, nothing to do.\r\n  if (!input.includes('\\\\\"')) return input;\r\n\r\n  // Wrapper-unescape only when there are no normal quotes in the payload.\r\n  const withoutEscaped = input\r\n    .replace(/\\\\\\\\\"/g, \"\")\r\n    .replace(/\\\\\"/g, \"\");\r\n  if (!withoutEscaped.includes('\"')) {\r\n    // Collapse one or more escaping layers for wrapper quotes.\r\n    let out = input;\r\n    for (let i = 0; i < 3; i++) {\r\n      const prev = out;\r\n      out = out.replace(/\\\\\\\\\"/g, '\\\\\"').replace(/\\\\\"/g, '\"');\r\n      if (out === prev) break;\r\n    }\r\n    return out;\r\n  }\r\n\r\n  return input;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: JS-style comments\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Strip JavaScript-style comments (`//` and `/* ... *\\/`) outside strings.\r\n */\r\nfunction stripJsComments(input: string): string {\r\n  const chars: string[] = [];\r\n  let inString = false;\r\n\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    if (inString) {\r\n      chars.push(ch);\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        chars.push(input[i]!);\r\n      } else if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      chars.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"/\" && i + 1 < input.length) {\r\n      const next = input[i + 1]!;\r\n\r\n      if (next === \"/\") {\r\n        i += 2;\r\n        while (i < input.length && input[i] !== \"\\n\") i++;\r\n        if (i < input.length && input[i] === \"\\n\") chars.push(\"\\n\");\r\n        continue;\r\n      }\r\n\r\n      if (next === \"*\") {\r\n        i += 2;\r\n        while (i + 1 < input.length) {\r\n          if (input[i] === \"*\" && input[i + 1] === \"/\") {\r\n            i++;\r\n            break;\r\n          }\r\n          i++;\r\n        }\r\n        continue;\r\n      }\r\n    }\r\n\r\n    chars.push(ch);\r\n  }\r\n\r\n  return chars.join(\"\");\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: Python-style literals\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Normalize Python literals (`True`, `False`, `None`) outside strings.\r\n */\r\nfunction normalizePythonLiterals(input: string): string {\r\n  const map: Record<string, string> = {\r\n    True: \"true\",\r\n    False: \"false\",\r\n    None: \"null\",\r\n  };\r\n\r\n  const chars: string[] = [];\r\n  let inString = false;\r\n  let i = 0;\r\n\r\n  while (i < input.length) {\r\n    const ch = input[i]!;\r\n\r\n    if (inString) {\r\n      chars.push(ch);\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        chars.push(input[i]!);\r\n      } else if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      i++;\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      chars.push(ch);\r\n      i++;\r\n      continue;\r\n    }\r\n\r\n    if (isAlpha(ch)) {\r\n      let j = i;\r\n      let word = \"\";\r\n      while (j < input.length && isWordChar(input[j]!)) {\r\n        word += input[j]!;\r\n        j++;\r\n      }\r\n\r\n      const replacement = map[word];\r\n      if (replacement && isWordBoundary(input, i - 1) && isWordBoundary(input, j)) {\r\n        chars.push(replacement);\r\n      } else {\r\n        chars.push(word);\r\n      }\r\n\r\n      i = j;\r\n      continue;\r\n    }\r\n\r\n    chars.push(ch);\r\n    i++;\r\n  }\r\n\r\n  return chars.join(\"\");\r\n}\r\n\r\nfunction isAlpha(ch: string): boolean {\r\n  return (ch >= \"a\" && ch <= \"z\") || (ch >= \"A\" && ch <= \"Z\");\r\n}\r\n\r\nfunction isWordChar(ch: string): boolean {\r\n  return isAlpha(ch) || (ch >= \"0\" && ch <= \"9\") || ch === \"_\";\r\n}\r\n\r\nfunction isWordBoundary(input: string, idx: number): boolean {\r\n  if (idx < 0 || idx >= input.length) return true;\r\n  const ch = input[idx]!;\r\n  return !isWordChar(ch);\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: Single-quoted strings → double-quoted\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Convert single-quoted keys and values to double-quoted ones.\r\n * Must track context to avoid replacing apostrophes inside double-quoted strings.\r\n */\r\nfunction fixSingleQuotes(input: string): string {\r\n  const chars: string[] = [];\r\n  let inDouble = false;\r\n  let inSingle = false;\r\n  let inBacktick = false;\r\n\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    // Handle escape sequences inside strings.\r\n    if ((inDouble || inSingle || inBacktick) && ch === \"\\\\\") {\r\n      if (i + 1 < input.length) {\r\n        i++;\r\n        const next = input[i]!;\r\n        // Inside a single-quote string being converted to double-quote,\r\n        // we need to escape any internal double-quotes and unescape escaped single-quotes.\r\n        if (inSingle || inBacktick) {\r\n          if (next === \"'\") {\r\n            // Unescape \\' → ' (no backslash needed inside double-quoted string).\r\n            chars.push(\"'\");\r\n          } else if (next === \"`\") {\r\n            chars.push(\"`\");\r\n          } else if (next === '\"') {\r\n            // Escape double-quote that was inside the single-quoted string.\r\n            chars.push('\\\\\"');\r\n          } else {\r\n            // Keep other escape sequences as-is.\r\n            chars.push(\"\\\\\", next);\r\n          }\r\n        } else {\r\n          // Inside a double-quoted string — preserve escape as-is.\r\n          chars.push(\"\\\\\", next);\r\n        }\r\n      } else {\r\n        // Trailing backslash at end of input.\r\n        chars.push(ch);\r\n      }\r\n      continue;\r\n    }\r\n\r\n    if (inDouble) {\r\n      if (ch === '\"') inDouble = false;\r\n      chars.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (inSingle) {\r\n      if (ch === \"'\") {\r\n        // Close single-quote → emit double-quote.\r\n        inSingle = false;\r\n        chars.push('\"');\r\n        continue;\r\n      }\r\n      // Escape any unescaped double-quotes inside the single-quoted string.\r\n      if (ch === '\"') {\r\n        chars.push('\\\\\"');\r\n        continue;\r\n      }\r\n      chars.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (inBacktick) {\r\n      if (ch === \"`\") {\r\n        inBacktick = false;\r\n        chars.push('\"');\r\n        continue;\r\n      }\r\n      if (ch === '\"') {\r\n        chars.push('\\\\\"');\r\n        continue;\r\n      }\r\n      chars.push(ch);\r\n      continue;\r\n    }\r\n\r\n    // Not inside any string.\r\n    if (ch === '\"') {\r\n      inDouble = true;\r\n      chars.push(ch);\r\n    } else if (ch === \"'\") {\r\n      inSingle = true;\r\n      chars.push('\"'); // Open single-quote → emit double-quote.\r\n    } else if (ch === \"`\") {\r\n      inBacktick = true;\r\n      chars.push('\"'); // Open backtick-quote → emit double-quote.\r\n    } else {\r\n      chars.push(ch);\r\n    }\r\n  }\r\n\r\n  return chars.join(\"\");\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: Unquoted keys\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Wrap bare (unquoted) object keys in double quotes.\r\n *\r\n * Detects patterns like `{ key:`, `{ key :`, `, key:` and wraps the key\r\n * identifier in `\"...\"`. Keys may contain word chars (`a-z`, `A-Z`, `0-9`, `_`, `$`).\r\n */\r\nfunction fixUnquotedKeys(input: string): string {\r\n  const chars: string[] = [];\r\n  let inString = false;\r\n  let i = 0;\r\n\r\n  while (i < input.length) {\r\n    const ch = input[i]!;\r\n\r\n    // Track string context.\r\n    if (inString) {\r\n      chars.push(ch);\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        chars.push(input[i]!);\r\n      } else if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      i++;\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      chars.push(ch);\r\n      i++;\r\n      continue;\r\n    }\r\n\r\n    // Look for unquoted key: we're at a position after `{`, `,`, or start\r\n    // and we see an identifier character.\r\n    if (isKeyStart(ch) && isAfterKeyPosition(chars)) {\r\n      // Consume the full key identifier.\r\n      let key = \"\";\r\n      let j = i;\r\n      while (j < input.length && isKeyChar(input[j]!)) {\r\n        key += input[j]!;\r\n        j++;\r\n      }\r\n\r\n      // Check if followed by `:` (possibly with whitespace).\r\n      let k = j;\r\n      while (k < input.length && isWhitespace(input[k]!)) k++;\r\n\r\n      if (k < input.length && input[k] === \":\") {\r\n        // This is an unquoted key — wrap it.\r\n        chars.push('\"', key, '\"');\r\n        i = j;\r\n        continue;\r\n      }\r\n    }\r\n\r\n    chars.push(ch);\r\n    i++;\r\n  }\r\n\r\n  return chars.join(\"\");\r\n}\r\n\r\nfunction isKeyStart(ch: string): boolean {\r\n  return (\r\n    (ch >= \"a\" && ch <= \"z\") ||\r\n    (ch >= \"A\" && ch <= \"Z\") ||\r\n    ch === \"_\" ||\r\n    ch === \"$\"\r\n  );\r\n}\r\n\r\nfunction isKeyChar(ch: string): boolean {\r\n  return isKeyStart(ch) || (ch >= \"0\" && ch <= \"9\");\r\n}\r\n\r\nfunction isWhitespace(ch: string): boolean {\r\n  return ch === \" \" || ch === \"\\t\" || ch === \"\\n\" || ch === \"\\r\";\r\n}\r\n\r\n/**\r\n * Check whether the accumulated output so far places us in a position where\r\n * an unquoted key would appear (after `{`, `,`, or start of input —\r\n * ignoring whitespace).\r\n */\r\nfunction isAfterKeyPosition(chars: string[]): boolean {\r\n  // Walk backwards through chars, skip whitespace.\r\n  for (let i = chars.length - 1; i >= 0; i--) {\r\n    const c = chars[i]!;\r\n    if (isWhitespace(c)) continue;\r\n    return c === \"{\" || c === \",\";\r\n  }\r\n  // Empty (start of input) — not a key position for bare JSON.\r\n  return false;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Fix: Trailing commas\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Remove trailing commas before `}` or `]`.\r\n * Character-by-character scan that tracks string context.\r\n */\r\nfunction fixTrailingCommas(input: string): string {\r\n  const chars: string[] = [];\r\n  let inString = false;\r\n\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    if (inString) {\r\n      chars.push(ch);\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        chars.push(input[i]!);\r\n      } else if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      chars.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (ch === \",\") {\r\n      // Look ahead: skip whitespace and see if the next non-ws char is } or ]\r\n      let j = i + 1;\r\n      while (j < input.length && isWhitespace(input[j]!)) j++;\r\n      if (j < input.length && (input[j] === \"}\" || input[j] === \"]\")) {\r\n        // Skip this comma (trailing comma — don't push it).\r\n        continue;\r\n      }\r\n    }\r\n\r\n    chars.push(ch);\r\n  }\r\n\r\n  return chars.join(\"\");\r\n}\r\n\r\nfunction canParseJson(input: string): boolean {\r\n  try {\r\n    JSON.parse(input);\r\n    return true;\r\n  } catch {\r\n    return false;\r\n  }\r\n}\r\n","import type { BalanceResult } from \"../types.js\";\r\n\r\n/**\r\n * Balance mismatched brackets and braces in a JSON string.\r\n *\r\n * When an LLM response is truncated (e.g. hitting `max_tokens`), the output\r\n * often ends mid-object or mid-array. This function uses a single-pass\r\n * stack-based scan to detect unclosed structures and appends the necessary\r\n * closing characters.\r\n *\r\n * ### Behaviour\r\n * - Tracks `{`, `}`, `[`, `]` while ignoring those inside string literals.\r\n * - At end-of-input, pops the stack and appends matching closers.\r\n * - Strips orphaned trailing closers that have no matching opener.\r\n *\r\n * @param input - A JSON-like string (after extraction & heuristic repair).\r\n * @returns The balanced string and whether any modification was made.\r\n *\r\n * @example\r\n * ```ts\r\n * balanceBrackets('{\"items\": [{\"id\": 1');\r\n * // => { result: '{\"items\": [{\"id\": 1}]}', wasBalanced: true }\r\n * ```\r\n */\r\nexport function balanceBrackets(input: string): BalanceResult {\r\n  if (input.length === 0) {\r\n    return { result: input, wasBalanced: false };\r\n  }\r\n\r\n  const stack: string[] = [];\r\n  const cleaned: string[] = [];\r\n  let inString = false;\r\n\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    // --- Inside a string literal: only watch for close-quote and escapes. ---\r\n    if (inString) {\r\n      cleaned.push(ch);\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        cleaned.push(input[i]!);\r\n      } else if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      continue;\r\n    }\r\n\r\n    // --- Outside a string literal. ---\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      cleaned.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"{\" || ch === \"[\") {\r\n      stack.push(ch);\r\n      cleaned.push(ch);\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"}\" || ch === \"]\") {\r\n      const expected = ch === \"}\" ? \"{\" : \"[\";\r\n      if (stack.length > 0 && stack[stack.length - 1] === expected) {\r\n        stack.pop();\r\n        cleaned.push(ch);\r\n      } else {\r\n        // Orphaned closer — skip it.\r\n      }\r\n      continue;\r\n    }\r\n\r\n    cleaned.push(ch);\r\n  }\r\n\r\n  // --- If we're inside an unclosed string, close it. ---\r\n  if (inString) {\r\n    cleaned.push('\"');\r\n  }\r\n\r\n  // --- Append missing closers from the stack (LIFO order). ---\r\n  let suffix = \"\";\r\n  while (stack.length > 0) {\r\n    const opener = stack.pop()!;\r\n    suffix += opener === \"{\" ? \"}\" : \"]\";\r\n  }\r\n\r\n  const result = cleaned.join(\"\") + suffix;\r\n  const wasBalanced = result !== input;\r\n\r\n  return { result, wasBalanced };\r\n}\r\n","import type { ParseResult } from \"../types.js\";\r\nimport { extractJsonString } from \"./extract.js\";\r\nimport { applyHeuristics } from \"./heuristics.js\";\r\nimport { balanceBrackets } from \"./balance.js\";\r\n\r\ninterface DirtyParseOptions {\r\n  heuristics?: {\r\n    escapedQuotes?: boolean;\r\n    singleQuotes?: boolean;\r\n    stripComments?: boolean;\r\n    normalizePythonLiterals?: boolean;\r\n    unquotedKeys?: boolean;\r\n    trailingCommas?: boolean;\r\n  };\r\n}\r\n\r\n/**\r\n * The Dirty Parser — Reforge's native JSON repair pipeline.\r\n *\r\n * Accepts raw LLM output (which may be wrapped in markdown, contain trailing\r\n * commas, have unquoted keys, or be truncated) and attempts to produce a\r\n * valid JavaScript value via `JSON.parse`.\r\n *\r\n * ### Pipeline Order\r\n * 1. **Fast path** — try `JSON.parse(input)` directly.\r\n * 2. **Extract** — strip markdown fences and conversational wrappers.\r\n * 3. **Heuristics** — fix trailing commas, unquoted keys, single quotes, escaped quotes.\r\n * 4. **Balance** — close unclosed brackets/braces (truncated output).\r\n * 5. **Final parse** — `JSON.parse` on the repaired string.\r\n *\r\n * ### Performance\r\n * The entire pipeline is synchronous, zero-allocation where possible, and\r\n * operates in O(n) time relative to input length.\r\n *\r\n * @param input - Raw string from an LLM.\r\n * @returns A discriminated-union `ParseResult`: either the parsed value or\r\n *          the raw input for error reporting.\r\n *\r\n * @example\r\n * ```ts\r\n * dirtyParse('```json\\n{\"name\": \"Alice\",}\\n```');\r\n * // => { success: true, value: { name: \"Alice\" }, isRepaired: true }\r\n * ```\r\n */\r\n\r\n/** Maximum input size in bytes (10 MB). Inputs larger than this are rejected. */\r\nconst MAX_INPUT_SIZE = 10 * 1024 * 1024;\r\n\r\nexport function dirtyParse(input: string, options?: DirtyParseOptions): ParseResult {\r\n  // --- Guard: reject absurdly large inputs to prevent DoS. ---\r\n  if (input.length > MAX_INPUT_SIZE) {\r\n    return {\r\n      success: false,\r\n      raw: input,\r\n      likelyErrorLine: getLastNonEmptyLine(input),\r\n    };\r\n  }\r\n\r\n  // --- Fast path: already valid JSON. ---\r\n  const fast = tryParse(input);\r\n  if (fast !== PARSE_FAILED) {\r\n    return {\r\n      success: true,\r\n      value: fast,\r\n      isRepaired: false,\r\n      extractedText: input,\r\n      repairedText: input,\r\n    };\r\n  }\r\n\r\n  // --- Stage 1: Extract ---\r\n  const { extracted, wasExtracted } = extractJsonString(input);\r\n\r\n  // --- Stage 2: Heuristics ---\r\n  const heuristicMeta = applyHeuristics(extracted, options?.heuristics);\r\n  const heuristicResult = heuristicMeta.result;\r\n  const heuristicsApplied = heuristicMeta.applied;\r\n\r\n  // --- Stage 3: Balance ---\r\n  const { result: balanced, wasBalanced } = balanceBrackets(heuristicResult);\r\n\r\n  // --- Final parse ---\r\n  const parsed = tryParse(balanced);\r\n  if (parsed !== PARSE_FAILED) {\r\n    const isRepaired = wasExtracted || heuristicsApplied || wasBalanced;\r\n    const appliedRepairs = [...(heuristicMeta.appliedRepairs ?? [])];\r\n    if (wasExtracted) appliedRepairs.unshift(\"extract_json\");\r\n    if (wasBalanced) appliedRepairs.push(\"balance_brackets\");\r\n\r\n    return {\r\n      success: true,\r\n      value: parsed,\r\n      isRepaired,\r\n      extractedText: extracted,\r\n      repairedText: balanced,\r\n      appliedRepairs: appliedRepairs.length > 0 ? appliedRepairs : undefined,\r\n    };\r\n  }\r\n\r\n  const appliedRepairs = [...(heuristicMeta.appliedRepairs ?? [])];\r\n  if (wasExtracted) appliedRepairs.unshift(\"extract_json\");\r\n  if (wasBalanced) appliedRepairs.push(\"balance_brackets\");\r\n\r\n  return {\r\n    success: false,\r\n    raw: input,\r\n    likelyErrorLine: inferLikelyErrorLine(balanced),\r\n    extractedText: extracted,\r\n    repairedText: balanced,\r\n    appliedRepairs: appliedRepairs.length > 0 ? appliedRepairs : undefined,\r\n  };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Internal helpers\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Sentinel value for failed `JSON.parse` attempts (avoids exceptions in hot path). */\r\nconst PARSE_FAILED: unique symbol = Symbol(\"PARSE_FAILED\");\r\n\r\nfunction tryParse(input: string): unknown | typeof PARSE_FAILED {\r\n  try {\r\n    return JSON.parse(input) as unknown;\r\n  } catch {\r\n    return PARSE_FAILED;\r\n  }\r\n}\r\n\r\nfunction inferLikelyErrorLine(input: string): number {\r\n  const stack: Array<{ ch: \"{\" | \"[\"; line: number }> = [];\r\n  let inString = false;\r\n  let line = 1;\r\n\r\n  for (let i = 0; i < input.length; i++) {\r\n    const ch = input[i]!;\r\n\r\n    if (ch === \"\\n\") {\r\n      line++;\r\n      continue;\r\n    }\r\n\r\n    if (inString) {\r\n      if (ch === \"\\\\\" && i + 1 < input.length) {\r\n        i++;\r\n        continue;\r\n      }\r\n      if (ch === '\"') {\r\n        inString = false;\r\n      }\r\n      continue;\r\n    }\r\n\r\n    if (ch === '\"') {\r\n      inString = true;\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"{\" || ch === \"[\") {\r\n      stack.push({ ch, line });\r\n      continue;\r\n    }\r\n\r\n    if (ch === \"}\" || ch === \"]\") {\r\n      const top = stack[stack.length - 1];\r\n      if (!top) return line;\r\n\r\n      const expected = top.ch === \"{\" ? \"}\" : \"]\";\r\n      if (expected !== ch) {\r\n        return line;\r\n      }\r\n\r\n      stack.pop();\r\n    }\r\n  }\r\n\r\n  if (stack.length > 0) {\r\n    return stack[stack.length - 1]!.line;\r\n  }\r\n\r\n  return getLastNonEmptyLine(input);\r\n}\r\n\r\nfunction getLastNonEmptyLine(input: string): number {\r\n  const lines = input.split(/\\r?\\n/);\r\n  for (let i = lines.length - 1; i >= 0; i--) {\r\n    if (lines[i]!.trim().length > 0) {\r\n      return i + 1;\r\n    }\r\n  }\r\n  return 1;\r\n}\r\n","import type { ZodIssue, ZodTypeAny } from \"zod\";\r\n\r\n/**\r\n * Validate parsed data against a Zod schema with LLM-friendly coercion.\r\n *\r\n * Before running `schema.safeParse()`, this module applies a lightweight\r\n * coercion pre-pass that handles the most common LLM type mismatches:\r\n *\r\n * | Input | Schema expects | Coerced to |\r\n * |---|---|---|\r\n * | `\"true\"` / `\"false\"` | `boolean` | `true` / `false` |\r\n * | `\"42\"`, `\"3.14\"` | `number` | `42`, `3.14` |\r\n * | `\"null\"` | `null` / `nullable` | `null` |\r\n * | `\"2025-03-13T00:00:00Z\"` | `date` | `Date` |\r\n * | `\"Active\"` | `enum(\"active\")` | `\"active\"` |\r\n *\r\n * Coercion is applied iteratively using a work queue (not recursion) to\r\n * comply with the project's security guidelines around stack safety.\r\n *\r\n * @module\r\n */\r\n\r\n/** Successful validation result. */\r\nexport interface ValidationSuccess<T> {\r\n  success: true;\r\n  data: T;\r\n}\r\n\r\n/** Failed validation result. */\r\nexport interface ValidationFailure {\r\n  success: false;\r\n  errors: ZodIssue[];\r\n}\r\n\r\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\r\n\r\n/**\r\n * Validate `data` against a Zod `schema`, applying coercion for common\r\n * LLM type mismatches before validation.\r\n *\r\n * @typeParam T - The Zod schema type.\r\n * @param data   - The parsed (but untyped) JavaScript value.\r\n * @param schema - The Zod schema to validate against.\r\n * @returns A discriminated-union result with either typed data or Zod errors.\r\n *\r\n * @example\r\n * ```ts\r\n * import { z } from 'zod';\r\n * validateWithSchema({ age: \"25\", active: \"true\" }, z.object({ age: z.number(), active: z.boolean() }));\r\n * // => { success: true, data: { age: 25, active: true } }\r\n * ```\r\n */\r\nexport function validateWithSchema<T extends ZodTypeAny>(\r\n  data: unknown,\r\n  schema: T,\r\n): ValidationResult<ReturnType<T[\"parse\"]>> {\r\n  // First attempt without coercion (fast path).\r\n  const direct = schema.safeParse(data);\r\n  if (direct.success) {\r\n    return { success: true, data: direct.data };\r\n  }\r\n\r\n  // Apply coercion and try again.\r\n  const coerced = coerceForSchema(data, schema);\r\n  const result = schema.safeParse(coerced);\r\n\r\n  if (result.success) {\r\n    return { success: true, data: result.data };\r\n  }\r\n\r\n  return { success: false, errors: result.error.issues };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Coercion Engine — iterative, schema-aware\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Attempt to coerce `data` to better match `schema` expectations.\r\n *\r\n * Uses a work queue to iteratively walk the data/schema tree without\r\n * recursion. Only coerces when the schema explicitly expects a different\r\n * primitive type than what the data contains.\r\n */\r\nfunction coerceForSchema(data: unknown, schema: ZodTypeAny): unknown {\r\n  // For primitives at the top level, try direct coercion.\r\n  if (typeof data !== \"object\" || data === null) {\r\n    return coercePrimitive(data, schema);\r\n  }\r\n\r\n  // For objects/arrays, clone & iteratively coerce leaves.\r\n  const root = cloneContainer(data);\r\n\r\n  // Work queue: [parentRef, key, subSchema]\r\n  type WorkItem = {\r\n    parent: Record<string, unknown> | unknown[];\r\n    key: string | number;\r\n    subSchema: ZodTypeAny;\r\n  };\r\n\r\n  const queue: WorkItem[] = [];\r\n  enqueueChildren(root, schema, queue);\r\n\r\n  // Process up to a sane limit to prevent DoS on adversarial inputs.\r\n  const MAX_ITERATIONS = 50_000;\r\n  let iterations = 0;\r\n\r\n  for (let queueIndex = 0; queueIndex < queue.length && iterations < MAX_ITERATIONS; queueIndex++) {\r\n    iterations++;\r\n    const item = queue[queueIndex]!;\r\n    const value = (item.parent as Record<string | number, unknown>)[item.key];\r\n\r\n    if (typeof value === \"object\" && value !== null) {\r\n      // Clone nested objects/arrays so we don't mutate the original.\r\n      const cloned = cloneContainer(value);\r\n      (item.parent as Record<string | number, unknown>)[item.key] = cloned;\r\n      enqueueChildren(cloned, item.subSchema, queue);\r\n    } else {\r\n      // Leaf — try primitive coercion.\r\n      const coerced = coercePrimitive(value, item.subSchema);\r\n      if (coerced !== value) {\r\n        (item.parent as Record<string | number, unknown>)[item.key] = coerced;\r\n      }\r\n    }\r\n  }\r\n\r\n  return root;\r\n}\r\n\r\nfunction cloneContainer(value: unknown): Record<string, unknown> | unknown[] {\r\n  if (Array.isArray(value)) {\r\n    return [...value];\r\n  }\r\n\r\n  if (isPlainObject(value)) {\r\n    const source = value as Record<string, unknown>;\r\n    const target = Object.create(null) as Record<string, unknown>;\r\n    for (const key of Object.keys(source)) {\r\n      target[key] = source[key];\r\n    }\r\n    return target;\r\n  }\r\n\r\n  return Object.create(null) as Record<string, unknown>;\r\n}\r\n\r\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\r\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\r\n    return false;\r\n  }\r\n\r\n  const proto = Object.getPrototypeOf(value);\r\n  return proto === Object.prototype || proto === null;\r\n}\r\n\r\n/**\r\n * Coerce a single primitive value based on what the schema expects.\r\n * Unwraps ZodOptional, ZodNullable, and ZodDefault wrappers to\r\n * find the inner type for coercion.\r\n */\r\nfunction coercePrimitive(value: unknown, schema: ZodTypeAny): unknown {\r\n  if (typeof value !== \"string\") return value;\r\n\r\n  const typeName = getSchemaTypeName(schema);\r\n  const def = (schema as { _def?: Record<string, unknown> })._def;\r\n\r\n  // Unwrap wrapper types to get at the actual target type.\r\n  if (typeName === \"ZodOptional\" || typeName === \"ZodNullable\" || typeName === \"ZodDefault\") {\r\n    const inner = getInnerSchema(def);\r\n\r\n    // For nullable, also check \"null\" string before unwrapping.\r\n    if (typeName === \"ZodNullable\" && value === \"null\") {\r\n      // Preserve literal \"null\" for nullable strings.\r\n      if (inner && getSchemaTypeName(inner) === \"ZodString\") return value;\r\n      return null;\r\n    }\r\n\r\n    if (inner) return coercePrimitive(value, inner);\r\n    return value;\r\n  }\r\n\r\n  if (typeName === \"ZodBoolean\") {\r\n    if (value === \"true\") return true;\r\n    if (value === \"false\") return false;\r\n  }\r\n\r\n  if (typeName === \"ZodNumber\") {\r\n    const n = Number(value);\r\n    if (value.trim() !== \"\" && !Number.isNaN(n)) return n;\r\n  }\r\n\r\n  if (typeName === \"ZodNull\") {\r\n    if (value === \"null\") return null;\r\n  }\r\n\r\n  if (typeName === \"ZodDate\") {\r\n    const d = new Date(value);\r\n    if (!Number.isNaN(d.getTime())) return d;\r\n  }\r\n\r\n  if (typeName === \"ZodLiteral\" && def) {\r\n    const literal = (def as { value?: unknown }).value;\r\n\r\n    if (typeof literal === \"number\") {\r\n      const n = Number(value);\r\n      if (value.trim() !== \"\" && !Number.isNaN(n) && n === literal) {\r\n        return literal;\r\n      }\r\n    }\r\n\r\n    if (typeof literal === \"boolean\") {\r\n      if ((value === \"true\" && literal === true) || (value === \"false\" && literal === false)) {\r\n        return literal;\r\n      }\r\n    }\r\n\r\n    if (typeof literal === \"string\") {\r\n      if (value === literal) return literal;\r\n      if (value.toLowerCase() === literal.toLowerCase()) return literal;\r\n    }\r\n  }\r\n\r\n  if (typeName === \"ZodEnum\" && def) {\r\n    const values = (def as { values?: unknown[] }).values;\r\n    if (Array.isArray(values)) {\r\n      const exact = values.find((v) => typeof v === \"string\" && v === value);\r\n      if (exact !== undefined) return exact;\r\n\r\n      const lower = value.toLowerCase();\r\n      const ci = values.find(\r\n        (v) => typeof v === \"string\" && (v as string).toLowerCase() === lower,\r\n      );\r\n      if (ci !== undefined) return ci;\r\n    }\r\n  }\r\n\r\n  if (typeName === \"ZodUnion\" && def) {\r\n    const options = getUnionOptions(def);\r\n    for (const option of options) {\r\n      const coerced = coercePrimitive(value, option);\r\n      const parsed = option.safeParse(coerced);\r\n      if (parsed.success) {\r\n        return parsed.data;\r\n      }\r\n    }\r\n  }\r\n\r\n  return value;\r\n}\r\n\r\n/**\r\n * Enqueue child fields/elements depending on the schema kind.\r\n */\r\nfunction enqueueChildren(\r\n  parent: Record<string, unknown> | unknown[],\r\n  schema: ZodTypeAny,\r\n  queue: { parent: Record<string, unknown> | unknown[]; key: string | number; subSchema: ZodTypeAny }[],\r\n): void {\r\n  const typeName = getSchemaTypeName(schema);\r\n  const def = (schema as { _def?: Record<string, unknown> })._def;\r\n\r\n  if (typeName === \"ZodObject\" && def) {\r\n    const shape = typeof (schema as unknown as { shape?: unknown }).shape === \"object\"\r\n      ? (schema as unknown as { shape: Record<string, ZodTypeAny> }).shape\r\n      : null;\r\n    if (shape) {\r\n      for (const key of Object.keys(shape)) {\r\n        if (key in (parent as Record<string, unknown>)) {\r\n          queue.push({ parent, key, subSchema: shape[key]! });\r\n        }\r\n      }\r\n    }\r\n  } else if (typeName === \"ZodArray\" && def && Array.isArray(parent)) {\r\n    const elementSchema = (def as { type?: ZodTypeAny }).type;\r\n    if (elementSchema) {\r\n      for (let i = 0; i < parent.length; i++) {\r\n        queue.push({ parent, key: i, subSchema: elementSchema });\r\n      }\r\n    }\r\n  } else if (typeName === \"ZodTuple\" && def && Array.isArray(parent)) {\r\n    const items = (def as { items?: ZodTypeAny[] }).items;\r\n    if (Array.isArray(items)) {\r\n      const count = Math.min(parent.length, items.length);\r\n      for (let i = 0; i < count; i++) {\r\n        queue.push({ parent, key: i, subSchema: items[i]! });\r\n      }\r\n    }\r\n  } else if (typeName === \"ZodUnion\" && def) {\r\n    const options = getUnionOptions(def);\r\n    for (const option of options) {\r\n      if (option.safeParse(parent).success) {\r\n        enqueueChildren(parent, option, queue);\r\n        return;\r\n      }\r\n    }\r\n    if (options.length > 0) {\r\n      enqueueChildren(parent, options[0]!, queue);\r\n    }\r\n  } else if (typeName === \"ZodDiscriminatedUnion\" && def && isPlainObject(parent)) {\r\n    const discriminator = (def as { discriminator?: unknown }).discriminator;\r\n    const optionsMap = (def as { optionsMap?: Map<unknown, ZodTypeAny> }).optionsMap;\r\n\r\n    if (typeof discriminator === \"string\" && optionsMap instanceof Map) {\r\n      const rawDiscriminatorValue = parent[discriminator];\r\n      const discriminatorValue = coerceDiscriminatorToMapKey(rawDiscriminatorValue, optionsMap);\r\n      if (optionsMap.has(discriminatorValue)) {\r\n        const option = optionsMap.get(discriminatorValue);\r\n        if (option) enqueueChildren(parent, option, queue);\r\n      }\r\n    }\r\n  } else if (typeName === \"ZodOptional\" || typeName === \"ZodNullable\" || typeName === \"ZodDefault\") {\r\n    // Unwrap wrapper types and re-process.\r\n    const inner = getInnerSchema(def);\r\n    if (inner) {\r\n      enqueueChildren(parent, inner, queue);\r\n    }\r\n  }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Schema introspection helpers\r\n// ---------------------------------------------------------------------------\r\n\r\nfunction getSchemaTypeName(schema: ZodTypeAny): string {\r\n  const def = (schema as { _def?: { typeName?: string } })._def;\r\n  return def?.typeName ?? \"\";\r\n}\r\n\r\nfunction getInnerSchema(def: Record<string, unknown> | undefined): ZodTypeAny | null {\r\n  if (!def) return null;\r\n  // ZodOptional, ZodNullable store inner schema as `innerType`.\r\n  // ZodDefault stores it as `innerType` as well.\r\n  const inner = def.innerType as ZodTypeAny | undefined;\r\n  return inner ?? null;\r\n}\r\n\r\nfunction getUnionOptions(def: Record<string, unknown>): ZodTypeAny[] {\r\n  const options = def.options as unknown;\r\n  if (Array.isArray(options)) {\r\n    return options.filter((v): v is ZodTypeAny => typeof v === \"object\" && v !== null);\r\n  }\r\n  return [];\r\n}\r\n\r\nfunction coerceDiscriminatorToMapKey(value: unknown, optionsMap: Map<unknown, ZodTypeAny>): unknown {\r\n  if (optionsMap.has(value)) return value;\r\n  if (typeof value !== \"string\") return value;\r\n\r\n  for (const key of optionsMap.keys()) {\r\n    if (typeof key === \"number\") {\r\n      const n = Number(value);\r\n      if (value.trim() !== \"\" && !Number.isNaN(n) && n === key) {\r\n        return key;\r\n      }\r\n    }\r\n    if (typeof key === \"boolean\") {\r\n      if ((value === \"true\" && key === true) || (value === \"false\" && key === false)) {\r\n        return key;\r\n      }\r\n    }\r\n    if (typeof key === \"string\" && key.toLowerCase() === value.toLowerCase()) {\r\n      return key;\r\n    }\r\n  }\r\n\r\n  return value;\r\n}\r\n","import type { ZodIssue } from \"zod\";\r\nimport type {\r\n  RetryPromptContextBlock,\r\n  RetryPromptOptions,\r\n  RetryPromptStrategy,\r\n  RetryPromptStrategyInput,\r\n} from \"../types.js\";\r\n\r\n/**\r\n * Maximum characters of raw input to include in a parse-failure prompt.\r\n * If the raw output exceeds this, the snippet is omitted entirely — a\r\n * truncated beginning gives the LLM no actionable signal about what went\r\n * wrong, and wastes tokens.\r\n */\r\nconst RAW_SNIPPET_MAX = 300;\r\n\r\ninterface RetryPromptConfig {\r\n  options?: RetryPromptOptions;\r\n  sourceText?: string;\r\n  strategy?: RetryPromptStrategy;\r\n  parseErrorLine?: number;\r\n  onContextBlocks?: (blocks: RetryPromptContextBlock[]) => void;\r\n}\r\n\r\nconst DEFAULT_RETRY_OPTIONS: Required<\r\n  Omit<RetryPromptOptions, \"redactPaths\" | \"redactRegex\">\r\n> = {\r\n  mode: \"compact\",\r\n  contextRadius: 1,\r\n  maxContextChars: 700,\r\n  includeLineNumbers: true,\r\n  maxIssueBlocks: 3,\r\n};\r\n\r\n/**\r\n * Generate a token-efficient retry prompt from Zod validation errors or a\r\n * parse failure.\r\n *\r\n * When `guard()` fails it calls this function to produce a concise instruction\r\n * string that can be appended to the LLM conversation to request a corrected\r\n * response.\r\n *\r\n * ### Design Goals\r\n * - **Token-efficient:** Every word costs money. The prompt is terse on purpose.\r\n * - **Actionable:** Validation errors include the exact JSON path, expected type,\r\n *   and received value. Parse failures include a snippet of the offending text.\r\n * - **Assumes schema context:** The LLM is expected to still have the original\r\n *   schema in its conversation context. The prompt never re-sends the schema —\r\n *   it only describes what was wrong with the previous response.\r\n *\r\n * @param errors     - The `ZodIssue[]` array from a failed `safeParse()`. Pass\r\n *                     an empty array when the failure is a parse error.\r\n * @param rawSnippet - The raw LLM output that could not be parsed. Included\r\n *                     in the prompt only when it fits entirely within\r\n *                     {@link RAW_SNIPPET_MAX} characters — a truncated leading\r\n *                     slice gives no actionable signal, so it is omitted for\r\n *                     longer outputs.\r\n * @returns A prompt string ready to be appended to the LLM message array.\r\n *\r\n * @example Validation failure\r\n * ```ts\r\n * generateRetryPrompt([\r\n *   { code: \"invalid_type\", expected: \"number\", received: \"string\", path: [\"user\", \"age\"], message: \"Expected number\" },\r\n * ]);\r\n * // => 'Your previous response failed schema validation. Errors: [Path: /user/age, Expected: number, Received: string]. The schema is still in your context — return ONLY corrected valid JSON.'\r\n * ```\r\n *\r\n * @example Parse failure\r\n * ```ts\r\n * generateRetryPrompt([], '{name: Alice, age:}');\r\n * // => 'Your previous response could not be parsed as JSON. Got: `{name: Alice, age:}`. The schema is still in your context — return ONLY valid JSON.'\r\n * ```\r\n */\r\nexport function generateRetryPrompt(\r\n  errors: ZodIssue[],\r\n  rawSnippet?: string,\r\n  config?: RetryPromptConfig,\r\n): string {\r\n  const options = {\r\n    ...DEFAULT_RETRY_OPTIONS,\r\n    ...(config?.options ?? {}),\r\n  };\r\n\r\n  let contextBlocks: RetryPromptContextBlock[] = [];\r\n\r\n  // Parse failure: JSON could not be extracted at all.\r\n  if (errors.length === 0) {\r\n    if (options.mode === \"line-aware\" && rawSnippet) {\r\n      const line =\r\n        config?.parseErrorLine !== undefined\r\n          ? clampLine(config.parseErrorLine, rawSnippet)\r\n          : inferLikelyParseLine(rawSnippet);\r\n\r\n      contextBlocks = createContextBlocksFromLines(\r\n        rawSnippet,\r\n        [line],\r\n        options.contextRadius,\r\n        options.maxIssueBlocks,\r\n        options.maxContextChars,\r\n        options.includeLineNumbers,\r\n      );\r\n      contextBlocks = applyContextRedaction(contextBlocks, options, []);\r\n    }\r\n\r\n    config?.onContextBlocks?.(contextBlocks);\r\n\r\n    const strategyInput: RetryPromptStrategyInput = {\r\n      errors,\r\n      rawOutput: rawSnippet,\r\n      contextBlocks,\r\n    };\r\n\r\n    if (config?.strategy) {\r\n      const custom = config.strategy(strategyInput).trim();\r\n      if (custom.length > 0) {\r\n        return custom;\r\n      }\r\n    }\r\n\r\n    // Only echo the raw output when it fits entirely — a truncated leading\r\n    // slice shows the LLM a fragment that may look fine, giving no signal\r\n    // about where extraction failed and wasting context tokens.\r\n    const redactedRaw = applyRawRedaction(rawSnippet, options);\r\n\r\n    if (contextBlocks.length > 0) {\r\n      const blocks = contextBlocks.map((b) => b.text).join(\"\\n\\n\");\r\n      return `Your previous response could not be parsed as JSON. Relevant lines:\\n${blocks}\\nThe schema is still in your context — return ONLY valid JSON.`;\r\n    }\r\n\r\n    if (\r\n      redactedRaw !== undefined &&\r\n      redactedRaw.length > 0 &&\r\n      redactedRaw.length <= RAW_SNIPPET_MAX\r\n    ) {\r\n      return `Your previous response could not be parsed as JSON. Got: \\`${redactedRaw}\\`. The schema is still in your context — return ONLY valid JSON.`;\r\n    }\r\n\r\n    return \"Your previous response could not be parsed as JSON. The schema is still in your context — return ONLY valid JSON.\";\r\n  }\r\n\r\n  if (options.mode === \"line-aware\" && config?.sourceText) {\r\n    const lines = gatherIssueLines(config.sourceText, errors);\r\n    contextBlocks = createContextBlocksFromLines(\r\n      config.sourceText,\r\n      lines,\r\n      options.contextRadius,\r\n      options.maxIssueBlocks,\r\n      options.maxContextChars,\r\n      options.includeLineNumbers,\r\n    );\r\n    contextBlocks = applyContextRedaction(contextBlocks, options, errors);\r\n  }\r\n\r\n  config?.onContextBlocks?.(contextBlocks);\r\n\r\n  const strategyInput: RetryPromptStrategyInput = {\r\n    errors,\r\n    rawOutput: rawSnippet,\r\n    contextBlocks,\r\n  };\r\n\r\n  if (config?.strategy) {\r\n    const custom = config.strategy(strategyInput).trim();\r\n    if (custom.length > 0) {\r\n      return custom;\r\n    }\r\n  }\r\n\r\n  // Validation failure: JSON parsed but didn't satisfy the schema.\r\n  const formatted = errors.map(formatIssue).join(\"; \");\r\n\r\n  if (contextBlocks.length > 0) {\r\n    const blocks = contextBlocks.map((b) => b.text).join(\"\\n\\n\");\r\n    return `Your previous response failed schema validation. Relevant lines:\\n${blocks}\\nErrors: ${formatted}. The schema is still in your context — return ONLY corrected valid JSON.`;\r\n  }\r\n\r\n  return `Your previous response failed schema validation. Errors: ${formatted}. The schema is still in your context — return ONLY corrected valid JSON.`;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Internal helpers\r\n// ---------------------------------------------------------------------------\r\n\r\nfunction formatIssue(issue: ZodIssue): string {\r\n  const path = \"/\" + issue.path.map(String).join(\"/\");\r\n\r\n  if (issue.code === \"too_small\") {\r\n    const comparator = issue.inclusive ? \"at least\" : \"greater than\";\r\n    return `[Path: ${path}, Constraint: must be ${comparator} ${String(issue.minimum)}]`;\r\n  }\r\n\r\n  if (issue.code === \"too_big\") {\r\n    const comparator = issue.inclusive ? \"at most\" : \"less than\";\r\n    return `[Path: ${path}, Constraint: must be ${comparator} ${String(issue.maximum)}]`;\r\n  }\r\n\r\n  if (issue.code === \"invalid_enum_value\") {\r\n    const allowed = issue.options.map((v) => JSON.stringify(v)).join(\", \");\r\n    return `[Path: ${path}, Constraint: must be one of: ${allowed}]`;\r\n  }\r\n\r\n  if (issue.code === \"custom\") {\r\n    return `[Path: ${path}, Constraint: ${issue.message}]`;\r\n  }\r\n\r\n  // Build informative detail based on the issue code.\r\n  const parts: string[] = [`Path: ${path}`];\r\n\r\n  if (\"expected\" in issue && issue.expected !== undefined) {\r\n    parts.push(`Expected: ${String(issue.expected)}`);\r\n  }\r\n  if (\"received\" in issue && issue.received !== undefined) {\r\n    parts.push(`Received: ${String(issue.received)}`);\r\n  }\r\n\r\n  // Fallback: always include the human-readable message.\r\n  if (parts.length === 1) {\r\n    parts.push(`Message: ${issue.message}`);\r\n  }\r\n\r\n  return `[${parts.join(\", \")}]`;\r\n}\r\n\r\nfunction gatherIssueLines(sourceText: string, errors: ZodIssue[]): number[] {\r\n  const lines = sourceText.split(/\\r?\\n/);\r\n  const result = new Set<number>();\r\n\r\n  for (const issue of errors) {\r\n    const line = findLineForIssue(lines, issue);\r\n    result.add(line);\r\n  }\r\n\r\n  if (result.size === 0) {\r\n    result.add(1);\r\n  }\r\n\r\n  return [...result].sort((a, b) => a - b);\r\n}\r\n\r\nfunction findLineForIssue(lines: string[], issue: ZodIssue): number {\r\n  if (issue.path.length === 0) {\r\n    return firstNonEmptyLine(lines);\r\n  }\r\n\r\n  for (let i = issue.path.length - 1; i >= 0; i--) {\r\n    const part = issue.path[i];\r\n    if (typeof part === \"string\") {\r\n      const needle = `\"${part}\"`;\r\n      const lineIdx = lines.findIndex((line) => line.includes(needle));\r\n      if (lineIdx !== -1) {\r\n        return lineIdx + 1;\r\n      }\r\n    }\r\n  }\r\n\r\n  return firstNonEmptyLine(lines);\r\n}\r\n\r\nfunction firstNonEmptyLine(lines: string[]): number {\r\n  for (let i = 0; i < lines.length; i++) {\r\n    if (lines[i]!.trim().length > 0) {\r\n      return i + 1;\r\n    }\r\n  }\r\n  return 1;\r\n}\r\n\r\nfunction createContextBlocksFromLines(\r\n  sourceText: string,\r\n  issueLines: number[],\r\n  radius: number,\r\n  maxBlocks: number,\r\n  maxChars: number,\r\n  includeLineNumbers: boolean,\r\n): RetryPromptContextBlock[] {\r\n  const lines = sourceText.split(/\\r?\\n/);\r\n  const windows = issueLines\r\n    .map((line) => ({\r\n      start: Math.max(1, line - radius),\r\n      end: Math.min(lines.length, line + radius),\r\n    }))\r\n    .sort((a, b) => a.start - b.start);\r\n\r\n  const merged: Array<{ start: number; end: number }> = [];\r\n  for (const win of windows) {\r\n    const last = merged[merged.length - 1];\r\n    if (!last || win.start > last.end + 1) {\r\n      merged.push({ ...win });\r\n    } else {\r\n      last.end = Math.max(last.end, win.end);\r\n    }\r\n  }\r\n\r\n  const blocks: RetryPromptContextBlock[] = [];\r\n  let budget = maxChars;\r\n  for (let i = 0; i < merged.length && i < maxBlocks && budget > 0; i++) {\r\n    const win = merged[i]!;\r\n    const rows: string[] = [];\r\n    for (let line = win.start; line <= win.end; line++) {\r\n      const raw = lines[line - 1] ?? \"\";\r\n      rows.push(includeLineNumbers ? `${line.toString().padStart(4, \" \")} | ${raw}` : raw);\r\n    }\r\n\r\n    let text = rows.join(\"\\n\");\r\n    if (text.length > budget) {\r\n      text = `${text.slice(0, Math.max(0, budget - 18))}\\n...[truncated]`;\r\n    }\r\n\r\n    if (text.length === 0) continue;\r\n\r\n    blocks.push({\r\n      startLine: win.start,\r\n      endLine: win.end,\r\n      text,\r\n    });\r\n\r\n    budget -= text.length;\r\n  }\r\n\r\n  return blocks;\r\n}\r\n\r\nfunction applyContextRedaction(\r\n  blocks: RetryPromptContextBlock[],\r\n  options: Required<Omit<RetryPromptOptions, \"redactPaths\" | \"redactRegex\">> &\r\n    Pick<RetryPromptOptions, \"redactPaths\" | \"redactRegex\">,\r\n  errors: ZodIssue[],\r\n): RetryPromptContextBlock[] {\r\n  if (blocks.length === 0) return blocks;\r\n\r\n  const keysToMask = new Set<string>();\r\n  for (const pointer of options.redactPaths ?? []) {\r\n    const parts = pointer.split(\"/\").filter(Boolean);\r\n    const last = parts[parts.length - 1];\r\n    if (last) keysToMask.add(last);\r\n  }\r\n\r\n  for (const issue of errors) {\r\n    const pointer = `/${issue.path.map(String).join(\"/\")}`;\r\n    if ((options.redactPaths ?? []).includes(pointer)) {\r\n      const last = issue.path[issue.path.length - 1];\r\n      if (typeof last === \"string\") {\r\n        keysToMask.add(last);\r\n      }\r\n    }\r\n  }\r\n\r\n  return blocks.map((block) => ({\r\n    ...block,\r\n    text: redactBlockText(block.text, keysToMask, options.redactRegex),\r\n  }));\r\n}\r\n\r\nfunction redactBlockText(\r\n  input: string,\r\n  keysToMask: Set<string>,\r\n  redactRegex?: RegExp[],\r\n): string {\r\n  let out = input;\r\n\r\n  for (const key of keysToMask) {\r\n    const escaped = escapeRegex(key);\r\n    const rx = new RegExp(`(\"${escaped}\"\\\\s*:\\\\s*)(.+)$`, \"gm\");\r\n    out = out.replace(rx, \"$1\\\"[REDACTED]\\\"\");\r\n  }\r\n\r\n  for (const rx of redactRegex ?? []) {\r\n    out = out.replace(rx, \"[REDACTED]\");\r\n  }\r\n\r\n  return out;\r\n}\r\n\r\nfunction applyRawRedaction(\r\n  rawSnippet: string | undefined,\r\n  options: Required<Omit<RetryPromptOptions, \"redactPaths\" | \"redactRegex\">> &\r\n    Pick<RetryPromptOptions, \"redactPaths\" | \"redactRegex\">,\r\n): string | undefined {\r\n  if (rawSnippet === undefined) return undefined;\r\n  let out = rawSnippet;\r\n\r\n  for (const rx of options.redactRegex ?? []) {\r\n    out = out.replace(rx, \"[REDACTED]\");\r\n  }\r\n\r\n  return out;\r\n}\r\n\r\nfunction inferLikelyParseLine(rawSnippet: string): number {\r\n  const lines = rawSnippet.split(/\\r?\\n/);\r\n  for (let i = lines.length - 1; i >= 0; i--) {\r\n    if (lines[i]!.trim().length > 0) return i + 1;\r\n  }\r\n  return 1;\r\n}\r\n\r\nfunction clampLine(line: number, rawSnippet: string): number {\r\n  const count = Math.max(1, rawSnippet.split(/\\r?\\n/).length);\r\n  if (!Number.isFinite(line)) return 1;\r\n  return Math.min(count, Math.max(1, Math.floor(line)));\r\n}\r\n\r\nfunction escapeRegex(input: string): string {\r\n  return input.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n}\r\n","/**\r\n * Telemetry utilities — environment-agnostic high-resolution timing.\r\n *\r\n * Uses `performance.now()` which is available in all target runtimes:\r\n * browsers, Node.js, Deno, Bun, and Cloudflare Workers.\r\n *\r\n * @module\r\n */\r\n\r\n/**\r\n * Create a high-resolution timer.\r\n *\r\n * @returns An object with a `stop()` method that returns elapsed milliseconds.\r\n *\r\n * @example\r\n * ```ts\r\n * const timer = createTimer();\r\n * // … do work …\r\n * const elapsed = timer.stop(); // e.g. 0.42\r\n * ```\r\n */\r\nexport function createTimer(): { stop: () => number } {\r\n  const start = performance.now();\r\n  return {\r\n    stop: () => performance.now() - start,\r\n  };\r\n}\r\n","import type { ZodIssue, ZodTypeAny, infer as ZodInfer } from \"zod\";\r\nimport type {\r\n  GuardResult,\r\n  TelemetryData,\r\n  GuardOptions,\r\n  GuardHeuristicOptions,\r\n  RetryPromptContextBlock,\r\n  GuardSemanticResolution,\r\n} from \"./types.js\";\r\nimport { dirtyParse } from \"./dirty-parser/index.js\";\r\nimport { validateWithSchema } from \"./validation/index.js\";\r\nimport { generateRetryPrompt } from \"./retry/index.js\";\r\nimport { createTimer } from \"./telemetry.js\";\r\n\r\nfunction createParseFailureError(): ZodIssue {\r\n  return {\r\n    code: \"custom\",\r\n    path: [],\r\n    message: \"Input could not be parsed as JSON\",\r\n  } as ZodIssue;\r\n}\r\n\r\n/**\r\n * Validate and repair raw LLM output against a Zod schema.\r\n *\r\n * `guard()` is the single entry-point for Reforge. It runs a three-stage\r\n * pipeline — **parse → validate → report** — and returns a typed,\r\n * discriminated-union result that is safe to pattern-match on.\r\n *\r\n * ### Pipeline\r\n * 1. **Dirty Parse** — Extracts JSON from markdown wrappers, fixes trailing\r\n *    commas / unquoted keys / single quotes, and closes truncated brackets.\r\n * 2. **Schema Validation** — Runs `schema.safeParse()` with automatic\r\n *    coercion for common LLM type mismatches (string `\"true\"` → boolean, etc.).\r\n * 3. **Result** — Returns either `{ success: true, data, telemetry }` or\r\n *    `{ success: false, retryPrompt, errors, telemetry }`.\r\n *\r\n * ### Guarantees\r\n * - **Never throws.** All error paths return a typed failure object.\r\n * - **Synchronous.** No async, no network calls, no I/O.\r\n * - **Pure.** No global state is mutated.\r\n * - **Fast.** Targets < 5 ms for a 2 KB input string.\r\n *\r\n * @typeParam T - A Zod schema type (e.g. `z.ZodObject<…>`).\r\n * @param llmOutput - The raw string produced by an LLM.\r\n * @param schema    - The Zod schema the output must conform to.\r\n * @returns A `GuardResult<z.infer<T>>` — either success with typed data\r\n *          or failure with a retry prompt and error details.\r\n *\r\n * @example\r\n * ```ts\r\n * import { z } from 'zod';\r\n * import { guard } from 'reforge-ai';\r\n *\r\n * const UserSchema = z.object({\r\n *   name: z.string(),\r\n *   age:  z.number(),\r\n * });\r\n *\r\n * const result = guard('```json\\n{\"name\": \"Alice\", \"age\": 30,}\\n```', UserSchema);\r\n *\r\n * if (result.success) {\r\n *   console.log(result.data);       // { name: \"Alice\", age: 30 }\r\n *   console.log(result.isRepaired); // true\r\n *   console.log(result.telemetry);  // { durationMs: 0.4, status: \"repaired_natively\" }\r\n * } else {\r\n *   // Append result.retryPrompt to your LLM conversation\r\n *   console.log(result.retryPrompt);\r\n * }\r\n * ```\r\n */\r\nexport function guard<T extends ZodTypeAny>(\r\n  llmOutput: string,\r\n  schema: T,\r\n  options?: GuardOptions,\r\n): GuardResult<ZodInfer<T>> {\r\n  const timer = createTimer();\r\n  const heuristics = resolveHeuristics(options);\r\n  let retryContextBlocks: RetryPromptContextBlock[] = [];\r\n\r\n  // --- Safety: handle non-string input at runtime boundary ---\r\n  if (typeof llmOutput !== \"string\") {\r\n    const parseError = createParseFailureError();\r\n    const telemetry: TelemetryData = {\r\n      durationMs: timer.stop(),\r\n      status: \"failed\",\r\n    };\r\n    return {\r\n      success: false,\r\n      retryPrompt: generateRetryPrompt([], undefined, {\r\n        options: options?.retryPrompt,\r\n        strategy: options?.retryPromptStrategy,\r\n        onContextBlocks: (blocks) => {\r\n          retryContextBlocks = blocks;\r\n        },\r\n      }),\r\n      errors: [parseError],\r\n      telemetry,\r\n      debug: options?.debug\r\n        ? {\r\n            retryContextBlocks:\r\n              retryContextBlocks.length > 0 ? retryContextBlocks : undefined,\r\n          }\r\n        : undefined,\r\n    };\r\n  }\r\n\r\n  // --- Stage 1: Dirty Parse ---\r\n  const parseResult = dirtyParse(llmOutput, { heuristics });\r\n\r\n  if (!parseResult.success) {\r\n    const parseError = createParseFailureError();\r\n    const telemetry: TelemetryData = {\r\n      durationMs: timer.stop(),\r\n      status: \"failed\",\r\n    };\r\n    return {\r\n      success: false,\r\n      retryPrompt: generateRetryPrompt([], parseResult.raw, {\r\n        options: options?.retryPrompt,\r\n        strategy: options?.retryPromptStrategy,\r\n        parseErrorLine: parseResult.likelyErrorLine,\r\n        onContextBlocks: (blocks) => {\r\n          retryContextBlocks = blocks;\r\n        },\r\n      }),\r\n      errors: [parseError],\r\n      telemetry,\r\n      debug: options?.debug\r\n        ? {\r\n            extractedText: parseResult.extractedText,\r\n            repairedText: parseResult.repairedText,\r\n            appliedRepairs: parseResult.appliedRepairs,\r\n            likelyErrorLine: parseResult.likelyErrorLine,\r\n            retryContextBlocks:\r\n              retryContextBlocks.length > 0 ? retryContextBlocks : undefined,\r\n          }\r\n        : undefined,\r\n    };\r\n  }\r\n\r\n  // --- Stage 2: Schema Validation (with coercion) ---\r\n  const validationResult = validateWithSchema(parseResult.value, schema);\r\n\r\n  if (validationResult.success) {\r\n    const status = parseResult.isRepaired ? \"repaired_natively\" : \"clean\";\r\n    const telemetry: TelemetryData = {\r\n      durationMs: timer.stop(),\r\n      status,\r\n      coercedPaths: [],\r\n    };\r\n    return {\r\n      success: true,\r\n      data: validationResult.data,\r\n      telemetry,\r\n      isRepaired: parseResult.isRepaired,\r\n      debug: options?.debug\r\n        ? {\r\n            extractedText: parseResult.extractedText,\r\n            repairedText: parseResult.repairedText,\r\n            appliedRepairs: parseResult.appliedRepairs,\r\n          }\r\n        : undefined,\r\n    };\r\n  }\r\n\r\n  const semanticMode = options?.semanticResolution?.mode ?? \"retry\";\r\n  if (semanticMode === \"clamp\") {\r\n    const coercion = applySemanticCoercion(\r\n      parseResult.value,\r\n      validationResult.errors,\r\n      options?.semanticResolution,\r\n    );\r\n\r\n    if (coercion.appliedPaths.length > 0) {\r\n      const secondPass = validateWithSchema(coercion.value, schema);\r\n      if (secondPass.success) {\r\n        const telemetry: TelemetryData = {\r\n          durationMs: timer.stop(),\r\n          status: \"coerced_locally\",\r\n          coercedPaths: coercion.appliedPaths,\r\n        };\r\n\r\n        return {\r\n          success: true,\r\n          data: secondPass.data,\r\n          telemetry,\r\n          isRepaired: parseResult.isRepaired,\r\n          debug: options?.debug\r\n            ? {\r\n                extractedText: parseResult.extractedText,\r\n                repairedText: safeStringify(secondPass.data) ?? parseResult.repairedText,\r\n                appliedRepairs: parseResult.appliedRepairs,\r\n              }\r\n            : undefined,\r\n        };\r\n      }\r\n    }\r\n  }\r\n\r\n  // --- Stage 3: Failure — generate retry prompt ---\r\n  const telemetry: TelemetryData = {\r\n    durationMs: timer.stop(),\r\n    status: \"failed\",\r\n    coercedPaths: [],\r\n  };\r\n  const sourceTextForContext =\r\n    parseResult.repairedText ??\r\n    safeStringify(parseResult.value) ??\r\n    undefined;\r\n\r\n  return {\r\n    success: false,\r\n    retryPrompt: generateRetryPrompt(validationResult.errors, undefined, {\r\n      options: options?.retryPrompt,\r\n      sourceText: sourceTextForContext,\r\n      strategy: options?.retryPromptStrategy,\r\n      onContextBlocks: (blocks) => {\r\n        retryContextBlocks = blocks;\r\n      },\r\n    }),\r\n    errors: validationResult.errors,\r\n    telemetry,\r\n    debug: options?.debug\r\n      ? {\r\n          extractedText: parseResult.extractedText,\r\n          repairedText: parseResult.repairedText,\r\n          appliedRepairs: parseResult.appliedRepairs,\r\n          retryContextBlocks:\r\n            retryContextBlocks.length > 0 ? retryContextBlocks : undefined,\r\n        }\r\n      : undefined,\r\n  };\r\n}\r\n\r\nfunction applySemanticCoercion(\r\n  input: unknown,\r\n  issues: ZodIssue[],\r\n  resolution?: GuardSemanticResolution,\r\n): { value: unknown; appliedPaths: string[] } {\r\n  const cloned = deepClone(input);\r\n  const appliedPaths = new Set<string>();\r\n\r\n  for (const issue of issues) {\r\n    const path = issue.path;\r\n    const currentValue = getAtPath(cloned, path);\r\n    const nextValue = resolveSemanticValue({\r\n      path,\r\n      issue,\r\n      currentValue,\r\n      resolution,\r\n    });\r\n\r\n    if (nextValue !== undefined && nextValue !== currentValue) {\r\n      if (setAtPath(cloned, path, nextValue)) {\r\n        appliedPaths.add(toPathString(path));\r\n      }\r\n    }\r\n  }\r\n\r\n  return {\r\n    value: cloned,\r\n    appliedPaths: [...appliedPaths],\r\n  };\r\n}\r\n\r\nfunction resolveSemanticValue(input: {\r\n  path: (string | number)[];\r\n  issue: ZodIssue;\r\n  currentValue: unknown;\r\n  resolution?: GuardSemanticResolution;\r\n}): unknown {\r\n  const { issue, path, currentValue, resolution } = input;\r\n\r\n  if (resolution?.resolver) {\r\n    const custom = resolution.resolver({ path, issue, currentValue });\r\n    if (custom !== undefined) return custom;\r\n  }\r\n\r\n  const pointer = toPathPointer(path);\r\n  if (resolution?.pathDefaults && pointer in resolution.pathDefaults) {\r\n    return resolution.pathDefaults[pointer];\r\n  }\r\n\r\n  if (issue.code === \"too_small\" && issue.type === \"number\") {\r\n    const min =\r\n      typeof issue.minimum === \"bigint\"\r\n        ? Number(issue.minimum)\r\n        : issue.minimum;\r\n    const n = typeof currentValue === \"number\" ? currentValue : Number(currentValue);\r\n    if (!Number.isFinite(min)) {\r\n      return undefined;\r\n    }\r\n    if (Number.isFinite(n)) {\r\n      if (issue.exact) return min;\r\n      return issue.inclusive ? Math.max(n, min) : Math.max(n, min + Number.EPSILON);\r\n    }\r\n    return min;\r\n  }\r\n\r\n  if (issue.code === \"too_big\" && issue.type === \"number\") {\r\n    const max =\r\n      typeof issue.maximum === \"bigint\"\r\n        ? Number(issue.maximum)\r\n        : issue.maximum;\r\n    const n = typeof currentValue === \"number\" ? currentValue : Number(currentValue);\r\n    if (!Number.isFinite(max)) {\r\n      return undefined;\r\n    }\r\n    if (Number.isFinite(n)) {\r\n      if (issue.exact) return max;\r\n      return issue.inclusive ? Math.min(n, max) : Math.min(n, max - Number.EPSILON);\r\n    }\r\n    return max;\r\n  }\r\n\r\n  if (issue.code === \"invalid_enum_value\") {\r\n    if (Array.isArray(issue.options) && issue.options.length > 0) {\r\n      return issue.options[0];\r\n    }\r\n  }\r\n\r\n  return undefined;\r\n}\r\n\r\nfunction deepClone<T>(value: T): T {\r\n  if (typeof globalThis.structuredClone === \"function\") {\r\n    return globalThis.structuredClone(value);\r\n  }\r\n\r\n  return JSON.parse(JSON.stringify(value)) as T;\r\n}\r\n\r\nfunction getAtPath(obj: unknown, path: (string | number)[]): unknown {\r\n  let cur: unknown = obj;\r\n  for (const segment of path) {\r\n    if (cur === null || typeof cur !== \"object\") return undefined;\r\n    cur = (cur as Record<string | number, unknown>)[segment];\r\n  }\r\n  return cur;\r\n}\r\n\r\nfunction setAtPath(obj: unknown, path: (string | number)[], value: unknown): boolean {\r\n  if (path.length === 0) return false;\r\n\r\n  let cur: unknown = obj;\r\n  for (let i = 0; i < path.length - 1; i++) {\r\n    const segment = path[i]!;\r\n    if (cur === null || typeof cur !== \"object\") return false;\r\n    cur = (cur as Record<string | number, unknown>)[segment];\r\n  }\r\n\r\n  if (cur === null || typeof cur !== \"object\") return false;\r\n  const leaf = path[path.length - 1]!;\r\n  (cur as Record<string | number, unknown>)[leaf] = value;\r\n  return true;\r\n}\r\n\r\nfunction toPathPointer(path: (string | number)[]): string {\r\n  return `/${path.map((s) => String(s)).join(\"/\")}`;\r\n}\r\n\r\nfunction toPathString(path: (string | number)[]): string {\r\n  if (path.length === 0) return \"$\";\r\n\r\n  let result = \"\";\r\n  for (const part of path) {\r\n    if (typeof part === \"number\") {\r\n      result += `[${part}]`;\r\n    } else if (result.length === 0) {\r\n      result += part;\r\n    } else {\r\n      result += `.${part}`;\r\n    }\r\n  }\r\n  return result;\r\n}\r\n\r\nfunction resolveHeuristics(options?: GuardOptions): GuardHeuristicOptions {\r\n  const profile = options?.profile ?? \"standard\";\r\n\r\n  const profileDefaults: Record<\r\n    \"safe\" | \"standard\" | \"aggressive\",\r\n    GuardHeuristicOptions\r\n  > = {\r\n    safe: {\r\n      escapedQuotes: false,\r\n      singleQuotes: true,\r\n      stripComments: false,\r\n      normalizePythonLiterals: false,\r\n      unquotedKeys: true,\r\n      trailingCommas: true,\r\n    },\r\n    standard: {\r\n      escapedQuotes: true,\r\n      singleQuotes: true,\r\n      stripComments: true,\r\n      normalizePythonLiterals: true,\r\n      unquotedKeys: true,\r\n      trailingCommas: true,\r\n    },\r\n    aggressive: {\r\n      escapedQuotes: true,\r\n      singleQuotes: true,\r\n      stripComments: true,\r\n      normalizePythonLiterals: true,\r\n      unquotedKeys: true,\r\n      trailingCommas: true,\r\n    },\r\n  };\r\n\r\n  return {\r\n    ...profileDefaults[profile],\r\n    ...(options?.heuristics ?? {}),\r\n  };\r\n}\r\n\r\nfunction safeStringify(value: unknown): string | null {\r\n  try {\r\n    return JSON.stringify(value, null, 2);\r\n  } catch {\r\n    return null;\r\n  }\r\n}\r\n","import type { ZodTypeAny, infer as ZodInfer } from \"zod\";\r\nimport type {\r\n  ReforgeProvider,\r\n  Message,\r\n  ForgeOptions,\r\n  ForgeResult,\r\n  ForgeTelemetry,\r\n  ForgeAttemptDetail,\r\n  ForgeFailurePayload,\r\n  ProviderCallOptions,\r\n  ForgeProviderHop,\r\n} from \"./types.js\";\r\nimport { guard } from \"../guard.js\";\r\nimport { createTimer } from \"../telemetry.js\";\r\n\r\nconst RETRY_ASSISTANT_MAX_CHARS = 2000;\r\nconst DEFAULT_MAX_AGENT_ITERATIONS = 5;\r\nconst DEFAULT_TOOL_TIMEOUT_MS = 15_000;\r\n\r\nexport class ForgeNetworkError extends Error {\r\n  readonly providerIndex: number;\r\n  readonly providerId: string;\r\n  readonly causeValue: unknown;\r\n\r\n  constructor(message: string, providerIndex: number, providerId: string, causeValue: unknown) {\r\n    super(message);\r\n    this.name = \"ForgeNetworkError\";\r\n    this.providerIndex = providerIndex;\r\n    this.providerId = providerId;\r\n    this.causeValue = causeValue;\r\n  }\r\n}\r\n\r\nfunction truncateAssistantRetryContent(raw: string): string {\r\n  if (raw.length <= RETRY_ASSISTANT_MAX_CHARS) {\r\n    return raw;\r\n  }\r\n\r\n  const truncatedChars = raw.length - RETRY_ASSISTANT_MAX_CHARS;\r\n  return `${raw.slice(0, RETRY_ASSISTANT_MAX_CHARS)}\\n...[truncated ${truncatedChars} chars]`;\r\n}\r\n\r\nfunction normalizeMaxRetries(value: number | undefined): number {\r\n  if (value === undefined) return 3;\r\n  if (!Number.isFinite(value)) return 0;\r\n  return Math.max(0, Math.floor(value));\r\n}\r\n\r\nfunction resolveMaxRetries<TNativeOptions extends Record<string, unknown>>(\r\n  options?: ForgeOptions<TNativeOptions>,\r\n): number {\r\n  return normalizeMaxRetries(options?.retryPolicy?.maxRetries ?? options?.maxRetries);\r\n}\r\n\r\nfunction resolveProviderOptions<TNativeOptions extends Record<string, unknown>>(\r\n  attempt: number,\r\n  options?: ForgeOptions<TNativeOptions>,\r\n): TNativeOptions | undefined {\r\n  const base = options?.providerOptions;\r\n  const mutate = options?.retryPolicy?.mutateProviderOptions;\r\n  if (!mutate) return base;\r\n\r\n  return mutate(attempt, base);\r\n}\r\n\r\nfunction normalizeProviders<TNativeOptions extends Record<string, unknown>>(\r\n  providerOrProviders: ReforgeProvider<TNativeOptions> | ReforgeProvider<TNativeOptions>[],\r\n): ReforgeProvider<TNativeOptions>[] {\r\n  return Array.isArray(providerOrProviders)\r\n    ? providerOrProviders\r\n    : [providerOrProviders];\r\n}\r\n\r\nfunction isIntrinsicNetworkError(error: unknown): boolean {\r\n  if (error == null) return false;\r\n\r\n  const msg =\r\n    typeof error === \"string\"\r\n      ? error\r\n      : error instanceof Error\r\n        ? error.message\r\n        : JSON.stringify(error);\r\n  const lower = msg.toLowerCase();\r\n\r\n  return (\r\n    lower.includes(\"429\") ||\r\n    lower.includes(\"500\") ||\r\n    lower.includes(\"503\") ||\r\n    lower.includes(\"rate limit\") ||\r\n    lower.includes(\"timeout\") ||\r\n    lower.includes(\"network\") ||\r\n    lower.includes(\"econnreset\") ||\r\n    lower.includes(\"etimedout\")\r\n  );\r\n}\r\n\r\ntype ParsedToolCall = {\r\n  id: string;\r\n  name: string;\r\n  arguments: string;\r\n};\r\n\r\nfunction extractToolCalls(raw: string): ParsedToolCall[] {\r\n  try {\r\n    const parsed = JSON.parse(raw) as unknown;\r\n    if (!parsed || typeof parsed !== \"object\") return [];\r\n\r\n    const calls = (parsed as { tool_calls?: unknown }).tool_calls;\r\n    if (!Array.isArray(calls)) return [];\r\n\r\n    const normalized: ParsedToolCall[] = [];\r\n    for (let i = 0; i < calls.length; i++) {\r\n      const call = calls[i];\r\n      if (!call || typeof call !== \"object\") continue;\r\n\r\n      const id = String((call as { id?: unknown }).id ?? `tool-call-${i + 1}`);\r\n      const name = (call as { name?: unknown }).name;\r\n      const args = (call as { arguments?: unknown }).arguments;\r\n      if (typeof name !== \"string\") continue;\r\n\r\n      let serializedArgs = \"{}\";\r\n      if (typeof args === \"string\") {\r\n        serializedArgs = args;\r\n      } else if (args !== undefined) {\r\n        serializedArgs = JSON.stringify(args);\r\n      }\r\n\r\n      normalized.push({ id, name, arguments: serializedArgs });\r\n    }\r\n\r\n    return normalized;\r\n  } catch {\r\n    return [];\r\n  }\r\n}\r\n\r\nasync function runWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\r\n  let timeoutId: ReturnType<typeof setTimeout> | undefined;\r\n  const timeoutPromise = new Promise<never>((_, reject) => {\r\n    timeoutId = setTimeout(() => {\r\n      reject(new Error(`Tool execution timed out after ${timeoutMs}ms`));\r\n    }, timeoutMs);\r\n  });\r\n\r\n  try {\r\n    return await Promise.race([promise, timeoutPromise]);\r\n  } finally {\r\n    if (timeoutId !== undefined) {\r\n      clearTimeout(timeoutId);\r\n    }\r\n  }\r\n}\r\n\r\n/**\r\n * End-to-end structured LLM output: call a provider, validate with\r\n * `guard()`, and automatically retry on failure.\r\n *\r\n * @typeParam T - A Zod schema type.\r\n * @param provider  - A `ReforgeProvider` (built-in adapter or custom).\r\n * @param messages  - The conversation messages to send to the LLM.\r\n * @param schema    - The Zod schema the output must conform to.\r\n * @param options   - Optional configuration (maxRetries, providerOptions).\r\n * @returns A `ForgeResult<z.infer<T>>` with telemetry.\r\n */\r\nexport async function forge<\r\n  T extends ZodTypeAny,\r\n  TNativeOptions extends Record<string, unknown> = ProviderCallOptions,\r\n>(\r\n  provider: ReforgeProvider<TNativeOptions> | ReforgeProvider<TNativeOptions>[],\r\n  messages: Message[],\r\n  schema: T,\r\n  options?: ForgeOptions<TNativeOptions>,\r\n): Promise<ForgeResult<ZodInfer<T>>> {\r\n  const providers = normalizeProviders(provider);\r\n  if (providers.length === 0) {\r\n    throw new Error(\"forge requires at least one provider\");\r\n  }\r\n\r\n  const maxRetries = resolveMaxRetries<TNativeOptions>(options);\r\n  const totalAttempts = 1 + maxRetries;\r\n  const timer = createTimer();\r\n  const maxAgentIterations = Math.max(1, options?.maxAgentIterations ?? DEFAULT_MAX_AGENT_ITERATIONS);\r\n  const toolTimeoutMs = Math.max(1, options?.toolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS);\r\n\r\n  // Clone messages so we never mutate the caller's array\r\n  const conversation: Message[] = [...messages];\r\n\r\n  let lastErrors: import(\"zod\").ZodIssue[] = [];\r\n  let lastRetryPrompt = \"Your previous response could not be parsed as JSON. The schema is still in your context — return ONLY valid JSON.\";\r\n  let lastTelemetry: import(\"../types.js\").TelemetryData = {\r\n    durationMs: 0,\r\n    status: \"failed\",\r\n  };\r\n  const attemptDetails: ForgeAttemptDetail[] = [];\r\n  const providerHops: ForgeProviderHop[] = [];\r\n  let networkDurationMs = 0;\r\n  let toolExecutionDurationMs = 0;\r\n\r\n  let providerIndex = 0;\r\n  let attempt = 0;\r\n\r\n  while (providerIndex < providers.length && attempt < totalAttempts) {\r\n    const activeProvider = providers[providerIndex]!;\r\n    attempt++;\r\n    options?.onEvent?.({ kind: \"attempt_start\", attempt, totalAttempts });\r\n\r\n    const providerOptions = resolveProviderOptions<TNativeOptions>(attempt, options);\r\n    const callStartedAt = Date.now();\r\n    let raw = \"\";\r\n    try {\r\n      raw = await activeProvider.call(conversation, providerOptions);\r\n    } catch (error) {\r\n      const callDurationMs = Date.now() - callStartedAt;\r\n      networkDurationMs += callDurationMs;\r\n      providerHops.push({\r\n        providerId: activeProvider.id ?? `provider-${providerIndex}`,\r\n        attempt,\r\n        succeeded: false,\r\n        durationMs: callDurationMs,\r\n      });\r\n\r\n      if (!isIntrinsicNetworkError(error)) {\r\n        throw error;\r\n      }\r\n\r\n      if (providerIndex < providers.length - 1) {\r\n        attempt--;\r\n        providerIndex++;\r\n        continue;\r\n      }\r\n\r\n      throw new ForgeNetworkError(\r\n        `Intrinsic network failure on provider '${activeProvider.id ?? `provider-${providerIndex}`}' and no fallback provider was available`,\r\n        providerIndex,\r\n        activeProvider.id ?? `provider-${providerIndex}`,\r\n        error,\r\n      );\r\n    }\r\n\r\n    const callDurationMs = Date.now() - callStartedAt;\r\n    networkDurationMs += callDurationMs;\r\n    providerHops.push({\r\n      providerId: activeProvider.id ?? `provider-${providerIndex}`,\r\n      attempt,\r\n      succeeded: false,\r\n      durationMs: callDurationMs,\r\n    });\r\n\r\n    let agentIterations = 0;\r\n    let fallbackTriggeredFromToolLoop = false;\r\n    let toolCalls = extractToolCalls(raw);\r\n    while (toolCalls.length > 0) {\r\n      agentIterations++;\r\n      if (agentIterations > maxAgentIterations) {\r\n        throw new Error(`maxAgentIterations (${maxAgentIterations}) exceeded`);\r\n      }\r\n\r\n      const toolMessages: Message[] = [];\r\n      for (const call of toolCalls) {\r\n        const toolDef = options?.tools?.[call.name];\r\n        if (!toolDef) {\r\n          toolMessages.push({\r\n            role: \"tool\",\r\n            content: `Tool '${call.name}' is not registered.`,\r\n            toolResponse: {\r\n              toolCallId: call.id,\r\n              name: call.name,\r\n              content: `Tool '${call.name}' is not registered.`,\r\n              isError: true,\r\n            },\r\n          });\r\n          continue;\r\n        }\r\n\r\n        let parsedArgs: unknown;\r\n        try {\r\n          parsedArgs = JSON.parse(call.arguments);\r\n        } catch {\r\n          parsedArgs = {};\r\n        }\r\n\r\n        const validated = toolDef.schema.safeParse(parsedArgs);\r\n        if (!validated.success) {\r\n          toolMessages.push({\r\n            role: \"tool\",\r\n            content: `Tool '${call.name}' received invalid arguments`,\r\n            toolResponse: {\r\n              toolCallId: call.id,\r\n              name: call.name,\r\n              content: `Tool '${call.name}' received invalid arguments`,\r\n              isError: true,\r\n            },\r\n          });\r\n          continue;\r\n        }\r\n\r\n        const started = Date.now();\r\n        try {\r\n          const result = await runWithTimeout(\r\n            Promise.resolve(toolDef.execute(validated.data)),\r\n            toolTimeoutMs,\r\n          );\r\n          toolExecutionDurationMs += Date.now() - started;\r\n\r\n          const serialized =\r\n            typeof result === \"string\" ? result : JSON.stringify(result);\r\n          toolMessages.push({\r\n            role: \"tool\",\r\n            content: serialized,\r\n            toolResponse: {\r\n              toolCallId: call.id,\r\n              name: call.name,\r\n              content: serialized,\r\n            },\r\n          });\r\n        } catch (error) {\r\n          toolExecutionDurationMs += Date.now() - started;\r\n          const msg = error instanceof Error ? error.message : \"Unknown tool error\";\r\n          toolMessages.push({\r\n            role: \"tool\",\r\n            content: `Tool ${call.name} failed with message: ${msg}`,\r\n            toolResponse: {\r\n              toolCallId: call.id,\r\n              name: call.name,\r\n              content: `Tool ${call.name} failed with message: ${msg}`,\r\n              isError: true,\r\n            },\r\n          });\r\n        }\r\n      }\r\n\r\n      conversation.push(\r\n        {\r\n          role: \"assistant\",\r\n          content: raw,\r\n          toolCalls: toolCalls.map((c) => ({\r\n            id: c.id,\r\n            name: c.name,\r\n            arguments: c.arguments,\r\n          })),\r\n        },\r\n        ...toolMessages,\r\n      );\r\n\r\n      const loopCallStartedAt = Date.now();\r\n      try {\r\n        raw = await activeProvider.call(conversation, providerOptions);\r\n      } catch (error) {\r\n        const loopDurationMs = Date.now() - loopCallStartedAt;\r\n        networkDurationMs += loopDurationMs;\r\n        providerHops.push({\r\n          providerId: activeProvider.id ?? `provider-${providerIndex}`,\r\n          attempt,\r\n          succeeded: false,\r\n          durationMs: loopDurationMs,\r\n        });\r\n\r\n        if (!isIntrinsicNetworkError(error)) {\r\n          throw error;\r\n        }\r\n\r\n        if (providerIndex < providers.length - 1) {\r\n          attempt--;\r\n          providerIndex++;\r\n          fallbackTriggeredFromToolLoop = true;\r\n          break;\r\n        }\r\n\r\n        throw new ForgeNetworkError(\r\n          `Intrinsic network failure on provider '${activeProvider.id ?? `provider-${providerIndex}`}' and no fallback provider was available`,\r\n          providerIndex,\r\n          activeProvider.id ?? `provider-${providerIndex}`,\r\n          error,\r\n        );\r\n      }\r\n\r\n      const loopDurationMs = Date.now() - loopCallStartedAt;\r\n      networkDurationMs += loopDurationMs;\r\n      providerHops.push({\r\n        providerId: activeProvider.id ?? `provider-${providerIndex}`,\r\n        attempt,\r\n        succeeded: false,\r\n        durationMs: loopDurationMs,\r\n      });\r\n\r\n      toolCalls = extractToolCalls(raw);\r\n    }\r\n\r\n    if (fallbackTriggeredFromToolLoop) {\r\n      continue;\r\n    }\r\n\r\n    options?.onChunk?.(raw);\r\n\r\n    const wouldTruncate = raw.length > RETRY_ASSISTANT_MAX_CHARS;\r\n    options?.onEvent?.({\r\n      kind: \"provider_response\",\r\n      attempt,\r\n      rawLength: raw.length,\r\n      truncatedForRetry: wouldTruncate,\r\n    });\r\n\r\n    const result = guard(raw, schema, options?.guardOptions);\r\n    lastTelemetry = result.telemetry;\r\n    attemptDetails.push({\r\n      attempt,\r\n      durationMs: result.telemetry.durationMs,\r\n      status: result.telemetry.status,\r\n    });\r\n\r\n    if (result.success) {\r\n      const successStatus = result.telemetry.status as\r\n        | \"clean\"\r\n        | \"repaired_natively\"\r\n        | \"coerced_locally\";\r\n\r\n      options?.onEvent?.({\r\n        kind: \"guard_success\",\r\n        attempt,\r\n        status: successStatus,\r\n        durationMs: result.telemetry.durationMs,\r\n      });\r\n\r\n      const forgeTelemetry: ForgeTelemetry = {\r\n        durationMs: result.telemetry.durationMs,\r\n        status: result.telemetry.status,\r\n        attempts: attempt,\r\n        totalDurationMs: timer.stop(),\r\n        networkDurationMs,\r\n        toolExecutionDurationMs,\r\n        providerHops: providerHops.map((hop, idx) =>\r\n          idx === providerHops.length - 1\r\n            ? { ...hop, succeeded: true }\r\n            : hop,\r\n        ),\r\n        attemptDetails,\r\n      };\r\n\r\n      options?.onEvent?.({\r\n        kind: \"finished\",\r\n        success: true,\r\n        attempts: attempt,\r\n        totalDurationMs: forgeTelemetry.totalDurationMs,\r\n      });\r\n\r\n      return {\r\n        success: true,\r\n        data: result.data,\r\n        telemetry: forgeTelemetry,\r\n        isRepaired: result.isRepaired,\r\n      };\r\n    }\r\n\r\n    lastErrors = result.errors;\r\n    lastRetryPrompt = result.retryPrompt;\r\n\r\n    options?.onEvent?.({\r\n      kind: \"guard_failure\",\r\n      attempt,\r\n      durationMs: result.telemetry.durationMs,\r\n      errorCount: result.errors.length,\r\n    });\r\n\r\n    const failurePayload: ForgeFailurePayload = {\r\n      errors: result.errors,\r\n      retryPrompt: result.retryPrompt,\r\n    };\r\n\r\n    const shouldRetry = options?.retryPolicy?.shouldRetry\r\n      ? options.retryPolicy.shouldRetry(failurePayload, attempt)\r\n      : true;\r\n\r\n    // Don't append retry messages after the final attempt\r\n    if (attempt < totalAttempts && shouldRetry) {\r\n      options?.onRetry?.(attempt, {\r\n        errors: result.errors,\r\n        retryPrompt: result.retryPrompt,\r\n      });\r\n\r\n      options?.onEvent?.({\r\n        kind: \"retry_scheduled\",\r\n        attempt,\r\n        nextAttempt: attempt + 1,\r\n        reason: \"guard_failure\",\r\n      });\r\n\r\n      const assistantRetryContent = truncateAssistantRetryContent(raw);\r\n\r\n      conversation.push(\r\n        { role: \"assistant\", content: assistantRetryContent },\r\n        { role: \"user\", content: result.retryPrompt },\r\n      );\r\n    } else if (!shouldRetry) {\r\n      break;\r\n    }\r\n  }\r\n\r\n  // All attempts exhausted\r\n  const forgeTelemetry: ForgeTelemetry = {\r\n    durationMs: lastTelemetry.durationMs,\r\n    status: \"failed\",\r\n    attempts: attemptDetails.length,\r\n    totalDurationMs: timer.stop(),\r\n    networkDurationMs,\r\n    toolExecutionDurationMs,\r\n    providerHops,\r\n    attemptDetails,\r\n  };\r\n\r\n  options?.onEvent?.({\r\n    kind: \"finished\",\r\n    success: false,\r\n    attempts: attemptDetails.length,\r\n    totalDurationMs: forgeTelemetry.totalDurationMs,\r\n  });\r\n\r\n  return {\r\n    success: false,\r\n    errors: lastErrors,\r\n    retryPrompt: lastRetryPrompt,\r\n    telemetry: forgeTelemetry,\r\n  };\r\n}\r\n","import type { ZodTypeAny, infer as ZodInfer } from \"zod\";\r\nimport { forge } from \"./forge.js\";\r\nimport type {\r\n  ForgeFallbackOptions,\r\n  ForgeFallbackProvider,\r\n  ForgeResult,\r\n} from \"./types.js\";\r\n\r\n/**\r\n * Try multiple providers in order until one succeeds.\r\n *\r\n * Each provider can define its own `maxAttempts` and `providerOptions`.\r\n * The helper preserves the same `ForgeResult<T>` contract as `forge()`.\r\n */\r\nexport async function forgeWithFallback<T extends ZodTypeAny>(\r\n  providers: ForgeFallbackProvider[],\r\n  messages: import(\"./types.js\").Message[],\r\n  schema: T,\r\n  options?: ForgeFallbackOptions,\r\n): Promise<ForgeResult<ZodInfer<T>>> {\r\n  if (providers.length === 0) {\r\n    throw new Error(\"forgeWithFallback requires at least one provider\");\r\n  }\r\n\r\n  let lastFailure: ForgeResult<ZodInfer<T>> | null = null;\r\n\r\n  for (let i = 0; i < providers.length; i++) {\r\n    const entry = providers[i]!;\r\n\r\n    const result = await forge(entry.provider, messages, schema, {\r\n      maxRetries: Math.max(0, (entry.maxAttempts ?? 1) - 1),\r\n      providerOptions: entry.providerOptions,\r\n      guardOptions: options?.guardOptions,\r\n      onRetry: options?.onRetry,\r\n      onEvent: options?.onEvent,\r\n    });\r\n\r\n    if (result.success) {\r\n      return result;\r\n    }\r\n\r\n    lastFailure = result;\r\n\r\n    if (i < providers.length - 1) {\r\n      options?.onProviderFallback?.(i, i + 1);\r\n    }\r\n  }\r\n\r\n  return lastFailure as ForgeResult<ZodInfer<T>>;\r\n}\r\n"],"mappings":";;;;;;;;;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CAAC;AAED,QAAI,OAAO,SAAS;AAClB,aAAO;AAAA,IACT;AAEA,kBAAc;AAEd,QAAI,IAAI,UAAU,SAAS,GAAG;AAC5B,eAAS,qBAAqB,GAAG,IAAI,CAAC;AAAA,IACxC;AAAA,EACF;AAEA,SAAO;AACT;","names":["content","extracted","appliedRepairs","strategyInput","telemetry","callDurationMs","result","loopDurationMs","forgeTelemetry"]}