@nhtio/adk 1.20260604.0 → 1.20260607.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/adk-mcp.mjs +1 -1
  3. package/batteries/embeddings/openai/adapter.cjs +1 -1
  4. package/batteries/embeddings/openai/adapter.mjs +1 -1
  5. package/batteries/embeddings/webllm/adapter.cjs +1 -1
  6. package/batteries/embeddings/webllm/adapter.mjs +1 -1
  7. package/batteries/index.d.ts +1 -0
  8. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  9. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  10. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  11. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  12. package/batteries/llm/openai_chat_completions/helpers.cjs +2 -2
  13. package/batteries/llm/openai_chat_completions/helpers.mjs +2 -2
  14. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  15. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
  16. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  17. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
  18. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  19. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  20. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  21. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  22. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  23. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
  24. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  25. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
  26. package/batteries/storage/flydrive.cjs +1 -1
  27. package/batteries/storage/flydrive.mjs +2 -2
  28. package/batteries/storage/in_memory.cjs +1 -1
  29. package/batteries/storage/in_memory.mjs +1 -1
  30. package/batteries/storage/opfs.cjs +1 -1
  31. package/batteries/storage/opfs.mjs +1 -1
  32. package/batteries/tools/color.cjs +2 -2
  33. package/batteries/tools/color.mjs +2 -2
  34. package/batteries/tools/comparison.cjs +3 -3
  35. package/batteries/tools/comparison.mjs +3 -3
  36. package/batteries/tools/data_structure.cjs +3 -3
  37. package/batteries/tools/data_structure.mjs +3 -3
  38. package/batteries/tools/datetime_extended.cjs +2 -2
  39. package/batteries/tools/datetime_extended.mjs +2 -2
  40. package/batteries/tools/datetime_math.cjs +2 -2
  41. package/batteries/tools/datetime_math.mjs +2 -2
  42. package/batteries/tools/encoding.cjs +3 -3
  43. package/batteries/tools/encoding.mjs +3 -3
  44. package/batteries/tools/formatting.cjs +3 -3
  45. package/batteries/tools/formatting.mjs +3 -3
  46. package/batteries/tools/geo_basics.cjs +2 -2
  47. package/batteries/tools/geo_basics.mjs +2 -2
  48. package/batteries/tools/math/index.d.ts +16 -5
  49. package/batteries/tools/math.cjs +340 -22
  50. package/batteries/tools/math.cjs.map +1 -1
  51. package/batteries/tools/math.mjs +338 -21
  52. package/batteries/tools/math.mjs.map +1 -1
  53. package/batteries/tools/memory.cjs +5 -5
  54. package/batteries/tools/memory.mjs +5 -5
  55. package/batteries/tools/parsing.cjs +4 -4
  56. package/batteries/tools/parsing.mjs +4 -4
  57. package/batteries/tools/retrievables.cjs +4 -4
  58. package/batteries/tools/retrievables.mjs +4 -4
  59. package/batteries/tools/standing_instructions.cjs +4 -4
  60. package/batteries/tools/standing_instructions.mjs +4 -4
  61. package/batteries/tools/statistics.cjs +4 -4
  62. package/batteries/tools/statistics.mjs +4 -4
  63. package/batteries/tools/string_processing.cjs +3 -3
  64. package/batteries/tools/string_processing.mjs +3 -3
  65. package/batteries/tools/structured_data.cjs +3 -3
  66. package/batteries/tools/structured_data.mjs +3 -3
  67. package/batteries/tools/text_analysis.cjs +3 -3
  68. package/batteries/tools/text_analysis.mjs +3 -3
  69. package/batteries/tools/text_comparison.cjs +2 -2
  70. package/batteries/tools/text_comparison.mjs +2 -2
  71. package/batteries/tools/time.cjs +2 -2
  72. package/batteries/tools/time.mjs +2 -2
  73. package/batteries/tools/unit_conversion.cjs +2 -2
  74. package/batteries/tools/unit_conversion.mjs +2 -2
  75. package/batteries/vector/arangodb/index.d.ts +38 -0
  76. package/batteries/vector/arangodb.cjs +257 -0
  77. package/batteries/vector/arangodb.cjs.map +1 -0
  78. package/batteries/vector/arangodb.mjs +255 -0
  79. package/batteries/vector/arangodb.mjs.map +1 -0
  80. package/batteries/vector/builder.cjs +297 -0
  81. package/batteries/vector/builder.cjs.map +1 -0
  82. package/batteries/vector/builder.d.ts +87 -0
  83. package/batteries/vector/builder.mjs +294 -0
  84. package/batteries/vector/builder.mjs.map +1 -0
  85. package/batteries/vector/chroma/index.d.ts +32 -0
  86. package/batteries/vector/chroma.cjs +305 -0
  87. package/batteries/vector/chroma.cjs.map +1 -0
  88. package/batteries/vector/chroma.mjs +302 -0
  89. package/batteries/vector/chroma.mjs.map +1 -0
  90. package/batteries/vector/clickhouse/index.d.ts +39 -0
  91. package/batteries/vector/clickhouse.cjs +246 -0
  92. package/batteries/vector/clickhouse.cjs.map +1 -0
  93. package/batteries/vector/clickhouse.mjs +244 -0
  94. package/batteries/vector/clickhouse.mjs.map +1 -0
  95. package/batteries/vector/cloudflare/index.d.ts +43 -0
  96. package/batteries/vector/cloudflare.cjs +397 -0
  97. package/batteries/vector/cloudflare.cjs.map +1 -0
  98. package/batteries/vector/cloudflare.mjs +395 -0
  99. package/batteries/vector/cloudflare.mjs.map +1 -0
  100. package/batteries/vector/conformance/index.d.ts +15 -0
  101. package/batteries/vector/conformance.cjs +209 -0
  102. package/batteries/vector/conformance.cjs.map +1 -0
  103. package/batteries/vector/conformance.mjs +205 -0
  104. package/batteries/vector/conformance.mjs.map +1 -0
  105. package/batteries/vector/contract.cjs +42 -0
  106. package/batteries/vector/contract.cjs.map +1 -0
  107. package/batteries/vector/contract.d.ts +39 -0
  108. package/batteries/vector/contract.mjs +40 -0
  109. package/batteries/vector/contract.mjs.map +1 -0
  110. package/batteries/vector/couchbase/index.d.ts +49 -0
  111. package/batteries/vector/couchbase.cjs +401 -0
  112. package/batteries/vector/couchbase.cjs.map +1 -0
  113. package/batteries/vector/couchbase.mjs +399 -0
  114. package/batteries/vector/couchbase.mjs.map +1 -0
  115. package/batteries/vector/duckdb/index.d.ts +33 -0
  116. package/batteries/vector/duckdb.cjs +218 -0
  117. package/batteries/vector/duckdb.cjs.map +1 -0
  118. package/batteries/vector/duckdb.mjs +216 -0
  119. package/batteries/vector/duckdb.mjs.map +1 -0
  120. package/batteries/vector/elasticsearch/index.d.ts +43 -0
  121. package/batteries/vector/elasticsearch.cjs +306 -0
  122. package/batteries/vector/elasticsearch.cjs.map +1 -0
  123. package/batteries/vector/elasticsearch.mjs +303 -0
  124. package/batteries/vector/elasticsearch.mjs.map +1 -0
  125. package/batteries/vector/exceptions.cjs +126 -0
  126. package/batteries/vector/exceptions.cjs.map +1 -0
  127. package/batteries/vector/exceptions.d.ts +142 -0
  128. package/batteries/vector/exceptions.mjs +107 -0
  129. package/batteries/vector/exceptions.mjs.map +1 -0
  130. package/batteries/vector/factory.cjs +28 -0
  131. package/batteries/vector/factory.cjs.map +1 -0
  132. package/batteries/vector/factory.d.ts +38 -0
  133. package/batteries/vector/factory.mjs +25 -0
  134. package/batteries/vector/factory.mjs.map +1 -0
  135. package/batteries/vector/filters.cjs +107 -0
  136. package/batteries/vector/filters.cjs.map +1 -0
  137. package/batteries/vector/filters.d.ts +34 -0
  138. package/batteries/vector/filters.mjs +99 -0
  139. package/batteries/vector/filters.mjs.map +1 -0
  140. package/batteries/vector/helpers.cjs +23 -0
  141. package/batteries/vector/helpers.cjs.map +1 -0
  142. package/batteries/vector/helpers.d.ts +12 -0
  143. package/batteries/vector/helpers.mjs +17 -0
  144. package/batteries/vector/helpers.mjs.map +1 -0
  145. package/batteries/vector/hnswlib/index.d.ts +35 -0
  146. package/batteries/vector/hnswlib.cjs +237 -0
  147. package/batteries/vector/hnswlib.cjs.map +1 -0
  148. package/batteries/vector/hnswlib.mjs +235 -0
  149. package/batteries/vector/hnswlib.mjs.map +1 -0
  150. package/batteries/vector/in_memory/index.d.ts +23 -0
  151. package/batteries/vector/in_memory.cjs +178 -0
  152. package/batteries/vector/in_memory.cjs.map +1 -0
  153. package/batteries/vector/in_memory.mjs +176 -0
  154. package/batteries/vector/in_memory.mjs.map +1 -0
  155. package/batteries/vector/index.d.ts +18 -0
  156. package/batteries/vector/lancedb/index.d.ts +34 -0
  157. package/batteries/vector/lancedb.cjs +224 -0
  158. package/batteries/vector/lancedb.cjs.map +1 -0
  159. package/batteries/vector/lancedb.mjs +222 -0
  160. package/batteries/vector/lancedb.mjs.map +1 -0
  161. package/batteries/vector/mariadb/index.d.ts +39 -0
  162. package/batteries/vector/mariadb.cjs +228 -0
  163. package/batteries/vector/mariadb.cjs.map +1 -0
  164. package/batteries/vector/mariadb.mjs +226 -0
  165. package/batteries/vector/mariadb.mjs.map +1 -0
  166. package/batteries/vector/meilisearch/index.d.ts +36 -0
  167. package/batteries/vector/meilisearch.cjs +242 -0
  168. package/batteries/vector/meilisearch.cjs.map +1 -0
  169. package/batteries/vector/meilisearch.mjs +240 -0
  170. package/batteries/vector/meilisearch.mjs.map +1 -0
  171. package/batteries/vector/migrate.cjs +54 -0
  172. package/batteries/vector/migrate.cjs.map +1 -0
  173. package/batteries/vector/migrate.d.ts +30 -0
  174. package/batteries/vector/migrate.mjs +52 -0
  175. package/batteries/vector/migrate.mjs.map +1 -0
  176. package/batteries/vector/milvus/index.d.ts +35 -0
  177. package/batteries/vector/milvus.cjs +357 -0
  178. package/batteries/vector/milvus.cjs.map +1 -0
  179. package/batteries/vector/milvus.mjs +354 -0
  180. package/batteries/vector/milvus.mjs.map +1 -0
  181. package/batteries/vector/mongodb/index.d.ts +46 -0
  182. package/batteries/vector/mongodb.cjs +270 -0
  183. package/batteries/vector/mongodb.cjs.map +1 -0
  184. package/batteries/vector/mongodb.mjs +268 -0
  185. package/batteries/vector/mongodb.mjs.map +1 -0
  186. package/batteries/vector/neo4j/index.d.ts +38 -0
  187. package/batteries/vector/neo4j.cjs +231 -0
  188. package/batteries/vector/neo4j.cjs.map +1 -0
  189. package/batteries/vector/neo4j.mjs +229 -0
  190. package/batteries/vector/neo4j.mjs.map +1 -0
  191. package/batteries/vector/opensearch/index.d.ts +46 -0
  192. package/batteries/vector/opensearch.cjs +316 -0
  193. package/batteries/vector/opensearch.cjs.map +1 -0
  194. package/batteries/vector/opensearch.mjs +313 -0
  195. package/batteries/vector/opensearch.mjs.map +1 -0
  196. package/batteries/vector/oracle23ai/index.d.ts +45 -0
  197. package/batteries/vector/oracle23ai.cjs +340 -0
  198. package/batteries/vector/oracle23ai.cjs.map +1 -0
  199. package/batteries/vector/oracle23ai.mjs +338 -0
  200. package/batteries/vector/oracle23ai.mjs.map +1 -0
  201. package/batteries/vector/orama/index.d.ts +23 -0
  202. package/batteries/vector/orama.cjs +272 -0
  203. package/batteries/vector/orama.cjs.map +1 -0
  204. package/batteries/vector/orama.mjs +270 -0
  205. package/batteries/vector/orama.mjs.map +1 -0
  206. package/batteries/vector/pgvector/index.d.ts +43 -0
  207. package/batteries/vector/pgvector.cjs +411 -0
  208. package/batteries/vector/pgvector.cjs.map +1 -0
  209. package/batteries/vector/pgvector.mjs +408 -0
  210. package/batteries/vector/pgvector.mjs.map +1 -0
  211. package/batteries/vector/pinecone/index.d.ts +38 -0
  212. package/batteries/vector/pinecone.cjs +415 -0
  213. package/batteries/vector/pinecone.cjs.map +1 -0
  214. package/batteries/vector/pinecone.mjs +412 -0
  215. package/batteries/vector/pinecone.mjs.map +1 -0
  216. package/batteries/vector/plan.cjs +2 -0
  217. package/batteries/vector/plan.d.ts +65 -0
  218. package/batteries/vector/plan.mjs +0 -0
  219. package/batteries/vector/qdrant/index.d.ts +34 -0
  220. package/batteries/vector/qdrant.cjs +286 -0
  221. package/batteries/vector/qdrant.cjs.map +1 -0
  222. package/batteries/vector/qdrant.mjs +284 -0
  223. package/batteries/vector/qdrant.mjs.map +1 -0
  224. package/batteries/vector/redis/index.d.ts +44 -0
  225. package/batteries/vector/redis.cjs +391 -0
  226. package/batteries/vector/redis.cjs.map +1 -0
  227. package/batteries/vector/redis.mjs +388 -0
  228. package/batteries/vector/redis.mjs.map +1 -0
  229. package/batteries/vector/retrievable.cjs +69 -0
  230. package/batteries/vector/retrievable.cjs.map +1 -0
  231. package/batteries/vector/retrievable.mjs +67 -0
  232. package/batteries/vector/retrievable.mjs.map +1 -0
  233. package/batteries/vector/retrievable_glue.d.ts +24 -0
  234. package/batteries/vector/s3vectors/index.d.ts +52 -0
  235. package/batteries/vector/s3vectors.cjs +438 -0
  236. package/batteries/vector/s3vectors.cjs.map +1 -0
  237. package/batteries/vector/s3vectors.mjs +436 -0
  238. package/batteries/vector/s3vectors.mjs.map +1 -0
  239. package/batteries/vector/schema.cjs +96 -0
  240. package/batteries/vector/schema.cjs.map +1 -0
  241. package/batteries/vector/schema.d.ts +40 -0
  242. package/batteries/vector/schema.mjs +93 -0
  243. package/batteries/vector/schema.mjs.map +1 -0
  244. package/batteries/vector/solr/index.d.ts +36 -0
  245. package/batteries/vector/solr.cjs +230 -0
  246. package/batteries/vector/solr.cjs.map +1 -0
  247. package/batteries/vector/solr.mjs +228 -0
  248. package/batteries/vector/solr.mjs.map +1 -0
  249. package/batteries/vector/sqlite_vec/index.d.ts +30 -0
  250. package/batteries/vector/sqlite_vec.cjs +318 -0
  251. package/batteries/vector/sqlite_vec.cjs.map +1 -0
  252. package/batteries/vector/sqlite_vec.mjs +316 -0
  253. package/batteries/vector/sqlite_vec.mjs.map +1 -0
  254. package/batteries/vector/surrealdb/index.d.ts +37 -0
  255. package/batteries/vector/surrealdb.cjs +230 -0
  256. package/batteries/vector/surrealdb.cjs.map +1 -0
  257. package/batteries/vector/surrealdb.mjs +228 -0
  258. package/batteries/vector/surrealdb.mjs.map +1 -0
  259. package/batteries/vector/types.cjs +2 -0
  260. package/batteries/vector/types.d.ts +100 -0
  261. package/batteries/vector/types.mjs +0 -0
  262. package/batteries/vector/typesense/index.d.ts +38 -0
  263. package/batteries/vector/typesense.cjs +272 -0
  264. package/batteries/vector/typesense.cjs.map +1 -0
  265. package/batteries/vector/typesense.mjs +270 -0
  266. package/batteries/vector/typesense.mjs.map +1 -0
  267. package/batteries/vector/validation.cjs +90 -0
  268. package/batteries/vector/validation.cjs.map +1 -0
  269. package/batteries/vector/validation.d.ts +18 -0
  270. package/batteries/vector/validation.mjs +83 -0
  271. package/batteries/vector/validation.mjs.map +1 -0
  272. package/batteries/vector/vector_store_constructor.cjs +56 -0
  273. package/batteries/vector/vector_store_constructor.cjs.map +1 -0
  274. package/batteries/vector/vector_store_constructor.d.ts +30 -0
  275. package/batteries/vector/vector_store_constructor.mjs +53 -0
  276. package/batteries/vector/vector_store_constructor.mjs.map +1 -0
  277. package/batteries/vector/vespa/index.d.ts +39 -0
  278. package/batteries/vector/vespa.cjs +423 -0
  279. package/batteries/vector/vespa.cjs.map +1 -0
  280. package/batteries/vector/vespa.mjs +421 -0
  281. package/batteries/vector/vespa.mjs.map +1 -0
  282. package/batteries/vector/weaviate/index.d.ts +57 -0
  283. package/batteries/vector/weaviate.cjs +325 -0
  284. package/batteries/vector/weaviate.cjs.map +1 -0
  285. package/batteries/vector/weaviate.mjs +322 -0
  286. package/batteries/vector/weaviate.mjs.map +1 -0
  287. package/batteries/vector.cjs +63 -0
  288. package/batteries/vector.mjs +14 -0
  289. package/batteries.cjs +62 -0
  290. package/batteries.mjs +15 -1
  291. package/{chunk-kRvK8_k2.mjs → chunk-Bpcn9VDT.mjs} +5 -1
  292. package/{common-lMrnzoyn.mjs → common-BT0nfCi9.mjs} +8 -8
  293. package/{common-lMrnzoyn.mjs.map → common-BT0nfCi9.mjs.map} +1 -1
  294. package/{common-D_e5zYsG.js → common-Cj8TaQ9U.js} +8 -8
  295. package/{common-D_e5zYsG.js.map → common-Cj8TaQ9U.js.map} +1 -1
  296. package/common.cjs +7 -7
  297. package/common.mjs +7 -7
  298. package/{dispatch_runner-CpuyATj1.js → dispatch_runner-BHBNupqp.js} +2 -2
  299. package/dispatch_runner-BHBNupqp.js.map +1 -0
  300. package/{dispatch_runner-CDF3X0nv.mjs → dispatch_runner-DPcS7Y_M.mjs} +2 -2
  301. package/dispatch_runner-DPcS7Y_M.mjs.map +1 -0
  302. package/dispatch_runner.cjs +1 -1
  303. package/dispatch_runner.mjs +1 -1
  304. package/forge.cjs +4 -4
  305. package/forge.mjs +4 -4
  306. package/guards.cjs +8 -8
  307. package/guards.mjs +8 -8
  308. package/index.cjs +12 -12
  309. package/index.mjs +12 -12
  310. package/lib/classes/tool_registry.d.ts +70 -4
  311. package/mcp/adk-docs-corpus.json +1 -1
  312. package/package.json +424 -88
  313. package/skills/adk-assembly/SKILL.md +2 -2
  314. package/{spooled_artifact-B8gIIn9h.js → spooled_artifact-BTq6Nzfy.js} +4 -4
  315. package/spooled_artifact-BTq6Nzfy.js.map +1 -0
  316. package/{spooled_artifact-CWoKUDEm.mjs → spooled_artifact-CHoZgWwI.mjs} +4 -4
  317. package/spooled_artifact-CHoZgWwI.mjs.map +1 -0
  318. package/spooled_artifact.cjs +2 -2
  319. package/spooled_artifact.mjs +2 -2
  320. package/{spooled_markdown_artifact-DQX0RCdI.js → spooled_markdown_artifact-CALSDxIx.js} +3 -3
  321. package/{spooled_markdown_artifact-DQX0RCdI.js.map → spooled_markdown_artifact-CALSDxIx.js.map} +1 -1
  322. package/{spooled_markdown_artifact-CNle4jXN.mjs → spooled_markdown_artifact-Ci5UL7l4.mjs} +3 -3
  323. package/{spooled_markdown_artifact-CNle4jXN.mjs.map → spooled_markdown_artifact-Ci5UL7l4.mjs.map} +1 -1
  324. package/src/types/evaluatex.d.ts +31 -0
  325. package/{thought-BD6AkkOr.js → thought-BbwhJ1wb.js} +4 -4
  326. package/thought-BbwhJ1wb.js.map +1 -0
  327. package/{thought-B_P8LiB6.mjs → thought-D34QQZZ9.mjs} +4 -4
  328. package/thought-D34QQZZ9.mjs.map +1 -0
  329. package/{tool-CRZSUcdP.mjs → tool-CMhaDRNd.mjs} +3 -3
  330. package/tool-CMhaDRNd.mjs.map +1 -0
  331. package/{tool-CX9vNHAw.js → tool-CVyZkFC7.js} +3 -3
  332. package/tool-CVyZkFC7.js.map +1 -0
  333. package/{tool_call-BUeMuCc6.mjs → tool_call-CV5qVNlb.mjs} +3 -3
  334. package/{tool_call-BUeMuCc6.mjs.map → tool_call-CV5qVNlb.mjs.map} +1 -1
  335. package/{tool_call--7ti-frB.js → tool_call-Db68hB7y.js} +3 -3
  336. package/{tool_call--7ti-frB.js.map → tool_call-Db68hB7y.js.map} +1 -1
  337. package/{tool_registry-BGHg6KTq.mjs → tool_registry-D1pSSlsd.mjs} +109 -22
  338. package/tool_registry-D1pSSlsd.mjs.map +1 -0
  339. package/{tool_registry-CtCQ4Xoz.js → tool_registry-DYUYqXvo.js} +109 -22
  340. package/tool_registry-DYUYqXvo.js.map +1 -0
  341. package/{turn_runner-BJTtAORU.js → turn_runner-DqWHNP80.js} +5 -5
  342. package/turn_runner-DqWHNP80.js.map +1 -0
  343. package/{turn_runner-C02LZHjt.mjs → turn_runner-fg1Wc3dK.mjs} +5 -5
  344. package/turn_runner-fg1Wc3dK.mjs.map +1 -0
  345. package/turn_runner.cjs +1 -1
  346. package/turn_runner.mjs +1 -1
  347. package/dispatch_runner-CDF3X0nv.mjs.map +0 -1
  348. package/dispatch_runner-CpuyATj1.js.map +0 -1
  349. package/spooled_artifact-B8gIIn9h.js.map +0 -1
  350. package/spooled_artifact-CWoKUDEm.mjs.map +0 -1
  351. package/thought-BD6AkkOr.js.map +0 -1
  352. package/thought-B_P8LiB6.mjs.map +0 -1
  353. package/tool-CRZSUcdP.mjs.map +0 -1
  354. package/tool-CX9vNHAw.js.map +0 -1
  355. package/tool_registry-BGHg6KTq.mjs.map +0 -1
  356. package/tool_registry-CtCQ4Xoz.js.map +0 -1
  357. package/turn_runner-BJTtAORU.js.map +0 -1
  358. package/turn_runner-C02LZHjt.mjs.map +0 -1
@@ -1 +1 @@
1
- {"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 { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\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 * Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.\n */\nfunction latexToMathjs(latex: string): string {\n let expr = latex.trim()\n\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n for (let i = 0; i < 10; 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(\n /\\\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g,\n '$1'\n )\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/**\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 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 into mathjs syntax, evaluates it, and returns the result.\n *\n * @remarks\n * Translates common LaTeX constructs (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek\n * macros like `\\pi`, `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) into their\n * mathjs equivalents before evaluation. Both the source and the translated mathjs expression\n * are subject to the 1000-character length cap.\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: 'Evaluate a KaTeX/LaTeX math expression and return the numeric result.',\n inputSchema: validator.object({\n katex: validator\n .string()\n .required()\n .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\"'),\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 const mathjsExpr = latexToMathjs(katex)\n\n const translatedLengthError = validateExpression(mathjsExpr)\n if (translatedLengthError) return translatedLengthError\n\n const result = math.evaluate!(mathjsExpr)\n return `Converted: ${mathjsExpr}\\nResult: ${result}`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,IAAM,QAAA,GAAA,OAA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KAAK,SAAU,UACc;EAC9C,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
1
+ {"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), or just strip subscript for single-arg\n expr = expr.replace(/log_\\{?(\\w+)\\}?\\(/g, (_, base) => {\n const baseLower = base.toLowerCase()\n if (baseLower === '10') return 'log10('\n if (baseLower === '2') return 'log2('\n if (baseLower === 'e') return 'ln('\n // Generic base: convert log_b(x) to ln(x)/ln(b) — evaluatex handles the\n // resulting expression fine.\n return `ln(/ln(${base})`\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 // 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 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,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;;;;;;;;;;;;;AAgBA,IAAa,gBAAgB,IAAI,aAAA,KAAK;CACpC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO,EAC5B,YAAY,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0CAAwC,EAChG,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,eAAe;EAEvB,MAAM,cAAc,mBAAmB,UAAU;EACjD,IAAI,aAAa,OAAO;EAExB,IAAI;GACF,MAAM,SAAS,KAAK,SAAU,UAAU;GAGxC,OAAO,WAAW,OAAO,YAFZ,KAAK,MAAO,UACX,EAAK,MACkB,EAAM,KAAK,OAAO;EACzD,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;AAwBD,IAAa,oBAAoB,IAAI,aAAA,KAAK;CACxC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO,EAC5B,OAAO,kBAAA,UACJ,OAAO,EACP,SAAS,EACT,YAAY,iFAA6E,EAC9F,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,UAAU;EAElB,MAAM,cAAc,mBAAmB,KAAK;EAC5C,IAAI,aAAa,OAAO;EAExB,IAAI;GAIF,MAAM,WAAW,YAAY,KAAK;GAClC,IAAI,aAAa,MAAM,OAAO;GAG9B,OAAO,WADQ,cAAc,KACX;EACpB,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
@@ -1,9 +1,10 @@
1
- import { o as isError } from "../../tool_registry-BGHg6KTq.mjs";
2
- import { t as Tool } from "../../tool-CRZSUcdP.mjs";
3
- import "../../common-lMrnzoyn.mjs";
1
+ import { o as isError, s as isInstanceOf } from "../../tool_registry-D1pSSlsd.mjs";
2
+ import { t as Tool } from "../../tool-CMhaDRNd.mjs";
3
+ import "../../common-BT0nfCi9.mjs";
4
4
  import "../../guards.mjs";
5
5
  import { validator } from "@nhtio/validation";
6
6
  import { all, create } from "mathjs";
7
+ import evaluatex from "evaluatex";
7
8
  //#region src/batteries/tools/math/index.ts
8
9
  /**
9
10
  * Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.
@@ -30,20 +31,110 @@ function validateExpression(expr) {
30
31
  if (expr.length > MAX_EXPRESSION_LENGTH) return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`;
31
32
  }
32
33
  /**
33
- * Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.
34
+ * EvaluateX scope providing constants and function aliases that evaluatex does not ship
35
+ * out-of-the-box, matching the capabilities that were previously provided by the mathjs
36
+ * translation layer.
34
37
  */
35
- function latexToMathjs(latex) {
38
+ var EVALUATEX_SCOPE = {
39
+ pi: Math.PI,
40
+ e: Math.E,
41
+ infinity: Infinity,
42
+ alpha: void 0,
43
+ beta: void 0,
44
+ gamma: void 0,
45
+ delta: void 0,
46
+ epsilon: void 0,
47
+ theta: void 0,
48
+ lambda: void 0,
49
+ mu: void 0,
50
+ sigma: void 0,
51
+ tau: void 0,
52
+ phi: void 0,
53
+ omega: void 0,
54
+ ln: Math.log,
55
+ log10: (x) => Math.log(x) / Math.LN10,
56
+ log2: (x) => Math.log(x) / Math.LN2,
57
+ nthRoot: (x, n) => Math.pow(x, 1 / n),
58
+ det: (x) => x
59
+ };
60
+ /**
61
+ * Translate a LaTeX/KaTeX expression to evaluatex-compatible syntax and evaluate it.
62
+ *
63
+ * The translation is a lightweight pass over the LaTeX source that handles common constructs
64
+ * (frac, sqrt, trig, Greek macros, delimiters, etc.) and feeds the result to evaluatex with
65
+ * a pre-built scope providing constants and function aliases. This replaces the previous
66
+ * hand-rolled regex → mathjs pipeline.
67
+ */
68
+ function evaluateLatex(latex) {
36
69
  let expr = latex.trim();
37
70
  expr = expr.replace(/^\$\$?|\$\$?$/g, "");
38
71
  expr = expr.replace(/^\\[[(]|\\[\])]$/g, "");
39
- for (let i = 0; i < 10; i++) {
72
+ for (let i = 0; i < 20; i++) {
40
73
  const before = expr;
41
- expr = expr.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g, "(($1)/($2))");
74
+ expr = expr.replace(/\\frac\s*\{([^}]*)\}\s*\{([^}]*)\}/g, "($1)/($2)");
42
75
  if (expr === before) break;
43
76
  }
44
- expr = expr.replace(/\\sqrt\[([^\]]+)\]\s*\{([^{}]*)\}/g, "nthRoot($2, $1)");
45
- expr = expr.replace(/\\sqrt\s*\{([^{}]*)\}/g, "sqrt($1)");
46
- expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
77
+ expr = expr.replace(/\\sqrt\[([^\]]+)\]\s*\{([^}]*)\}/g, "nthRoot($2, $1)");
78
+ expr = expr.replace(/\\sqrt\s*\{([^}]*)\}/g, "sqrt($1)");
79
+ expr = expr.replace(/\\arcsin/g, "asin");
80
+ expr = expr.replace(/\\arccos/g, "acos");
81
+ expr = expr.replace(/\\arctan/g, "atan");
82
+ expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
83
+ expr = expr.replace(/log_\{?(\w+)\}?\(/g, (_, base) => {
84
+ const baseLower = base.toLowerCase();
85
+ if (baseLower === "10") return "log10(";
86
+ if (baseLower === "2") return "log2(";
87
+ if (baseLower === "e") return "ln(";
88
+ return `ln(/ln(${base})`;
89
+ });
90
+ expr = expr.replace(/_\{[^}]*\}/g, "");
91
+ expr = expr.replace(/_\w/g, "");
92
+ expr = expr.replace(/\^{([^{}]*)}/g, "^($1)");
93
+ expr = expr.replace(/\\pi/g, "pi");
94
+ expr = expr.replace(/\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g, "$1");
95
+ expr = expr.replace(/\\cdot/g, "*");
96
+ expr = expr.replace(/\\times/g, "*");
97
+ expr = expr.replace(/\\div/g, "/");
98
+ expr = expr.replace(/\\infty/g, "infinity");
99
+ expr = expr.replace(/\\left\s*([([{|])/g, "$1");
100
+ expr = expr.replace(/\\right\s*([)\]}|])/g, "$1");
101
+ expr = expr.replace(/\\sum/g, "sum");
102
+ expr = expr.replace(/\\prod/g, "prod");
103
+ expr = expr.replace(/\\,/g, " ");
104
+ expr = expr.replace(/\\;/g, " ");
105
+ expr = expr.replace(/\\quad/g, " ");
106
+ expr = expr.replace(/\\qquad/g, " ");
107
+ expr = expr.replace(/\\text\{([^{}]*)\}/g, "");
108
+ expr = expr.replace(/(\d)([a-zA-Z(])/g, "$1*$2");
109
+ expr = expr.replace(/\)\s*\(/g, ")*(");
110
+ expr = expr.replace(/\s+/g, " ").trim();
111
+ const result = evaluatex(expr, EVALUATEX_SCOPE)();
112
+ if (typeof result !== "number" || !Number.isFinite(result)) throw new Error("Result is not finite");
113
+ return result;
114
+ }
115
+ /**
116
+ * Lightweight LaTeX-to-string translator for internal use by the numeric calculus path.
117
+ *
118
+ * This is the same translation pass as {@link evaluateLatex}, but returns the translated string
119
+ * (compatible with mathjs syntax) rather than evaluating it. Used by the calculus handlers to
120
+ * convert integrands, function bodies, and bound expressions before passing them to
121
+ * `math.evaluate` for specific-point evaluation.
122
+ */
123
+ function translateLatex(latex) {
124
+ let expr = latex.trim();
125
+ expr = expr.replace(/^\$\$?|\$\$?$/g, "");
126
+ expr = expr.replace(/^\\[[(]|\\[\])]$/g, "");
127
+ for (let i = 0; i < 20; i++) {
128
+ const before = expr;
129
+ expr = expr.replace(/\\frac\s*\{([^}]*)\}\s*\{([^}]*)\}/g, "($1)/($2)");
130
+ if (expr === before) break;
131
+ }
132
+ expr = expr.replace(/\\sqrt\[([^\]]+)\]\s*\{([^}]*)\}/g, "nthRoot($2, $1)");
133
+ expr = expr.replace(/\\sqrt\s*\{([^}]*)\}/g, "sqrt($1)");
134
+ expr = expr.replace(/\\arcsin/g, "asin");
135
+ expr = expr.replace(/\\arccos/g, "acos");
136
+ expr = expr.replace(/\\arctan/g, "atan");
137
+ expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
47
138
  expr = expr.replace(/log_\{?(\w+)\}?\s*\(([^)]+)\)/g, "log($2, $1)");
48
139
  expr = expr.replace(/\^{([^{}]*)}/g, "^($1)");
49
140
  expr = expr.replace(/_\{[^{}]*\}/g, "");
@@ -68,6 +159,222 @@ function latexToMathjs(latex) {
68
159
  expr = expr.replace(/\s+/g, " ").trim();
69
160
  return expr;
70
161
  }
162
+ /** A tagged error whose message is surfaced to the model verbatim (caught by {@link tryCalculus}). */
163
+ var CalculusError = class extends Error {};
164
+ /** Evaluate a mathjs expression at a single point, guarding against non-finite results. */
165
+ function evalAt(expr, varName, x) {
166
+ const y = math.evaluate(expr, { [varName]: x });
167
+ if (typeof y !== "number" || !Number.isFinite(y)) throw new CalculusError("NON_FINITE");
168
+ return y;
169
+ }
170
+ /** Composite Simpson's rule over a finite interval. Throws {@link CalculusError} on a singularity. */
171
+ function simpson(fn, a, b, n = 1e3) {
172
+ if (n % 2 === 1) n++;
173
+ const h = (b - a) / n;
174
+ let sum = fn(a) + fn(b);
175
+ for (let i = 1; i < n; i++) sum += (i % 2 === 1 ? 4 : 2) * fn(a + i * h);
176
+ const result = h / 3 * sum;
177
+ if (!Number.isFinite(result)) throw new CalculusError("NON_FINITE");
178
+ return result;
179
+ }
180
+ /** Round numeric output to 12 significant digits, collapsing floating-point noise. */
181
+ function formatNumeric(n) {
182
+ if (Math.abs(n) < 1e-9) return "0";
183
+ return math.format(n, { precision: 12 });
184
+ }
185
+ /**
186
+ * Reads a single `_`/`^` script starting at `i`, supporting braced (`_{0}`, `^{\pi}`), command
187
+ * (`^\pi`), and bare-token (`_0`, `^1`) forms. Returns the mark, its raw-LaTeX value, and the next
188
+ * index, or `null` when there is no script at `i`.
189
+ */
190
+ function readScript(s, i) {
191
+ while (s[i] === " ") i++;
192
+ const mark = s[i];
193
+ if (mark !== "_" && mark !== "^") return null;
194
+ i++;
195
+ while (s[i] === " ") i++;
196
+ if (s[i] === "{") {
197
+ let depth = 0;
198
+ const start = ++i;
199
+ for (; i < s.length; i++) if (s[i] === "{") depth++;
200
+ else if (s[i] === "}") {
201
+ if (depth === 0) break;
202
+ depth--;
203
+ }
204
+ return {
205
+ mark,
206
+ val: s.slice(start, i),
207
+ next: i + 1
208
+ };
209
+ }
210
+ if (s[i] === "\\") {
211
+ const m = /^\\[a-zA-Z]+/.exec(s.slice(i));
212
+ if (!m) return null;
213
+ return {
214
+ mark,
215
+ val: m[0],
216
+ next: i + m[0].length
217
+ };
218
+ }
219
+ const m = /^[A-Za-z0-9.]+/.exec(s.slice(i));
220
+ if (!m) return null;
221
+ return {
222
+ mark,
223
+ val: m[0],
224
+ next: i + m[0].length
225
+ };
226
+ }
227
+ /** Translate a raw-LaTeX bound/target fragment and evaluate it to a finite number. */
228
+ function evalBound(latex) {
229
+ const trimmed = latex.trim();
230
+ if (/\\infty/.test(trimmed)) throw new CalculusError("INFINITE_BOUND");
231
+ const mathjsExpr = translateLatex(trimmed);
232
+ const value = math.evaluate(mathjsExpr);
233
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new CalculusError("BAD_BOUND");
234
+ return value;
235
+ }
236
+ /** Evaluate a definite integral `\int_{a}^{b} f \,dx` by Simpson quadrature. */
237
+ function evalIntegral(s) {
238
+ const m = /\\int(?:\\limits)?/.exec(s);
239
+ if (!m) throw new CalculusError("NOT_INTEGRAL");
240
+ let i = m.index + m[0].length;
241
+ const scripts = {
242
+ "_": void 0,
243
+ "^": void 0
244
+ };
245
+ for (let k = 0; k < 2; k++) {
246
+ const sc = readScript(s, i);
247
+ if (!sc) break;
248
+ scripts[sc.mark] = sc.val;
249
+ i = sc.next;
250
+ }
251
+ if (scripts._ === void 0 || scripts["^"] === void 0) throw new CalculusError("INDEFINITE");
252
+ const rest = s.slice(i);
253
+ const diff = /\\?,?\s*\bd\s*([a-zA-Z])\s*$/.exec(rest);
254
+ if (!diff) throw new CalculusError("NO_DIFFERENTIAL");
255
+ const variable = diff[1];
256
+ const integrandLatex = rest.slice(0, diff.index);
257
+ if (integrandLatex.trim().length === 0) throw new CalculusError("NO_INTEGRAND");
258
+ const a = evalBound(scripts._);
259
+ const b = evalBound(scripts["^"]);
260
+ const integrand = translateLatex(integrandLatex);
261
+ const fn = (x) => evalAt(integrand, variable, x);
262
+ let result;
263
+ if (a === b) result = 0;
264
+ else if (a < b) result = simpson(fn, a, b);
265
+ else result = -simpson(fn, b, a);
266
+ return `Converted: ∫(${integrand}) d${variable} from ${formatNumeric(a)} to ${formatNumeric(b)}\nResult (numeric): ${formatNumeric(result)}`;
267
+ }
268
+ /** Evaluate a derivative `\frac{d}{dx} f \big|_{x=a}` at a point via central finite difference. */
269
+ function evalDerivative(s) {
270
+ let variable;
271
+ let body = s;
272
+ const fracOp = /\\frac\s*\{\s*d\s*\}\s*\{\s*d\s*([a-zA-Z])\s*\}/.exec(s);
273
+ if (fracOp) {
274
+ variable = fracOp[1];
275
+ body = s.slice(fracOp.index + fracOp[0].length);
276
+ } else {
277
+ const bareOp = /(?:^|[^a-zA-Z])d\s*\/\s*d([a-zA-Z])/.exec(s);
278
+ if (bareOp) {
279
+ variable = bareOp[1];
280
+ body = s.slice(bareOp.index + bareOp[0].length);
281
+ }
282
+ }
283
+ if (!variable) throw new CalculusError("NOT_DERIVATIVE");
284
+ body = body.replace(/\\left\.?/g, "").replace(/\\right\.?/g, "");
285
+ const bar = /\\?(?:Big|big|bigg|Bigg)?\s*\|\s*_\s*\{?\s*([a-zA-Z])\s*=\s*([^}]+?)\s*\}?\s*$/.exec(body);
286
+ if (!bar) throw new CalculusError("NO_POINT");
287
+ const point = evalBound(bar[2]);
288
+ let fnLatex = body.slice(0, bar.index).trim();
289
+ fnLatex = fnLatex.replace(/^\\?\(([\s\S]*)\\?\)$/, "$1").replace(/^\[([\s\S]*)\]$/, "$1").trim();
290
+ if (fnLatex.length === 0) throw new CalculusError("NO_FUNCTION");
291
+ const expr = translateLatex(fnLatex);
292
+ const h = 1e-6;
293
+ const fn = (x) => evalAt(expr, variable, x);
294
+ const result = (fn(point + h) - fn(point - h)) / (2 * h);
295
+ if (!Number.isFinite(result)) throw new CalculusError("NON_FINITE");
296
+ return `Converted: d/d${variable}(${expr}) at ${variable}=${formatNumeric(point)}\nResult (numeric): ${formatNumeric(result)}`;
297
+ }
298
+ /** Evaluate a limit `\lim_{x \to a} f(x)` by a two-sided numeric approach. */
299
+ function evalLimit(s) {
300
+ const head = /\\lim\s*_\s*\{\s*([a-zA-Z])\s*\\to\s*([\s\S]+?)\s*\}/.exec(s);
301
+ if (!head) throw new CalculusError("NOT_LIMIT");
302
+ const variable = head[1];
303
+ let targetLatex = head[2].trim();
304
+ const bodyLatex = s.slice(head.index + head[0].length).trim();
305
+ if (bodyLatex.length === 0) throw new CalculusError("NO_FUNCTION");
306
+ let side = "both";
307
+ const oneSided = /\^\s*\{?\s*([+-])\s*\}?\s*$/.exec(targetLatex);
308
+ if (oneSided) {
309
+ side = oneSided[1] === "+" ? "plus" : "minus";
310
+ targetLatex = targetLatex.slice(0, oneSided.index).trim();
311
+ }
312
+ const expr = translateLatex(bodyLatex);
313
+ const fn = (x) => evalAt(expr, variable, x);
314
+ const eps = 1e-6;
315
+ let result;
316
+ let targetLabel;
317
+ if (/^-\s*\\infty$/.test(targetLatex)) {
318
+ result = fn(-1e8);
319
+ targetLabel = "-∞";
320
+ } else if (/^\\infty$/.test(targetLatex)) {
321
+ result = fn(1e8);
322
+ targetLabel = "∞";
323
+ } else {
324
+ const target = evalBound(targetLatex);
325
+ targetLabel = formatNumeric(target);
326
+ if (side === "plus") result = fn(target + eps);
327
+ else if (side === "minus") result = fn(target - eps);
328
+ else {
329
+ const lo = fn(target - eps);
330
+ const hi = fn(target + eps);
331
+ const avg = (lo + hi) / 2;
332
+ if (Math.abs(hi - lo) > .001 * Math.max(1, Math.abs(avg))) throw new CalculusError("LIMIT_MISMATCH");
333
+ result = avg;
334
+ }
335
+ }
336
+ if (!Number.isFinite(result)) throw new CalculusError("LIMIT_UNBOUNDED");
337
+ const nearest = Math.round(result);
338
+ if (Math.abs(result - nearest) < 1e-6) result = nearest;
339
+ return `Converted: lim ${variable}→${targetLabel} of (${expr})\nResult (numeric): ${formatNumeric(result)}`;
340
+ }
341
+ /** Human-readable, model-actionable message for each {@link CalculusError} tag. */
342
+ function calculusErrorMessage(tag) {
343
+ switch (tag) {
344
+ case "INDEFINITE": return "Cannot evaluate an indefinite integral numerically. Provide bounds, e.g. \\int_{0}^{1} x dx.";
345
+ case "NO_DIFFERENTIAL": return "Could not find the integration variable. Expected a trailing differential like 'dx'.";
346
+ case "NO_INTEGRAND": return "The integral has no integrand to evaluate.";
347
+ case "INFINITE_BOUND": return "Infinite integration bounds are not supported. Provide finite numeric bounds, e.g. \\int_{0}^{1} f dx.";
348
+ case "BAD_BOUND": return "Could not evaluate the integration bounds to numbers.";
349
+ case "NO_POINT": return "Cannot evaluate a derivative numerically without a point. Specify where, e.g. \\frac{d}{dx}(x^2)\\Big|_{x=3}.";
350
+ case "NO_FUNCTION": return "Could not find the function to evaluate.";
351
+ case "LIMIT_MISMATCH": return "The limit may not exist (left and right values disagree).";
352
+ case "LIMIT_UNBOUNDED": return "The limit appears to diverge (function is unbounded near the target).";
353
+ case "NON_FINITE": return "The expression is not finite over the requested range (possible singularity); cannot evaluate numerically.";
354
+ default: return "Could not evaluate the calculus expression.";
355
+ }
356
+ }
357
+ /**
358
+ * Detects a calculus construct in raw LaTeX and routes it to the matching numeric handler. Returns
359
+ * the result/error string, or `null` when the input is not a calculus expression (so the caller
360
+ * falls through to the scalar evaluation path unchanged).
361
+ */
362
+ function tryCalculus(latex) {
363
+ let s = latex.trim();
364
+ s = s.replace(/^\$\$?|\$\$?$/g, "");
365
+ s = s.replace(/^\\[[(]|\\[\])]$/g, "").trim();
366
+ let handler;
367
+ if (/\\int/.test(s)) handler = evalIntegral;
368
+ else if (/\\lim/.test(s)) handler = evalLimit;
369
+ else if (/\\frac\s*\{\s*d\s*\}\s*\{\s*d\s*[a-zA-Z]\s*\}/.test(s) || /(?:^|[^a-zA-Z])d\s*\/\s*d[a-zA-Z]/.test(s)) handler = evalDerivative;
370
+ if (!handler) return null;
371
+ try {
372
+ return handler(s);
373
+ } catch (err) {
374
+ if (isInstanceOf(err, "CalculusError", CalculusError)) return `Error: ${calculusErrorMessage(err.message)}`;
375
+ return `Error: ${isError(err) ? err.message : String(err)}`;
376
+ }
377
+ }
71
378
  /**
72
379
  * Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX
73
380
  * representation of the parsed expression.
@@ -99,29 +406,39 @@ var calculateTool = new Tool({
99
406
  }
100
407
  });
101
408
  /**
102
- * Translates a LaTeX/KaTeX expression into mathjs syntax, evaluates it, and returns the result.
409
+ * Translates a LaTeX/KaTeX expression using evaluatex and returns the numeric result.
103
410
  *
104
411
  * @remarks
105
- * Translates common LaTeX constructs (`\frac{a}{b}`, `\sqrt{...}`, `\cdot`, `\times`, Greek
106
- * macros like `\pi`, `\left`/`\right` delimiters, `\text{...}`, subscripts, etc.) into their
107
- * mathjs equivalents before evaluation. Both the source and the translated mathjs expression
108
- * are subject to the 1000-character length cap.
412
+ * Uses the evaluatex library to parse and evaluate LaTeX expressions. Handles common constructs
413
+ * (`\frac{a}{b}`, `\sqrt{...}`, `\cdot`, `\times`, Greek macros like `\pi`, inverse trig,
414
+ * `\left`/`\right` delimiters, `\text{...}`, subscripts, etc.) with a proper parser rather than
415
+ * brittle regex.
416
+ *
417
+ * Also evaluates three calculus constructs **numerically** (mathjs has no symbolic integration, and
418
+ * its symbolic `derivative` is blocklisted here for safety):
419
+ * - Definite integrals — `\int_{a}^{b} f \,dx` via composite Simpson quadrature.
420
+ * - Derivatives at a point — `\frac{d}{dx} f \big|_{x=a}` via central finite difference.
421
+ * - Limits — `\lim_{x \to a} f` (including `a = \pm\infty`) via a two-sided numeric approach.
422
+ *
423
+ * Numeric results are rounded with `math.format(..., { precision: 12 })` and labelled
424
+ * `Result (numeric):` to flag that they are approximations. Constructs that cannot be evaluated
425
+ * numerically (indefinite integrals, derivatives without a point, infinite integration bounds,
426
+ * singular integrands, divergent limits) return a specific, guiding error string.
109
427
  *
110
428
  * Parse and evaluation errors are returned as error strings rather than thrown.
111
429
  */
112
430
  var evaluateKatexTool = new Tool({
113
431
  name: "evaluate_katex",
114
- description: "Evaluate a KaTeX/LaTeX math expression and return the numeric result.",
115
- inputSchema: validator.object({ katex: validator.string().required().description("LaTeX expression, e.g. \"\\frac{1}{2} + \\sqrt{9}\"") }),
432
+ description: "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).",
433
+ inputSchema: validator.object({ katex: validator.string().required().description("LaTeX expression, e.g. \"\\frac{1}{2} + \\sqrt{9}\" or \"\\int_{0}^{1} x^2 dx\"") }),
116
434
  handler: async (args) => {
117
435
  const { katex } = args;
118
436
  const lengthError = validateExpression(katex);
119
437
  if (lengthError) return lengthError;
120
438
  try {
121
- const mathjsExpr = latexToMathjs(katex);
122
- const translatedLengthError = validateExpression(mathjsExpr);
123
- if (translatedLengthError) return translatedLengthError;
124
- return `Converted: ${mathjsExpr}\nResult: ${math.evaluate(mathjsExpr)}`;
439
+ const calculus = tryCalculus(katex);
440
+ if (calculus !== null) return calculus;
441
+ return `Result: ${evaluateLatex(katex)}`;
125
442
  } catch (err) {
126
443
  return `Error: ${isError(err) ? err.message : String(err)}`;
127
444
  }
@@ -1 +1 @@
1
- {"version":3,"file":"math.mjs","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 { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\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 * Convert common LaTeX/KaTeX notation to a mathjs-evaluable expression.\n */\nfunction latexToMathjs(latex: string): string {\n let expr = latex.trim()\n\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n for (let i = 0; i < 10; 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(\n /\\\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|exp|abs|det)/g,\n '$1'\n )\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/**\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 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 into mathjs syntax, evaluates it, and returns the result.\n *\n * @remarks\n * Translates common LaTeX constructs (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek\n * macros like `\\pi`, `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) into their\n * mathjs equivalents before evaluation. Both the source and the translated mathjs expression\n * are subject to the 1000-character length cap.\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: 'Evaluate a KaTeX/LaTeX math expression and return the numeric result.',\n inputSchema: validator.object({\n katex: validator\n .string()\n .required()\n .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\"'),\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 const mathjsExpr = latexToMathjs(katex)\n\n const translatedLengthError = validateExpression(mathjsExpr)\n if (translatedLengthError) return translatedLengthError\n\n const result = math.evaluate!(mathjsExpr)\n return `Converted: ${mathjsExpr}\\nResult: ${result}`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAM,OAAO,OAAO,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;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QAAQ,QAAQ,GAAG,EAAE,KAAK;CAEtC,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,IAAa,gBAAgB,IAAI,KAAK;CACpC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO,EAC5B,YAAY,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0CAAwC,EAChG,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,eAAe;EAEvB,MAAM,cAAc,mBAAmB,UAAU;EACjD,IAAI,aAAa,OAAO;EAExB,IAAI;GACF,MAAM,SAAS,KAAK,SAAU,UAAU;GAGxC,OAAO,WAAW,OAAO,YAFZ,KAAK,MAAO,UACX,EAAK,MACkB,EAAM,KAAK,OAAO;EACzD,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;;;;;AAaD,IAAa,oBAAoB,IAAI,KAAK;CACxC,MAAM;CACN,aAAa;CACb,aAAa,UAAU,OAAO,EAC5B,OAAO,UACJ,OAAO,EACP,SAAS,EACT,YAAY,qDAAmD,EACpE,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,UAAU;EAElB,MAAM,cAAc,mBAAmB,KAAK;EAC5C,IAAI,aAAa,OAAO;EAExB,IAAI;GACF,MAAM,aAAa,cAAc,KAAK;GAEtC,MAAM,wBAAwB,mBAAmB,UAAU;GAC3D,IAAI,uBAAuB,OAAO;GAGlC,OAAO,cAAc,WAAW,YADjB,KAAK,SAAU,UACc;EAC9C,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"math.mjs","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), or just strip subscript for single-arg\n expr = expr.replace(/log_\\{?(\\w+)\\}?\\(/g, (_, base) => {\n const baseLower = base.toLowerCase()\n if (baseLower === '10') return 'log10('\n if (baseLower === '2') return 'log2('\n if (baseLower === 'e') return 'ln('\n // Generic base: convert log_b(x) to ln(x)/ln(b) — evaluatex handles the\n // resulting expression fine.\n return `ln(/ln(${base})`\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 // 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 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,OAAO,OAAO,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,CAAC;C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