{"version":3,"file":"math.cjs","names":[],"sources":["../../../src/batteries/tools/math/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.\n *\n * @module @nhtio/adk/batteries/tools/math\n *\n * @remarks\n * Pre-constructed bundled tools for the `math` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { create, all } from 'mathjs'\nimport { Tool } from '@nhtio/adk/common'\nimport { validator } from '@nhtio/validation'\nimport { default as evaluatex } from 'evaluatex'\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\n\nconst math = create(all)\n\nconst BLOCKED_FUNCTIONS = [\n  'import',\n  'createUnit',\n  'simplify',\n  'derivative',\n  'compile',\n  'chain',\n  'reviver',\n  'replacer',\n]\n\nfor (const fn of BLOCKED_FUNCTIONS) {\n  if (fn in math) {\n    ;(math as any)[fn] = undefined\n  }\n}\n\nconst MAX_EXPRESSION_LENGTH = 1000\n\nfunction validateExpression(expr: string): string | undefined {\n  if (expr.length > MAX_EXPRESSION_LENGTH) {\n    return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`\n  }\n  return undefined\n}\n\n/**\n * EvaluateX scope providing constants and function aliases that evaluatex does not ship\n * out-of-the-box, matching the capabilities that were previously provided by the mathjs\n * translation layer.\n */\nconst EVALUATEX_SCOPE: Record<string, unknown> = {\n  // Mathematical constants\n  pi: Math.PI,\n  e: Math.E,\n  infinity: Infinity,\n  // Greek letters as named constants (matching LaTeX macro names)\n  alpha: undefined,\n  beta: undefined,\n  gamma: undefined,\n  delta: undefined,\n  epsilon: undefined,\n  theta: undefined,\n  lambda: undefined,\n  mu: undefined,\n  sigma: undefined,\n  tau: undefined,\n  phi: undefined,\n  omega: undefined,\n  // Function aliases — evaluatex uses log for natural log; provide ln as alias,\n  // plus common log bases and nthRoot for \\sqrt[n]{...}.\n  ln: Math.log,\n  log10: (x: number) => Math.log(x) / Math.LN10,\n  log2: (x: number) => Math.log(x) / Math.LN2,\n  nthRoot: (x: number, n: number) => Math.pow(x, 1 / n),\n  // Determinant (identity for scalars — det([a,b;c,d]) is not supported in the scalar path)\n  det: (x: number) => x,\n}\n\n/**\n * Translate a LaTeX/KaTeX expression to evaluatex-compatible syntax and evaluate it.\n *\n * The translation is a lightweight pass over the LaTeX source that handles common constructs\n * (frac, sqrt, trig, Greek macros, delimiters, etc.) and feeds the result to evaluatex with\n * a pre-built scope providing constants and function aliases. This replaces the previous\n * hand-rolled regex → mathjs pipeline.\n */\nfunction evaluateLatex(latex: string): number {\n  let expr = latex.trim()\n\n  // Strip display/inline math delimiters: $$...$$ or $...$\n  expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n  // Strip \\[ ... \\] or \\( ... \\) delimiters\n  expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n  // ---- LaTeX command translation ----\n\n  // \\frac{a}{b} → (a)/(b) — iterates to handle nested fractions\n  for (let i = 0; i < 20; i++) {\n    const before = expr\n    expr = expr.replace(/\\\\frac\\s*\\{([^}]*)\\}\\s*\\{([^}]*)\\}/g, '($1)/($2)')\n    if (expr === before) break\n  }\n\n  // \\sqrt[n]{x} → nthRoot(x, n)\n  expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^}]*)\\}/g, 'nthRoot($2, $1)')\n  // \\sqrt{x} → sqrt(x)\n  expr = expr.replace(/\\\\sqrt\\s*\\{([^}]*)\\}/g, 'sqrt($1)')\n\n  // Inverse trig: \\arcsin → asin (evaluatex uses asin/acos/atan natively)\n  expr = expr.replace(/\\\\arcsin/g, 'asin')\n  expr = expr.replace(/\\\\arccos/g, 'acos')\n  expr = expr.replace(/\\\\arctan/g, 'atan')\n\n  // Strip backslash from known function macros: \\sin, \\cos, \\tan, \\cot, \\sec, \\csc,\n  // \\sinh, \\cosh, \\tanh, \\ln, \\log, \\exp, \\abs, etc.\n  expr = expr.replace(/\\\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, '$1')\n\n  // Subscript-based log: \\log_2(x) → log2(x), \\log_10(x) → log10(x), \\log_e(x) → ln(x), and a\n  // generic base \\log_b(arg) → (ln(arg)/ln(b)) via change of base. The argument is captured here\n  // (single level of nested parens) so the change-of-base form is well-formed — previously the\n  // argument was not captured and the output was the malformed `ln(/ln(b)`.\n  expr = expr.replace(\n    /log_\\{?(\\w+)\\}?\\(((?:[^()]|\\([^()]*\\))*)\\)/g,\n    (_, base: string, arg: string) => {\n      const baseLower = base.toLowerCase()\n      if (baseLower === '10') return `log10(${arg})`\n      if (baseLower === '2') return `log2(${arg})`\n      if (baseLower === 'e') return `ln(${arg})`\n      return `(ln(${arg})/ln(${base}))`\n    }\n  )\n  // Strip any remaining subscripts (e.g. x_1, a_n)\n  expr = expr.replace(/_\\{[^}]*\\}/g, '')\n  expr = expr.replace(/_\\w/g, '')\n\n  // Powers: ^{...} → ^(...)\n  expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n\n  // Greek letter macros\n  expr = expr.replace(/\\\\pi/g, 'pi')\n  expr = expr.replace(\n    /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n    '$1'\n  )\n\n  // Spacing and operators\n  expr = expr.replace(/\\\\cdot/g, '*')\n  expr = expr.replace(/\\\\times/g, '*')\n  expr = expr.replace(/\\\\div/g, '/')\n  expr = expr.replace(/\\\\infty/g, 'infinity')\n  expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n  expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n  expr = expr.replace(/\\\\sum/g, 'sum')\n  expr = expr.replace(/\\\\prod/g, 'prod')\n  expr = expr.replace(/\\\\,/g, ' ')\n  expr = expr.replace(/\\\\;/g, ' ')\n  expr = expr.replace(/\\\\quad/g, ' ')\n  expr = expr.replace(/\\\\qquad/g, ' ')\n  // Strip \\text{...} blocks entirely\n  expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n\n  // Scientific notation: evaluatex doesn't understand `2e3` natively (it reads `e3` as a symbol),\n  // so rewrite a numeric literal's exponent into an explicit power: `2e3` → `(2*10^(3))`,\n  // `1.5e-8` → `(1.5*10^(-8))`. Done BEFORE implicit-multiplication insertion.\n  expr = expr.replace(/(\\d(?:\\.\\d+)?)[eE]([+-]?\\d+)/g, '($1*10^($2))')\n\n  // Implicit multiplication: 2x, 3(x+1), etc.\n  expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n  expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n\n  // Collapse whitespace\n  expr = expr.replace(/\\s+/g, ' ').trim()\n\n  const fn = evaluatex(expr, EVALUATEX_SCOPE)\n  const result = fn()\n  if (typeof result !== 'number' || !Number.isFinite(result)) {\n    throw new Error('Result is not finite')\n  }\n  return result\n}\n\n/**\n * Lightweight LaTeX-to-string translator for internal use by the numeric calculus path.\n *\n * This is the same translation pass as {@link evaluateLatex}, but returns the translated string\n * (compatible with mathjs syntax) rather than evaluating it. Used by the calculus handlers to\n * convert integrands, function bodies, and bound expressions before passing them to\n * `math.evaluate` for specific-point evaluation.\n */\nfunction translateLatex(latex: string): string {\n  let expr = latex.trim()\n  expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n  expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n  for (let i = 0; i < 20; i++) {\n    const before = expr\n    expr = expr.replace(/\\\\frac\\s*\\{([^}]*)\\}\\s*\\{([^}]*)\\}/g, '($1)/($2)')\n    if (expr === before) break\n  }\n\n  expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^}]*)\\}/g, 'nthRoot($2, $1)')\n  expr = expr.replace(/\\\\sqrt\\s*\\{([^}]*)\\}/g, 'sqrt($1)')\n\n  expr = expr.replace(/\\\\arcsin/g, 'asin')\n  expr = expr.replace(/\\\\arccos/g, 'acos')\n  expr = expr.replace(/\\\\arctan/g, 'atan')\n\n  expr = expr.replace(/\\\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, '$1')\n\n  expr = expr.replace(/log_\\{?(\\w+)\\}?\\s*\\(([^)]+)\\)/g, 'log($2, $1)')\n  expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n  expr = expr.replace(/_\\{[^{}]*\\}/g, '')\n  expr = expr.replace(/_\\w/g, '')\n\n  expr = expr.replace(/\\\\pi/g, 'pi')\n  expr = expr.replace(\n    /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n    '$1'\n  )\n\n  expr = expr.replace(/\\\\cdot/g, '*')\n  expr = expr.replace(/\\\\times/g, '*')\n  expr = expr.replace(/\\\\div/g, '/')\n  expr = expr.replace(/\\\\infty/g, 'Infinity')\n  expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n  expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n  expr = expr.replace(/\\\\sum/g, 'sum')\n  expr = expr.replace(/\\\\prod/g, 'prod')\n  expr = expr.replace(/\\\\,/g, ' ')\n  expr = expr.replace(/\\\\;/g, ' ')\n  expr = expr.replace(/\\\\quad/g, ' ')\n  expr = expr.replace(/\\\\qquad/g, ' ')\n  expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n  expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n  expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n  expr = expr.replace(/\\s+/g, ' ').trim()\n\n  return expr\n}\n\n// ─── Numeric calculus ─────────────────────────────────────────────────────────\n//\n// `evaluate_katex` is a numeric evaluator. mathjs has no symbolic integration, and its symbolic\n// `derivative` is intentionally blocklisted above, so calculus is computed NUMERICALLY: definite\n// integrals via composite Simpson quadrature, derivatives via central finite differences, and limits\n// via a two-sided approach. These are approximations (correct to ~1e-9 for the smooth expressions a\n// model emits), surfaced under a `Result (numeric):` label so the distinction is explicit.\n//\n// Detection runs on the RAW LaTeX, before `translateLatex` flattens it — its subscript stripping\n// would otherwise destroy integral bounds (`\\int_{0}^{1}` → `\\int^(1)`) and limit targets. The\n// extracted sub-expressions (integrand, bounds, body, point) are then translated by the existing\n// `translateLatex` and evaluated per-point with a scope, which works under the security blocklist.\n\n/** A tagged error whose message is surfaced to the model verbatim (caught by {@link tryCalculus}). */\nclass CalculusError extends Error {}\n\n/** Evaluate a mathjs expression at a single point, guarding against non-finite results. */\nfunction evalAt(expr: string, varName: string, x: number): number {\n  const y = math.evaluate!(expr, { [varName]: x })\n  if (typeof y !== 'number' || !Number.isFinite(y)) {\n    throw new CalculusError('NON_FINITE')\n  }\n  return y\n}\n\n/** Composite Simpson's rule over a finite interval. Throws {@link CalculusError} on a singularity. */\nfunction simpson(fn: (x: number) => number, a: number, b: number, n = 1000): number {\n  if (n % 2 === 1) n++\n  const h = (b - a) / n\n  let sum = fn(a) + fn(b)\n  for (let i = 1; i < n; i++) {\n    sum += (i % 2 === 1 ? 4 : 2) * fn(a + i * h)\n  }\n  const result = (h / 3) * sum\n  if (!Number.isFinite(result)) throw new CalculusError('NON_FINITE')\n  return result\n}\n\n/** Round numeric output to 12 significant digits, collapsing floating-point noise. */\nfunction formatNumeric(n: number): string {\n  // Snap values that are zero-to-within-tolerance to exactly 0 (e.g. lim_{x->inf} 1/x ≈ 1e-8).\n  if (Math.abs(n) < 1e-9) return '0'\n  return math.format!(n, { precision: 12 })\n}\n\n/**\n * Reads a single `_`/`^` script starting at `i`, supporting braced (`_{0}`, `^{\\pi}`), command\n * (`^\\pi`), and bare-token (`_0`, `^1`) forms. Returns the mark, its raw-LaTeX value, and the next\n * index, or `null` when there is no script at `i`.\n */\nfunction readScript(s: string, i: number): { mark: '_' | '^'; val: string; next: number } | null {\n  while (s[i] === ' ') i++\n  const mark = s[i]\n  if (mark !== '_' && mark !== '^') return null\n  i++\n  while (s[i] === ' ') i++\n  if (s[i] === '{') {\n    let depth = 0\n    const start = ++i\n    for (; i < s.length; i++) {\n      if (s[i] === '{') depth++\n      else if (s[i] === '}') {\n        if (depth === 0) break\n        depth--\n      }\n    }\n    return { mark, val: s.slice(start, i), next: i + 1 }\n  }\n  if (s[i] === '\\\\') {\n    const m = /^\\\\[a-zA-Z]+/.exec(s.slice(i))\n    if (!m) return null\n    return { mark, val: m[0], next: i + m[0].length }\n  }\n  const m = /^[A-Za-z0-9.]+/.exec(s.slice(i))\n  if (!m) return null\n  return { mark, val: m[0], next: i + m[0].length }\n}\n\n/** Translate a raw-LaTeX bound/target fragment and evaluate it to a finite number. */\nfunction evalBound(latex: string): number {\n  const trimmed = latex.trim()\n  if (/\\\\infty/.test(trimmed)) throw new CalculusError('INFINITE_BOUND')\n  const mathjsExpr = translateLatex(trimmed)\n  const value = math.evaluate!(mathjsExpr)\n  if (typeof value !== 'number' || !Number.isFinite(value)) {\n    throw new CalculusError('BAD_BOUND')\n  }\n  return value\n}\n\n/** Evaluate a definite integral `\\int_{a}^{b} f \\,dx` by Simpson quadrature. */\nfunction evalIntegral(s: string): string {\n  // Strip the operator (\\int, optionally with \\limits).\n  const m = /\\\\int(?:\\\\limits)?/.exec(s)\n  if (!m) throw new CalculusError('NOT_INTEGRAL')\n  let i = m.index + m[0].length\n\n  // Read up to two scripts (bounds), in either order.\n  const scripts: Record<'_' | '^', string | undefined> = { '_': undefined, '^': undefined }\n  for (let k = 0; k < 2; k++) {\n    const sc = readScript(s, i)\n    if (!sc) break\n    scripts[sc.mark] = sc.val\n    i = sc.next\n  }\n  if (scripts._ === undefined || scripts['^'] === undefined) {\n    throw new CalculusError('INDEFINITE')\n  }\n\n  // The remainder is `integrand … d<var>`. Pull the trailing differential off the end.\n  const rest = s.slice(i)\n  const diff = /\\\\?,?\\s*\\bd\\s*([a-zA-Z])\\s*$/.exec(rest)\n  if (!diff) throw new CalculusError('NO_DIFFERENTIAL')\n  const variable = diff[1]\n  const integrandLatex = rest.slice(0, diff.index)\n  if (integrandLatex.trim().length === 0) throw new CalculusError('NO_INTEGRAND')\n\n  const a = evalBound(scripts._)\n  const b = evalBound(scripts['^'])\n  const integrand = translateLatex(integrandLatex)\n  const fn = (x: number) => evalAt(integrand, variable, x)\n\n  let result: number\n  if (a === b) result = 0\n  else if (a < b) result = simpson(fn, a, b)\n  else result = -simpson(fn, b, a)\n\n  return `Converted: ∫(${integrand}) d${variable} from ${formatNumeric(a)} to ${formatNumeric(b)}\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Evaluate a derivative `\\frac{d}{dx} f \\big|_{x=a}` at a point via central finite difference. */\nfunction evalDerivative(s: string): string {\n  // Operator + variable: \\frac{d}{dx} … or bare d/dx ….\n  let variable: string | undefined\n  let body = s\n  const fracOp = /\\\\frac\\s*\\{\\s*d\\s*\\}\\s*\\{\\s*d\\s*([a-zA-Z])\\s*\\}/.exec(s)\n  if (fracOp) {\n    variable = fracOp[1]\n    body = s.slice(fracOp.index + fracOp[0].length)\n  } else {\n    const bareOp = /(?:^|[^a-zA-Z])d\\s*\\/\\s*d([a-zA-Z])/.exec(s)\n    if (bareOp) {\n      variable = bareOp[1]\n      body = s.slice(bareOp.index + bareOp[0].length)\n    }\n  }\n  if (!variable) throw new CalculusError('NOT_DERIVATIVE')\n\n  // Remove pure \\left. / \\right. delimiters.\n  body = body.replace(/\\\\left\\.?/g, '').replace(/\\\\right\\.?/g, '')\n\n  // Evaluation bar + point at the end: …|_{x=3} (optionally \\Big| etc.).\n  const bar = /\\\\?(?:Big|big|bigg|Bigg)?\\s*\\|\\s*_\\s*\\{?\\s*([a-zA-Z])\\s*=\\s*([^}]+?)\\s*\\}?\\s*$/.exec(\n    body\n  )\n  if (!bar) throw new CalculusError('NO_POINT')\n  const point = evalBound(bar[2])\n  let fnLatex = body.slice(0, bar.index).trim()\n\n  // Strip one layer of wrapping parentheses/brackets around the function body.\n  fnLatex = fnLatex\n    .replace(/^\\\\?\\(([\\s\\S]*)\\\\?\\)$/, '$1')\n    .replace(/^\\[([\\s\\S]*)\\]$/, '$1')\n    .trim()\n  if (fnLatex.length === 0) throw new CalculusError('NO_FUNCTION')\n\n  const expr = translateLatex(fnLatex)\n  const h = 1e-6\n  const fn = (x: number) => evalAt(expr, variable, x)\n  const result = (fn(point + h) - fn(point - h)) / (2 * h)\n  if (!Number.isFinite(result)) throw new CalculusError('NON_FINITE')\n\n  return `Converted: d/d${variable}(${expr}) at ${variable}=${formatNumeric(point)}\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Evaluate a limit `\\lim_{x \\to a} f(x)` by a two-sided numeric approach. */\nfunction evalLimit(s: string): string {\n  const head = /\\\\lim\\s*_\\s*\\{\\s*([a-zA-Z])\\s*\\\\to\\s*([\\s\\S]+?)\\s*\\}/.exec(s)\n  if (!head) throw new CalculusError('NOT_LIMIT')\n  const variable = head[1]\n  let targetLatex = head[2].trim()\n  const bodyLatex = s.slice(head.index + head[0].length).trim()\n  if (bodyLatex.length === 0) throw new CalculusError('NO_FUNCTION')\n\n  // One-sided markers (0^+, 0^-, 0^{+}) — record the side, strip the marker.\n  let side: 'both' | 'plus' | 'minus' = 'both'\n  const oneSided = /\\^\\s*\\{?\\s*([+-])\\s*\\}?\\s*$/.exec(targetLatex)\n  if (oneSided) {\n    side = oneSided[1] === '+' ? 'plus' : 'minus'\n    targetLatex = targetLatex.slice(0, oneSided.index).trim()\n  }\n\n  const expr = translateLatex(bodyLatex)\n  const fn = (x: number) => evalAt(expr, variable, x)\n  const eps = 1e-6\n\n  // Infinite targets via large-magnitude substitution.\n  let result: number\n  let targetLabel: string\n  if (/^-\\s*\\\\infty$/.test(targetLatex)) {\n    result = fn(-1e8)\n    targetLabel = '-∞'\n  } else if (/^\\\\infty$/.test(targetLatex)) {\n    result = fn(1e8)\n    targetLabel = '∞'\n  } else {\n    const target = evalBound(targetLatex)\n    targetLabel = formatNumeric(target)\n    if (side === 'plus') {\n      result = fn(target + eps)\n    } else if (side === 'minus') {\n      result = fn(target - eps)\n    } else {\n      const lo = fn(target - eps)\n      const hi = fn(target + eps)\n      const avg = (lo + hi) / 2\n      if (Math.abs(hi - lo) > 1e-3 * Math.max(1, Math.abs(avg))) {\n        throw new CalculusError('LIMIT_MISMATCH')\n      }\n      result = avg\n    }\n  }\n  if (!Number.isFinite(result)) throw new CalculusError('LIMIT_UNBOUNDED')\n\n  // Infinite-target substitution (±1e8) and the eps offset leave more residue than Simpson or the\n  // derivative difference, so snap a limit result to a nearby round value before formatting:\n  // 0.99999998 → 1, 1e-8 → 0. The tolerance is loose enough to absorb the substitution error yet\n  // far tighter than the divergence check that already rejected genuinely non-convergent limits.\n  const nearest = Math.round(result)\n  if (Math.abs(result - nearest) < 1e-6) result = nearest\n\n  return `Converted: lim ${variable}→${targetLabel} of (${expr})\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Human-readable, model-actionable message for each {@link CalculusError} tag. */\nfunction calculusErrorMessage(tag: string): string {\n  switch (tag) {\n    case 'INDEFINITE':\n      return 'Cannot evaluate an indefinite integral numerically. Provide bounds, e.g. \\\\int_{0}^{1} x dx.'\n    case 'NO_DIFFERENTIAL':\n      return \"Could not find the integration variable. Expected a trailing differential like 'dx'.\"\n    case 'NO_INTEGRAND':\n      return 'The integral has no integrand to evaluate.'\n    case 'INFINITE_BOUND':\n      return 'Infinite integration bounds are not supported. Provide finite numeric bounds, e.g. \\\\int_{0}^{1} f dx.'\n    case 'BAD_BOUND':\n      return 'Could not evaluate the integration bounds to numbers.'\n    case 'NO_POINT':\n      return 'Cannot evaluate a derivative numerically without a point. Specify where, e.g. \\\\frac{d}{dx}(x^2)\\\\Big|_{x=3}.'\n    case 'NO_FUNCTION':\n      return 'Could not find the function to evaluate.'\n    case 'LIMIT_MISMATCH':\n      return 'The limit may not exist (left and right values disagree).'\n    case 'LIMIT_UNBOUNDED':\n      return 'The limit appears to diverge (function is unbounded near the target).'\n    case 'NON_FINITE':\n      return 'The expression is not finite over the requested range (possible singularity); cannot evaluate numerically.'\n    default:\n      return 'Could not evaluate the calculus expression.'\n  }\n}\n\n/**\n * Detects a calculus construct in raw LaTeX and routes it to the matching numeric handler. Returns\n * the result/error string, or `null` when the input is not a calculus expression (so the caller\n * falls through to the scalar evaluation path unchanged).\n */\nfunction tryCalculus(latex: string): string | null {\n  let s = latex.trim()\n  s = s.replace(/^\\$\\$?|\\$\\$?$/g, '')\n  s = s.replace(/^\\\\[[(]|\\\\[\\])]$/g, '').trim()\n\n  let handler: ((expr: string) => string) | undefined\n  if (/\\\\int/.test(s)) handler = evalIntegral\n  else if (/\\\\lim/.test(s)) handler = evalLimit\n  else if (\n    /\\\\frac\\s*\\{\\s*d\\s*\\}\\s*\\{\\s*d\\s*[a-zA-Z]\\s*\\}/.test(s) ||\n    /(?:^|[^a-zA-Z])d\\s*\\/\\s*d[a-zA-Z]/.test(s)\n  )\n    handler = evalDerivative\n  if (!handler) return null\n\n  try {\n    return handler(s)\n  } catch (err) {\n    if (isInstanceOf(err, 'CalculusError', CalculusError)) {\n      return `Error: ${calculusErrorMessage(err.message)}`\n    }\n    return `Error: ${isError(err) ? err.message : String(err)}`\n  }\n}\n\n/**\n * Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX\n * representation of the parsed expression.\n *\n * @remarks\n * Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit\n * operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,\n * `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are\n * disabled to prevent interpreter-surface exposure.\n *\n * Expressions over 1000 characters are rejected with an error string (not thrown). Parse and\n * evaluation errors are also returned as error strings — the tool surfaces math errors as\n * content rather than exceptions, so the model can react to them in-line.\n */\nexport const calculateTool = new Tool({\n  name: 'calculate',\n  description:\n    'Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.',\n  inputSchema: validator.object({\n    expression: validator.string().required().description('Math expression, e.g. \"sin(pi/4) + 5!\"'),\n  }),\n  handler: async (args) => {\n    const { expression } = args as { expression: string }\n\n    const lengthError = validateExpression(expression)\n    if (lengthError) return lengthError\n\n    try {\n      const result = math.evaluate!(expression)\n      // A scalar that overflowed float64 (e.g. `2^5000`, `factorial(200)`) comes back as\n      // `Infinity`/`NaN`. Surface that as a clear error rather than printing `Result: Infinity`,\n      // which reads like a genuine answer.\n      if (typeof result === 'number' && !Number.isFinite(result)) {\n        return `Error: result is not finite (${result}) — the value overflows JavaScript's numeric range.`\n      }\n      const node = math.parse!(expression)\n      const katex = node.toTex()\n      return `Result: ${result}\\nKaTeX: $${katex} = ${result}$`\n    } catch (err) {\n      return `Error: ${isError(err) ? err.message : String(err)}`\n    }\n  },\n})\n\n/**\n * Translates a LaTeX/KaTeX expression using evaluatex and returns the numeric result.\n *\n * @remarks\n * Uses the evaluatex library to parse and evaluate LaTeX expressions. Handles common constructs\n * (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek macros like `\\pi`, inverse trig,\n * `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) with a proper parser rather than\n * brittle regex.\n *\n * Also evaluates three calculus constructs **numerically** (mathjs has no symbolic integration, and\n * its symbolic `derivative` is blocklisted here for safety):\n * - Definite integrals — `\\int_{a}^{b} f \\,dx` via composite Simpson quadrature.\n * - Derivatives at a point — `\\frac{d}{dx} f \\big|_{x=a}` via central finite difference.\n * - Limits — `\\lim_{x \\to a} f` (including `a = \\pm\\infty`) via a two-sided numeric approach.\n *\n * Numeric results are rounded with `math.format(..., { precision: 12 })` and labelled\n * `Result (numeric):` to flag that they are approximations. Constructs that cannot be evaluated\n * numerically (indefinite integrals, derivatives without a point, infinite integration bounds,\n * singular integrands, divergent limits) return a specific, guiding error string.\n *\n * Parse and evaluation errors are returned as error strings rather than thrown.\n */\nexport const evaluateKatexTool = new Tool({\n  name: 'evaluate_katex',\n  description:\n    'Evaluate a KaTeX/LaTeX math expression and return the numeric result. Supports arithmetic, trig, logs, roots, and numeric calculus: definite integrals (\\\\int_{a}^{b} f dx), derivatives at a point (\\\\frac{d}{dx} f|_{x=a}), and limits (\\\\lim_{x \\\\to a} f).',\n  inputSchema: validator.object({\n    katex: validator\n      .string()\n      .required()\n      .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\" or \"\\\\int_{0}^{1} x^2 dx\"'),\n  }),\n  handler: async (args) => {\n    const { katex } = args as { katex: string }\n\n    const lengthError = validateExpression(katex)\n    if (lengthError) return lengthError\n\n    try {\n      // Calculus (\\int, \\lim, d/dx) is detected on the raw LaTeX and evaluated numerically before\n      // the scalar flattening path, which would otherwise mangle bounds/targets. Returns null for\n      // non-calculus input, falling through to the scalar evaluator below unchanged.\n      const calculus = tryCalculus(katex)\n      if (calculus !== null) return calculus\n\n      const result = evaluateLatex(katex)\n      return `Result: ${result}`\n    } catch (err) {\n      return `Error: ${isError(err) ? err.message : String(err)}`\n    }\n  },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,QAAA,GAAA,OAAA,QAAc,OAAA,GAAG;AAavB,KAAK,MAAM,MAAM;CAVf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAGe,GACf,IAAI,MAAM,MACP,KAAc,MAAM,KAAA;AAIzB,IAAM,wBAAwB;AAE9B,SAAS,mBAAmB,MAAkC;CAC5D,IAAI,KAAK,SAAS,uBAChB,OAAO,4BAA4B,sBAAsB;AAG7D;;;;;;AAOA,IAAM,kBAA2C;CAE/C,IAAI,KAAK;CACT,GAAG,KAAK;CACR,UAAU;CAEV,OAAO,KAAA;CACP,MAAM,KAAA;CACN,OAAO,KAAA;CACP,OAAO,KAAA;CACP,SAAS,KAAA;CACT,OAAO,KAAA;CACP,QAAQ,KAAA;CACR,IAAI,KAAA;CACJ,OAAO,KAAA;CACP,KAAK,KAAA;CACL,KAAK,KAAA;CACL,OAAO,KAAA;CAGP,IAAI,KAAK;CACT,QAAQ,MAAc,KAAK,IAAI,CAAC,IAAI,KAAK;CACzC,OAAO,MAAc,KAAK,IAAI,CAAC,IAAI,KAAK;CACxC,UAAU,GAAW,MAAc,KAAK,IAAI,GAAG,IAAI,CA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