{"version":3,"sources":["../src/self-debug.ts"],"names":["wrapToolWithSelfDebug","tool","selfDebugger","options","maxAttempts","args","context","attempt","currentArgs","lastError","result","err","decision","createLlmSelfDebugger","complete","error","prompt","text","body","start","end","parsed"],"mappings":"aAwCO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CAA4B,EAAC,CACb,CAChB,GAAI,CAACF,CAAAA,CAAK,QAAS,MAAM,IAAI,MAAM,CAAA,6BAAA,EAAgCA,CAAAA,CAAK,IAAI,CAAA,gBAAA,CAAkB,CAAA,CAC9F,IAAMG,CAAAA,CAAc,IAAA,CAAK,IAAI,CAAA,CAAGD,CAAAA,CAAQ,aAAe,CAAC,CAAA,CAExD,OAAO,CACL,GAAGF,EACH,MAAM,OAAA,CAAQI,EAAMC,CAAAA,CAAS,CAC3B,IAAIC,CAAAA,CAAU,CAAA,CACVC,EAAc,CAAE,GAAGH,CAAK,CAAA,CACxBI,CAAAA,CACJ,OACE,GAAI,CACF,IAAMC,EAAS,MAAMT,CAAAA,CAAK,QAASO,CAAAA,CAAaF,CAAO,EACvD,OAAAH,CAAAA,CAAQ,UAAU,CAAE,IAAA,CAAM,UAAW,IAAA,CAAMF,CAAAA,CAAK,KAAM,OAAA,CAAAM,CAAQ,CAAC,CAAA,CACxDG,CACT,OAASC,CAAAA,CAAK,CAQZ,GAPAF,CAAAA,CAAYE,CAAAA,YAAe,MAAQA,CAAAA,CAAM,IAAI,MAAM,MAAA,CAAOA,CAAG,CAAC,CAAA,CAC9DR,CAAAA,CAAQ,UAAU,CAChB,IAAA,CAAM,UACN,IAAA,CAAMF,CAAAA,CAAK,IAAA,CACX,OAAA,CAAAM,CAAAA,CACA,KAAA,CAAOE,EAAU,OACnB,CAAC,EACGF,CAAAA,EAAWH,CAAAA,CACb,MAAAD,CAAAA,CAAQ,OAAA,GAAU,CAAE,IAAA,CAAM,SAAA,CAAW,KAAMF,CAAAA,CAAK,IAAA,CAAM,QAAAM,CAAAA,CAAS,KAAA,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,UAAW,+BAAgC,CAClE,CAGA,IAAME,CAAAA,CAAAA,CADQD,CAAAA,CAAK,KAAA,CAAM,8BAA8B,CAAA,GACjC,CAAC,GAAKA,CAAAA,EAAM,IAAA,GAC5BE,CAAAA,CAAQD,CAAAA,CAAK,QAAQ,GAAG,CAAA,CACxBE,EAAMF,CAAAA,CAAK,WAAA,CAAY,GAAG,CAAA,CAChC,GAAIC,EAAQ,CAAA,EAAKC,CAAAA,EAAOD,CAAAA,CAAO,OAAO,CAAE,IAAA,CAAM,IAAA,CAAM,UAAW,8BAA+B,CAAA,CAE9F,GAAI,CACF,IAAME,EAAS,IAAA,CAAK,KAAA,CAAMH,EAAK,KAAA,CAAMC,CAAAA,CAAOC,EAAM,CAAC,CAAC,EACpD,OAAIC,CAAAA,CAAO,MAAA,CAAe,CAAE,KAAM,IAAA,CAAM,SAAA,CAAW,kBAAmB,CAAA,CAC/D,CAAE,KAAMA,CAAO,CACxB,MAAQ,CACN,OAAO,CAAE,IAAA,CAAM,IAAA,CAAM,UAAW,sCAAuC,CACzE,CACF,CACF","file":"self-debug.cjs","sourcesContent":["import type { ToolDefinition } from './types/tool'\n\nexport interface SelfDebugInput {\n  tool: ToolDefinition\n  args: Record<string, unknown>\n  error: Error\n  attempt: number\n}\n\nexport interface SelfDebugResult {\n  /** Either corrected arguments (retry) or `null` to give up. */\n  args: Record<string, unknown> | null\n  /** Free-form note appended to telemetry. */\n  reasoning?: string\n}\n\nexport type SelfDebugger = (input: SelfDebugInput) => Promise<SelfDebugResult> | SelfDebugResult\n\nexport interface SelfDebugOptions {\n  /** Max retry attempts after the original call. Default 2. */\n  maxAttempts?: number\n  /** Called on every failure + retry for observability. */\n  onEvent?: (event: {\n    type: 'failure' | 'retry' | 'give-up' | 'success'\n    tool: string\n    attempt: number\n    error?: string\n  }) => void\n}\n\n/**\n * Wrap any tool with a self-debug loop. When `execute` throws, the\n * configured `debugger` receives the error + args and can return\n * corrected args for another attempt. Give up by returning\n * `{ args: null }`. No retry happens on the original (attempt 0) call\n * — `maxAttempts` controls additional retries.\n *\n * This is the \"agent fixes itself\" pattern — typically plug in an\n * LLM call that reads the error + schema and emits new arguments.\n */\nexport function wrapToolWithSelfDebug(\n  tool: ToolDefinition,\n  selfDebugger: SelfDebugger,\n  options: SelfDebugOptions = {},\n): ToolDefinition {\n  if (!tool.execute) throw new Error(`wrapToolWithSelfDebug: tool \"${tool.name}\" has no execute`)\n  const maxAttempts = Math.max(0, options.maxAttempts ?? 2)\n\n  return {\n    ...tool,\n    async execute(args, context) {\n      let attempt = 0\n      let currentArgs = { ...args }\n      let lastError: Error | undefined\n      while (true) {\n        try {\n          const result = await tool.execute!(currentArgs, context)\n          options.onEvent?.({ type: 'success', tool: tool.name, attempt })\n          return result\n        } catch (err) {\n          lastError = err instanceof Error ? err : new Error(String(err))\n          options.onEvent?.({\n            type: 'failure',\n            tool: tool.name,\n            attempt,\n            error: lastError.message,\n          })\n          if (attempt >= maxAttempts) {\n            options.onEvent?.({ type: 'give-up', tool: tool.name, attempt, error: lastError.message })\n            throw lastError\n          }\n          const decision = await selfDebugger({ tool, args: currentArgs, error: lastError, attempt })\n          if (!decision.args) {\n            options.onEvent?.({ type: 'give-up', tool: tool.name, attempt, error: lastError.message })\n            throw lastError\n          }\n          attempt++\n          currentArgs = decision.args\n          options.onEvent?.({ type: 'retry', tool: tool.name, attempt })\n        }\n      }\n    },\n  }\n}\n\n/**\n * Debugger backed by a user-supplied async function that asks an LLM\n * to produce corrected JSON arguments. The helper handles prompt\n * construction + JSON parsing; plug in your own completion\n * (`runOnce(adapter, prompt)` via any runtime).\n */\nexport function createLlmSelfDebugger(\n  complete: (prompt: string) => Promise<string>,\n): SelfDebugger {\n  return async ({ tool, args, error, attempt }) => {\n    const prompt = `You are diagnosing a failed tool call and producing corrected arguments.\n\nTool: ${tool.name}\nDescription: ${tool.description ?? '(none)'}\nSchema: ${JSON.stringify(tool.schema ?? {}, null, 2)}\n\nPrevious arguments (attempt ${attempt + 1}):\n${JSON.stringify(args, null, 2)}\n\nError: ${error.message}\n\nEmit a single JSON object with corrected arguments that should make the tool succeed. If you cannot recover, emit {\"giveUp\": true}. Return JSON only, no commentary.`\n\n    let text: string\n    try {\n      text = await complete(prompt)\n    } catch {\n      return { args: null, reasoning: 'self-debugger upstream failed' }\n    }\n\n    const match = text.match(/```(?:json)?\\s*([\\s\\S]+?)```/)\n    const body = (match?.[1] ?? text).trim()\n    const start = body.indexOf('{')\n    const end = body.lastIndexOf('}')\n    if (start < 0 || end <= start) return { args: null, reasoning: 'no JSON in debugger response' }\n\n    try {\n      const parsed = JSON.parse(body.slice(start, end + 1)) as Record<string, unknown> & { giveUp?: boolean }\n      if (parsed.giveUp) return { args: null, reasoning: 'debugger gave up' }\n      return { args: parsed }\n    } catch {\n      return { args: null, reasoning: 'debugger response was not valid JSON' }\n    }\n  }\n}\n"]}