{"version":3,"sources":["../src/tables.ts","../src/errors.ts","../src/calc.ts","../src/adapter.ts","../src/tools.ts"],"names":["ArAgentsError","overlap","z","tool"],"mappings":";;;;;;;AA0BA,IAAM,eAAA,GAAkD;AAAA,EACtD;AAAA,IACE,QAAA,EAAU,WAAA;AAAA,IACV,MAAA,EAAQ,WAAA;AAAA,IACR,sBAAA,EAAwB,MAAA;AAAA;AAAA,IACxB,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,QAAA,EAAU,WAAA;AAAA,IACV,MAAA,EAAQ,cAAA;AAAA,IACR,sBAAA,EAAwB,CAAA;AAAA,IACxB,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,QAAA,EAAU,WAAA;AAAA,IACV,MAAA,EAAQ,QAAA;AAAA,IACR,sBAAA,EAAwB,CAAA;AAAA,IACxB,QAAA,EAAU;AAAA;AAEd,CAAA;AAsBA,IAAM,gBAAA,GAAmD;AAAA,EACvD;AAAA,IACE,QAAA,EAAU,YAAA;AAAA,IACV,MAAA,EAAQ,WAAA;AAAA,IACR,sBAAA,EAAwB,MAAA;AAAA;AAAA,IACxB,KAAA,EAAO;AAAA,MACL,EAAE,YAAA,EAAc,IAAA,EAAW,IAAA,EAAM,CAAA,EAAG,eAAe,CAAA,EAAE;AAAA,MACrD,EAAE,YAAA,EAAc,IAAA,EAAW,IAAA,EAAM,IAAA,EAAM,eAAe,CAAA,EAAE;AAAA,MACxD,EAAE,YAAA,EAAc,IAAA,EAAW,IAAA,EAAM,IAAA,EAAM,eAAe,IAAA,EAAQ;AAAA,MAC9D,EAAE,YAAA,EAAc,KAAA,EAAY,IAAA,EAAM,IAAA,EAAM,eAAe,KAAA,EAAQ;AAAA,MAC/D,EAAE,YAAA,EAAc,KAAA,EAAY,IAAA,EAAM,IAAA,EAAM,eAAe,MAAA,EAAU;AAAA,MACjE,EAAE,YAAA,EAAc,KAAA,EAAY,IAAA,EAAM,IAAA,EAAM,eAAe,MAAA,EAAU;A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SAAA,EAAWA,MAAE,OAAA;AAAQ,WACtB;AAAA,SACH,CACC,IAAI,CAAC;AAAA,OACT,CAAA;AAAA,MACD,OAAA,EAAS,OAAO,KAAA,KACd,eAAA,CAAgB;AAAA,QACd,QAAQ,KAAA,CAAM,MAAA;AAAA,QACd,WAAW,KAAA,CAAM,SAAA;AAAA,QACjB,SAAS,KAAA,CAAM;AAAA,OAChB;AAAA,KACJ,CAAA;AAAA,IAED,oBAAoBC,OAAA,CAAK;AAAA,MACvB,WAAA,EACE,gPAAA;AAAA,MACF,WAAA,EAAaD,MAAE,MAAA,CAAO;AAAA,QACpB,IAAA,EAAMA,KAAA,CAAE,OAAA,EAAQ,CAAE,SAAS,8BAA8B;AAAA,OAC1D,CAAA;AAAA,MACD,SAAS,OAAO,EAAE,MAAK,KACrB,OAAA,CAAQ,WAAW,IAAkD;AAAA,KACxE;AAAA,GACH;AAEA,EAAA,MAAM,MAAyD,EAAC;AAChE,EAAA,KAAA,MAAW,QAAQ,cAAA,EAAgB;AACjC,IAAA,IAAI,MAAA,CAAO,IAAI,IAAI,CAAA,MAAO,IAAI,CAAA,GAAI,SAAS,IAAI,CAAA;AAAA,EACjD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * SICORE rate tables — snapshot 2024-Q4.\n *\n * IMPORTANT: these are SNAPSHOTS. Mínimos no imponibles and rate\n * scales are updated regularly (RG 5531/2024 was the last major\n * adjustment). Verify against the current AFIP/ARCA regulation before\n * filing. Override the table via `RetentionInput.rateTable` whenever\n * the period being calculated falls outside this snapshot.\n *\n * Source documents:\n *   - RG 830/00 (régimen general)\n *   - RG 5531/2024 (última actualización de mínimos no-imponibles)\n *   - Anexo II tipos 28, 36, 49, 78\n *\n * All amounts in ARS centavos (integers). Rates as fractions.\n */\nimport type { SicoreRateEntry } from \"./types\";\n\n/**\n * Servicios — Locaciones de obra y/o servicios sin relación de\n * dependencia (Anexo II tipo 36).\n *\n *   Inscripto:      Rate 2% sobre el excedente de $67.170 mensual.\n *   No-inscripto:   Rate 28% sobre el TOTAL pagado (sin mínimo).\n *   Exento:         Rate 0% (con cert de no-retención RG 830 art 38).\n */\nconst SERVICIOS_TABLE: ReadonlyArray<SicoreRateEntry> = [\n  {\n    category: \"servicios\",\n    status: \"inscripto\",\n    minimumMonthlyCentavos: 6_717_000, // $67.170\n    flatRate: 0.02,\n  },\n  {\n    category: \"servicios\",\n    status: \"no_inscripto\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0.28,\n  },\n  {\n    category: \"servicios\",\n    status: \"exento\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0,\n  },\n];\n\n/**\n * Honorarios — Honorarios profesionales (Anexo II tipo 28).\n *\n *   Inscripto:      Escala progresiva 0% / 5% / 9% / 12% / 15% / 19% /\n *                   22% más un importe fijo por tramo. Mínimo $67.170.\n *   No-inscripto:   Rate 28% sobre el total.\n *   Exento:         Rate 0%.\n *\n * Escala honorarios inscripto (RG 5531/2024, sobre excedente del mínimo):\n *\n *   excedente hasta       rate    fijo\n *   ─────────────────     ────    ─────\n *   $    24.000           0%      $     0\n *   $    48.000           5%      $     0\n *   $    96.000           9%      $ 1.200\n *   $   192.000          12%      $ 5.520\n *   $   384.000          15%      $ 17.040\n *   $   768.000          19%      $ 45.840\n *   $ 1.000.000+         22%      $ 118.800\n */\nconst HONORARIOS_TABLE: ReadonlyArray<SicoreRateEntry> = [\n  {\n    category: \"honorarios\",\n    status: \"inscripto\",\n    minimumMonthlyCentavos: 6_717_000, // $67.170\n    scale: [\n      { upToCentavos: 2_400_000, rate: 0, fixedCentavos: 0 },\n      { upToCentavos: 4_800_000, rate: 0.05, fixedCentavos: 0 },\n      { upToCentavos: 9_600_000, rate: 0.09, fixedCentavos: 120_000 },\n      { upToCentavos: 19_200_000, rate: 0.12, fixedCentavos: 552_000 },\n      { upToCentavos: 38_400_000, rate: 0.15, fixedCentavos: 1_704_000 },\n      { upToCentavos: 76_800_000, rate: 0.19, fixedCentavos: 4_584_000 },\n      { upToCentavos: Infinity, rate: 0.22, fixedCentavos: 11_880_000 },\n    ],\n  },\n  {\n    category: \"honorarios\",\n    status: \"no_inscripto\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0.28,\n  },\n  {\n    category: \"honorarios\",\n    status: \"exento\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0,\n  },\n];\n\n/**\n * Bienes — Compraventa de cosas muebles (Anexo II tipo 78).\n *\n *   Inscripto:      Rate 2% sobre el excedente de $224.000 mensual.\n *   No-inscripto:   Rate 10% sobre el total.\n *   Exento:         Rate 0%.\n */\nconst BIENES_TABLE: ReadonlyArray<SicoreRateEntry> = [\n  {\n    category: \"bienes\",\n    status: \"inscripto\",\n    minimumMonthlyCentavos: 22_400_000, // $224.000\n    flatRate: 0.02,\n  },\n  {\n    category: \"bienes\",\n    status: \"no_inscripto\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0.1,\n  },\n  {\n    category: \"bienes\",\n    status: \"exento\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0,\n  },\n];\n\n/**\n * Alquileres — Locaciones de inmuebles urbanos (Anexo II tipo 49).\n *\n *   Inscripto:      Rate 6% sobre el excedente de $30.000 mensual.\n *   No-inscripto:   Rate 28% sobre el total.\n *   Exento:         Rate 0%.\n */\nconst ALQUILERES_TABLE: ReadonlyArray<SicoreRateEntry> = [\n  {\n    category: \"alquileres\",\n    status: \"inscripto\",\n    minimumMonthlyCentavos: 3_000_000, // $30.000\n    flatRate: 0.06,\n  },\n  {\n    category: \"alquileres\",\n    status: \"no_inscripto\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0.28,\n  },\n  {\n    category: \"alquileres\",\n    status: \"exento\",\n    minimumMonthlyCentavos: 0,\n    flatRate: 0,\n  },\n];\n\n/**\n * Default rate-table shipping with the package (2024-Q4 snapshot).\n * Combines all four categories. Override per-call when the period\n * falls outside this snapshot.\n */\nexport const DEFAULT_RATE_TABLE: ReadonlyArray<SicoreRateEntry> = [\n  ...SERVICIOS_TABLE,\n  ...HONORARIOS_TABLE,\n  ...BIENES_TABLE,\n  ...ALQUILERES_TABLE,\n];\n\n/** Re-exported for callers that want to compose subsets. */\nexport const SICORE_TABLES = {\n  servicios: SERVICIOS_TABLE,\n  honorarios: HONORARIOS_TABLE,\n  bienes: BIENES_TABLE,\n  alquileres: ALQUILERES_TABLE,\n} as const;\n","/**\n * Error taxonomy for @ar-agents/sicore.\n *\n * Agents should distinguish:\n *   - validation errors (bad input, do NOT retry)\n *   - rate-table errors (no entry for category/status, surface to operator)\n *   - unconfigured errors (adapter not wired, surface to operator)\n *\n * `SicoreError` extends `ArAgentsError` from `@ar-agents/core` so the\n * `@ar-agents/*` family shares one error contract.\n */\n\nimport { ArAgentsError } from \"@ar-agents/core\";\n\nexport class SicoreError extends ArAgentsError {\n  constructor(message: string, code = \"sicore_error\", context: Record<string, unknown> = {}) {\n    super(message, { code, retryable: false, context });\n    this.name = \"SicoreError\";\n  }\n}\n\n/** Bad input (e.g. negative payment, invalid CUIT). Do NOT retry. */\nexport class SicoreValidationError extends SicoreError {\n  readonly field: string;\n  constructor(field: string, message: string) {\n    super(`Invalid ${field}: ${message}`, \"validation_failed\", { field });\n    this.name = \"SicoreValidationError\";\n    this.field = field;\n  }\n}\n\n/** No rate-table entry for the (category, status) pair the caller asked\n * for. Usually means the table is incomplete for the supplier's\n * situation. */\nexport class SicoreRateNotFoundError extends SicoreError {\n  readonly category: string;\n  readonly status: string;\n  constructor(category: string, status: string) {\n    super(\n      `No SICORE rate-table entry for category=\"${category}\" status=\"${status}\"`,\n      \"rate_not_found\",\n      { category, status },\n    );\n    this.name = \"SicoreRateNotFoundError\";\n    this.category = category;\n    this.status = status;\n  }\n}\n\n/** Adapter not wired (no submission target). Surface to the operator. */\nexport class SicoreUnconfiguredError extends SicoreError {\n  readonly operation: string;\n  constructor(operation: string, label = \"unconfigured\") {\n    super(\n      `SICORE adapter not configured for \"${operation}\" (${label}). Wire an adapter (or call the pure calc primitives directly).`,\n      \"unconfigured\",\n      { operation, label },\n    );\n    this.name = \"SicoreUnconfiguredError\";\n    this.operation = operation;\n  }\n}\n","/**\n * Pure calculation primitives for SICORE / Ganancias retentions.\n *\n * The math is deterministic and offline. Given an input + a rate table,\n * `calculateRetention` returns exactly what AFIP expects on the\n * comprobante de retención.\n *\n * Two important nuances of RG 830/00:\n *\n *   1. ACUMULADO. The retention applies to the MONTHLY ACCUMULATED\n *      amount paid to the same supplier — not to a single invoice.\n *      The first payment of the month often retains $0 (under the\n *      mínimo), and later payments retain the catch-up.\n *\n *   2. NETO YA RETENIDO. The retention amount for this payment equals\n *      the theoretical retention on the accumulated minus retentions\n *      already practiced this month. This way the cumulative retained\n *      always matches the cumulative theoretical, even when monthly\n *      payments straddle the threshold.\n *\n * If you skip these two rules, you'll over-retain on big single\n * payments and under-retain when payments straddle the threshold.\n */\nimport type {\n  RetentionInput,\n  RetentionResult,\n  SicoreRateEntry,\n  SupplierStatus,\n  SicoreCategory,\n  SicoreDdjjArgs,\n  SicoreDdjjResult,\n  SicoreEntry,\n} from \"./types\";\nimport { DEFAULT_RATE_TABLE } from \"./tables\";\nimport { SicoreRateNotFoundError, SicoreValidationError } from \"./errors\";\n\nconst CUIT_RE = /^\\d{11}$/;\nconst DATE_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst PERIOD_RE = /^\\d{4}-\\d{2}$/;\n\nfunction normalizeCuit(cuit: string): string {\n  const clean = cuit.replace(/-/g, \"\");\n  if (!CUIT_RE.test(clean)) {\n    throw new SicoreValidationError(\n      \"supplierCuit\",\n      \"must be 11 digits (with or without hyphens)\",\n    );\n  }\n  return clean;\n}\n\nfunction findEntry(\n  table: ReadonlyArray<SicoreRateEntry>,\n  category: SicoreCategory,\n  status: SupplierStatus,\n): SicoreRateEntry {\n  const e = table.find(\n    (entry) => entry.category === category && entry.status === status,\n  );\n  if (!e) throw new SicoreRateNotFoundError(category, status);\n  return e;\n}\n\n/**\n * Apply a progressive scale to an excedente (amount above the\n * mínimo). Each scale step adds `fixed + rate × (overlap with that\n * step)`. The result is the total theoretical retention on the\n * excedente.\n */\nfunction applyScale(\n  excedente: number,\n  scale: ReadonlyArray<{ upToCentavos: number; rate: number; fixedCentavos: number }>,\n): number {\n  // Find the step the excedente falls into.\n  let prevUpper = 0;\n  for (const step of scale) {\n    if (excedente <= step.upToCentavos) {\n      const overlap = excedente - prevUpper;\n      return step.fixedCentavos + Math.round(overlap * step.rate);\n    }\n    prevUpper = step.upToCentavos;\n  }\n  // Fell off the end of the scale (shouldn't happen if the table ends\n  // with Infinity, but guard anyway).\n  const top = scale[scale.length - 1]!;\n  const overlap = excedente - prevUpper;\n  return top.fixedCentavos + Math.round(overlap * top.rate);\n}\n\n/**\n * Calculate the SICORE retention for a single payment.\n *\n * The math:\n *   accumulated_after = accumulated_before_today + payment\n *   excedente = max(accumulated_after - mínimo, 0)\n *   theoretical_retention = scale ? applyScale(excedente) : excedente × rate\n *   retention_today = theoretical_retention - already_retained_this_month\n *\n * If `status` is \"exento\", retention is always 0.\n * If `accumulated_after < mínimo`, retention is 0 (below threshold).\n */\nexport function calculateRetention(input: RetentionInput): RetentionResult {\n  if (input.paymentCentavos < 0) {\n    throw new SicoreValidationError(\"paymentCentavos\", \"must be non-negative\");\n  }\n  if ((input.accumulatedMonthCentavos ?? 0) < 0) {\n    throw new SicoreValidationError(\n      \"accumulatedMonthCentavos\",\n      \"must be non-negative\",\n    );\n  }\n  if ((input.alreadyRetainedThisMonthCentavos ?? 0) < 0) {\n    throw new SicoreValidationError(\n      \"alreadyRetainedThisMonthCentavos\",\n      \"must be non-negative\",\n    );\n  }\n  if (!DATE_RE.test(input.paymentDate)) {\n    throw new SicoreValidationError(\"paymentDate\", \"must be YYYY-MM-DD\");\n  }\n\n  const supplierCuit = normalizeCuit(input.supplierCuit);\n  const table = input.rateTable ?? DEFAULT_RATE_TABLE;\n  const entry = findEntry(table, input.category, input.status);\n\n  const accumulatedBefore = input.accumulatedMonthCentavos ?? 0;\n  const alreadyRetained = input.alreadyRetainedThisMonthCentavos ?? 0;\n  const accumulatedAfter = accumulatedBefore + input.paymentCentavos;\n\n  // Exento: zero retention regardless of amounts.\n  if (input.status === \"exento\") {\n    return {\n      category: input.category,\n      status: input.status,\n      supplierCuit,\n      paymentDate: input.paymentDate,\n      paymentCentavos: input.paymentCentavos,\n      accumulatedAfterPaymentCentavos: accumulatedAfter,\n      minimumMonthlyCentavos: entry.minimumMonthlyCentavos,\n      effectiveRate: 0,\n      theoreticalRetentionCentavos: 0,\n      alreadyRetainedThisMonthCentavos: alreadyRetained,\n      retentionAmountCentavos: 0,\n      waiverReason: \"exento_certificate\",\n    };\n  }\n\n  // Below mínimo: zero retention.\n  if (accumulatedAfter <= entry.minimumMonthlyCentavos) {\n    return {\n      category: input.category,\n      status: input.status,\n      supplierCuit,\n      paymentDate: input.paymentDate,\n      paymentCentavos: input.paymentCentavos,\n      accumulatedAfterPaymentCentavos: accumulatedAfter,\n      minimumMonthlyCentavos: entry.minimumMonthlyCentavos,\n      effectiveRate: 0,\n      theoreticalRetentionCentavos: 0,\n      alreadyRetainedThisMonthCentavos: alreadyRetained,\n      retentionAmountCentavos: 0,\n      waiverReason: \"below_minimum\",\n    };\n  }\n\n  const excedente = accumulatedAfter - entry.minimumMonthlyCentavos;\n  let theoretical: number;\n  let effectiveRate: number;\n  if (entry.scale && entry.scale.length > 0) {\n    theoretical = applyScale(excedente, entry.scale);\n    effectiveRate = excedente > 0 ? theoretical / excedente : 0;\n  } else if (entry.flatRate !== undefined) {\n    theoretical = Math.round(excedente * entry.flatRate);\n    effectiveRate = entry.flatRate;\n  } else {\n    throw new SicoreValidationError(\n      \"rateTable\",\n      `entry for ${input.category}/${input.status} has neither flatRate nor scale`,\n    );\n  }\n\n  const retentionToday = Math.max(0, theoretical - alreadyRetained);\n\n  return {\n    category: input.category,\n    status: input.status,\n    supplierCuit,\n    paymentDate: input.paymentDate,\n    paymentCentavos: input.paymentCentavos,\n    accumulatedAfterPaymentCentavos: accumulatedAfter,\n    minimumMonthlyCentavos: entry.minimumMonthlyCentavos,\n    effectiveRate,\n    theoreticalRetentionCentavos: theoretical,\n    alreadyRetainedThisMonthCentavos: alreadyRetained,\n    retentionAmountCentavos: retentionToday,\n    ...(retentionToday === 0 && theoretical > 0\n      ? { waiverReason: \"already_satisfied\" as const }\n      : {}),\n  };\n}\n\n/**\n * Walk through a chronological stream of payments to the SAME supplier\n * and return one RetentionResult per payment, with the accumulator\n * advancing automatically. Use this when you have a flat list of\n * payments and don't want to bookkeep the running totals yourself.\n */\nexport function calculateRetentionStream(\n  payments: ReadonlyArray<{\n    category: SicoreCategory;\n    status: SupplierStatus;\n    supplierCuit: string;\n    paymentCentavos: number;\n    paymentDate: string;\n  }>,\n  rateTable?: ReadonlyArray<SicoreRateEntry>,\n): RetentionResult[] {\n  if (payments.length === 0) return [];\n  const supplier = normalizeCuit(payments[0]!.supplierCuit);\n  const month = payments[0]!.paymentDate.slice(0, 7);\n  for (const p of payments) {\n    if (normalizeCuit(p.supplierCuit) !== supplier) {\n      throw new SicoreValidationError(\n        \"payments\",\n        \"calculateRetentionStream expects a stream for ONE supplier; got multiple CUITs. Group by supplier first.\",\n      );\n    }\n    if (p.paymentDate.slice(0, 7) !== month) {\n      throw new SicoreValidationError(\n        \"payments\",\n        \"calculateRetentionStream expects a stream within ONE calendar month; got multiple periods.\",\n      );\n    }\n  }\n  let accumulated = 0;\n  let retained = 0;\n  const out: RetentionResult[] = [];\n  // Process in date order to make the result deterministic.\n  const sorted = [...payments].sort((a, b) =>\n    a.paymentDate.localeCompare(b.paymentDate),\n  );\n  for (const p of sorted) {\n    const r = calculateRetention({\n      category: p.category,\n      status: p.status,\n      supplierCuit: p.supplierCuit,\n      paymentCentavos: p.paymentCentavos,\n      paymentDate: p.paymentDate,\n      accumulatedMonthCentavos: accumulated,\n      alreadyRetainedThisMonthCentavos: retained,\n      ...(rateTable ? { rateTable } : {}),\n    });\n    accumulated += p.paymentCentavos;\n    retained += r.retentionAmountCentavos;\n    out.push(r);\n  }\n  return out;\n}\n\n// ── Monthly DDJJ aggregation ────────────────────────────────────\n\nexport function buildSicoreDdjj(args: SicoreDdjjArgs): SicoreDdjjResult {\n  if (!PERIOD_RE.test(args.period)) {\n    throw new SicoreValidationError(\"period\", \"must be YYYY-MM\");\n  }\n  normalizeCuit(args.agentCuit);\n  const byCat = new Map<\n    SicoreCategory,\n    { paymentCentavos: number; retentionCentavos: number; entryCount: number }\n  >();\n  const bySupplier = new Map<\n    string,\n    { paymentCentavos: number; retentionCentavos: number; entryCount: number }\n  >();\n  let totalPayment = 0;\n  let totalRet = 0;\n  for (const e of args.entries) {\n    totalPayment += e.retention.paymentCentavos;\n    totalRet += e.retention.retentionAmountCentavos;\n    const cat = e.retention.category;\n    const catRow = byCat.get(cat) ?? {\n      paymentCentavos: 0,\n      retentionCentavos: 0,\n      entryCount: 0,\n    };\n    catRow.paymentCentavos += e.retention.paymentCentavos;\n    catRow.retentionCentavos += e.retention.retentionAmountCentavos;\n    catRow.entryCount += 1;\n    byCat.set(cat, catRow);\n    const sup = e.retention.supplierCuit;\n    const supRow = bySupplier.get(sup) ?? {\n      paymentCentavos: 0,\n      retentionCentavos: 0,\n      entryCount: 0,\n    };\n    supRow.paymentCentavos += e.retention.paymentCentavos;\n    supRow.retentionCentavos += e.retention.retentionAmountCentavos;\n    supRow.entryCount += 1;\n    bySupplier.set(sup, supRow);\n  }\n  return {\n    period: args.period,\n    agentCuit: args.agentCuit.replace(/-/g, \"\"),\n    totals: {\n      paymentCentavos: totalPayment,\n      retentionCentavos: totalRet,\n      entryCount: args.entries.length,\n    },\n    byCategory: Array.from(byCat.entries()).map(([category, v]) => ({\n      category,\n      ...v,\n    })),\n    bySupplier: Array.from(bySupplier.entries())\n      .map(([supplierCuit, v]) => ({ supplierCuit, ...v }))\n      .sort((a, b) => b.retentionCentavos - a.retentionCentavos),\n    entries: args.entries,\n  };\n}\n\n/** Convenience: pure helper to skip the typed input boilerplate. */\nexport function quickRetention(\n  category: SicoreCategory,\n  status: SupplierStatus,\n  paymentCentavos: number,\n  options: {\n    supplierCuit?: string;\n    paymentDate?: string;\n    accumulatedMonthCentavos?: number;\n    alreadyRetainedThisMonthCentavos?: number;\n  } = {},\n): number {\n  const r = calculateRetention({\n    category,\n    status,\n    supplierCuit: options.supplierCuit ?? \"20000000000\",\n    paymentCentavos,\n    paymentDate: options.paymentDate ?? \"2026-01-15\",\n    ...(options.accumulatedMonthCentavos !== undefined\n      ? { accumulatedMonthCentavos: options.accumulatedMonthCentavos }\n      : {}),\n    ...(options.alreadyRetainedThisMonthCentavos !== undefined\n      ? { alreadyRetainedThisMonthCentavos: options.alreadyRetainedThisMonthCentavos }\n      : {}),\n  });\n  return r.retentionAmountCentavos;\n}\n\n// Export a helper to assemble a SicoreEntry from a calc result.\nexport function asEntry(\n  comprobanteRef: string,\n  retention: RetentionResult,\n): SicoreEntry {\n  return { comprobanteRef, retention };\n}\n","/**\n * SICORE adapter contract.\n *\n * The math layer (calc.ts) is pure and doesn't need any adapter. The\n * adapter exists for downstream operations that touch AFIP/ARCA's\n * SICORE upload surface — namely, submitting a monthly DDJJ.\n *\n * SICORE submission is XML-based and requires an AFIP-signed token\n * (WSAA) plus a series of jurisdiction-specific quirks. This package\n * does NOT bundle a default real adapter because:\n *   (a) credentials live in the host, never the lib\n *   (b) the upload surface is significantly more complex than the math\n *   (c) most users will want to file via their accountant's tool, not\n *       directly from agent code\n *\n * v0.1 ships only the contract + an unconfigured default.\n */\nimport { SicoreUnconfiguredError } from \"./errors\";\nimport type { SicoreDdjjResult } from \"./types\";\n\nexport interface SicoreAdapter {\n  /**\n   * Submit a SICORE DDJJ to AFIP/ARCA. Returns an opaque receipt id\n   * (typically the F.997 / F.744 acuse de recibo number) and the raw\n   * AFIP response so the host can persist the audit trail.\n   */\n  submitDdjj(ddjj: SicoreDdjjResult): Promise<{\n    receiptId: string;\n    submittedAt: string;\n    raw?: unknown;\n  }>;\n}\n\n/** Default. Throws on every submission attempt. Safe for unit tests. */\nexport class UnconfiguredSicoreAdapter implements SicoreAdapter {\n  async submitDdjj(): Promise<never> {\n    throw new SicoreUnconfiguredError(\n      \"submitDdjj\",\n      \"no SICORE submission adapter wired\",\n    );\n  }\n}\n","/**\n * Drop-in tool collection for Vercel AI SDK 6+. Pair with an Agent.\n *\n * The tool layer leans heavily on the pure calc primitives in calc.ts\n * (calculateRetention, calculateRetentionStream, buildSicoreDdjj). The\n * adapter is only required for `sicore_submit_ddjj` (currently throws\n * by default; wire a custom adapter if your host has AFIP creds).\n */\nimport { tool, type ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport type { SicoreAdapter } from \"./adapter\";\nimport { UnconfiguredSicoreAdapter } from \"./adapter\";\nimport {\n  calculateRetention,\n  calculateRetentionStream,\n  buildSicoreDdjj,\n  asEntry,\n} from \"./calc\";\nimport { DEFAULT_RATE_TABLE } from \"./tables\";\nimport type {\n  SicoreEntry,\n  SicoreRateEntry,\n  RetentionInput,\n} from \"./types\";\n\nconst categoryEnum = z.enum([\n  \"servicios\",\n  \"honorarios\",\n  \"bienes\",\n  \"alquileres\",\n]);\nconst statusEnum = z.enum([\"inscripto\", \"no_inscripto\", \"exento\"]);\n\nconst cuitSchema = z\n  .string()\n  .regex(/^\\d{2}-?\\d{8}-?\\d{1}$|^\\d{11}$/)\n  .describe(\"CUIT with or without hyphens (11 digits).\");\n\nconst dateSchema = z\n  .string()\n  .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n  .describe(\"Payment date in YYYY-MM-DD.\");\n\nconst retentionInputSchema = z.object({\n  category: categoryEnum,\n  status: statusEnum,\n  supplierCuit: cuitSchema,\n  paymentCentavos: z.number().int().nonnegative(),\n  paymentDate: dateSchema,\n  accumulatedMonthCentavos: z.number().int().nonnegative().optional(),\n  alreadyRetainedThisMonthCentavos: z.number().int().nonnegative().optional(),\n});\n\nexport interface SicoreToolsOptions {\n  /** Adapter for submission. Defaults to UnconfiguredSicoreAdapter. */\n  adapter?: SicoreAdapter;\n  /** Override the in-package rate-table snapshot. */\n  rateTable?: ReadonlyArray<SicoreRateEntry>;\n  /** Optional subset of tools to expose. */\n  include?: ReadonlyArray<SicoreToolName>;\n}\n\nexport const ALL_TOOL_NAMES = [\n  \"sicore_calculate_retention\",\n  \"sicore_calculate_retention_stream\",\n  \"sicore_build_ddjj\",\n  \"sicore_submit_ddjj\",\n] as const;\n\nexport type SicoreToolName = (typeof ALL_TOOL_NAMES)[number];\n\nexport function sicoreTools(opts: SicoreToolsOptions = {}): ToolSet {\n  const adapter = opts.adapter ?? new UnconfiguredSicoreAdapter();\n  const rateTable = opts.rateTable ?? DEFAULT_RATE_TABLE;\n  const wanted = new Set<SicoreToolName>(opts.include ?? ALL_TOOL_NAMES);\n\n  const allTools = {\n    sicore_calculate_retention: tool({\n      description:\n        \"Calculate the SICORE income-tax retention on a supplier payment (calcular retención de Ganancias SICORE). Implements the RG 830/00 rule: retention is on the MONTHLY ACCUMULATED amount (passed via accumulatedMonthCentavos), minus what's already been retained this month (alreadyRetainedThisMonthCentavos). Returns 0 when the supplier is exento or the accumulated is below the minimum. Inputs are centavos integers; rates are fractions.\",\n      inputSchema: retentionInputSchema,\n      execute: async (input) => {\n        const args: RetentionInput = {\n          category: input.category,\n          status: input.status,\n          supplierCuit: input.supplierCuit,\n          paymentCentavos: input.paymentCentavos,\n          paymentDate: input.paymentDate,\n          ...(input.accumulatedMonthCentavos !== undefined\n            ? { accumulatedMonthCentavos: input.accumulatedMonthCentavos }\n            : {}),\n          ...(input.alreadyRetainedThisMonthCentavos !== undefined\n            ? {\n                alreadyRetainedThisMonthCentavos:\n                  input.alreadyRetainedThisMonthCentavos,\n              }\n            : {}),\n          rateTable,\n        };\n        return calculateRetention(args);\n      },\n    }),\n\n    sicore_calculate_retention_stream: tool({\n      description:\n        \"Walk a chronological stream of payments to ONE supplier in ONE month and return the retention per payment, with the accumulator advancing automatically. Use this when reconciling a supplier's invoices for the month, the tool does the bookkeeping so the agent does not have to track running totals.\",\n      inputSchema: z.object({\n        payments: z\n          .array(\n            z.object({\n              category: categoryEnum,\n              status: statusEnum,\n              supplierCuit: cuitSchema,\n              paymentCentavos: z.number().int().nonnegative(),\n              paymentDate: dateSchema,\n            }),\n          )\n          .min(1)\n          .describe(\"All payments to one supplier in one month.\"),\n      }),\n      execute: async ({ payments }) =>\n        calculateRetentionStream(payments, rateTable),\n    }),\n\n    sicore_build_ddjj: tool({\n      description:\n        \"Assemble the monthly SICORE return (armar la DDJJ SICORE) from a list of retention results. Returns totals + per-category + per-supplier breakdowns ready for filing. Pure aggregation; does NOT submit.\",\n      inputSchema: z.object({\n        period: z.string().regex(/^\\d{4}-\\d{2}$/),\n        agentCuit: cuitSchema,\n        entries: z\n          .array(\n            z.object({\n              comprobanteRef: z.string().min(1),\n              retention: z.unknown(),\n            }),\n          )\n          .min(1),\n      }),\n      execute: async (input) =>\n        buildSicoreDdjj({\n          period: input.period,\n          agentCuit: input.agentCuit,\n          entries: input.entries as SicoreEntry[],\n        }),\n    }),\n\n    sicore_submit_ddjj: tool({\n      description:\n        \"Submit an assembled SICORE return to AFIP/ARCA (presentar la DDJJ SICORE). Throws SicoreUnconfiguredError unless the host wired a real submission adapter. Confirmation gate REQUIRED in the host UI before invoking, this files a tax return.\",\n      inputSchema: z.object({\n        ddjj: z.unknown().describe(\"Result of sicore_build_ddjj.\"),\n      }),\n      execute: async ({ ddjj }) =>\n        adapter.submitDdjj(ddjj as Parameters<SicoreAdapter[\"submitDdjj\"]>[0]),\n    }),\n  } as const;\n\n  const out: Record<string, (typeof allTools)[SicoreToolName]> = {};\n  for (const name of ALL_TOOL_NAMES) {\n    if (wanted.has(name)) out[name] = allTools[name];\n  }\n  return out as Pick<typeof allTools, SicoreToolName>;\n}\n\nexport { asEntry };\n"]}