@nhtio/adk 1.20260607.2 → 1.20260609.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.
- package/CHANGELOG.md +185 -0
- package/batteries/embeddings/openai/adapter.cjs +1 -1
- package/batteries/embeddings/openai/adapter.mjs +1 -1
- package/batteries/embeddings/openai/exceptions.cjs +1 -1
- package/batteries/embeddings/openai/exceptions.mjs +1 -1
- package/batteries/embeddings/openai/types.d.ts +7 -0
- package/batteries/embeddings/webllm/adapter.cjs +1 -1
- package/batteries/embeddings/webllm/adapter.mjs +1 -1
- package/batteries/embeddings/webllm/exceptions.cjs +1 -1
- package/batteries/embeddings/webllm/exceptions.mjs +1 -1
- package/batteries/llm/chat_common/helpers.d.ts +165 -0
- package/batteries/llm/chat_common/types.d.ts +309 -0
- package/batteries/llm/index.d.ts +5 -0
- package/batteries/llm/ollama/adapter.cjs +736 -0
- package/batteries/llm/ollama/adapter.cjs.map +1 -0
- package/batteries/llm/ollama/adapter.d.ts +64 -0
- package/batteries/llm/ollama/adapter.mjs +734 -0
- package/batteries/llm/ollama/adapter.mjs.map +1 -0
- package/batteries/llm/ollama/exceptions.cjs +105 -0
- package/batteries/llm/ollama/exceptions.cjs.map +1 -0
- package/batteries/llm/ollama/exceptions.d.ts +112 -0
- package/batteries/llm/ollama/exceptions.mjs +96 -0
- package/batteries/llm/ollama/exceptions.mjs.map +1 -0
- package/batteries/llm/ollama/helpers.cjs +487 -0
- package/batteries/llm/ollama/helpers.cjs.map +1 -0
- package/batteries/llm/ollama/helpers.d.ts +158 -0
- package/batteries/llm/ollama/helpers.mjs +450 -0
- package/batteries/llm/ollama/helpers.mjs.map +1 -0
- package/batteries/llm/ollama/index.d.ts +29 -0
- package/batteries/llm/ollama/types.cjs +2 -0
- package/batteries/llm/ollama/types.d.ts +334 -0
- package/batteries/llm/ollama/types.mjs +0 -0
- package/batteries/llm/ollama/validation.cjs +130 -0
- package/batteries/llm/ollama/validation.cjs.map +1 -0
- package/batteries/llm/ollama/validation.d.ts +31 -0
- package/batteries/llm/ollama/validation.mjs +127 -0
- package/batteries/llm/ollama/validation.mjs.map +1 -0
- package/batteries/llm/ollama.cjs +54 -0
- package/batteries/llm/ollama.mjs +6 -0
- package/batteries/llm/openai_chat_completions/adapter.cjs +36 -19
- package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/adapter.mjs +23 -6
- package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/openai_chat_completions/exceptions.mjs +1 -1
- package/batteries/llm/openai_chat_completions/helpers.cjs +80 -320
- package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/helpers.d.ts +68 -144
- package/batteries/llm/openai_chat_completions/helpers.mjs +40 -280
- package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/types.d.ts +273 -181
- package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions.cjs +29 -28
- package/batteries/llm/openai_chat_completions.mjs +2 -1
- package/batteries/llm/webllm_chat_completions/adapter.cjs +38 -19
- package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.d.ts +18 -0
- package/batteries/llm/webllm_chat_completions/adapter.mjs +25 -6
- package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/webllm_chat_completions/exceptions.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/helpers.cjs +29 -28
- package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -1
- package/batteries/llm/webllm_chat_completions/types.d.ts +21 -0
- package/batteries/llm/webllm_chat_completions/validation.cjs +13 -1
- package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/validation.d.ts +12 -0
- package/batteries/llm/webllm_chat_completions/validation.mjs +13 -1
- package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions.cjs +29 -28
- package/batteries/llm/webllm_chat_completions.mjs +2 -1
- package/batteries/llm.cjs +44 -28
- package/batteries/llm.mjs +9 -4
- package/batteries/storage/flydrive.cjs +1 -1
- package/batteries/storage/flydrive.mjs +1 -1
- package/batteries/storage/in_memory/index.d.ts +1 -1
- package/batteries/storage/in_memory.cjs +2 -2
- package/batteries/storage/in_memory.cjs.map +1 -1
- package/batteries/storage/in_memory.mjs +2 -2
- package/batteries/storage/in_memory.mjs.map +1 -1
- package/batteries/storage/opfs/index.d.ts +19 -0
- package/batteries/storage/opfs.cjs +1 -1
- package/batteries/storage/opfs.cjs.map +1 -1
- package/batteries/storage/opfs.mjs +1 -1
- package/batteries/storage/opfs.mjs.map +1 -1
- package/batteries/tools/color.cjs +3 -2
- package/batteries/tools/color.cjs.map +1 -1
- package/batteries/tools/color.mjs +3 -2
- package/batteries/tools/color.mjs.map +1 -1
- package/batteries/tools/comparison.cjs +4 -3
- package/batteries/tools/comparison.cjs.map +1 -1
- package/batteries/tools/comparison.mjs +4 -3
- package/batteries/tools/comparison.mjs.map +1 -1
- package/batteries/tools/data_structure.cjs +30 -10
- package/batteries/tools/data_structure.cjs.map +1 -1
- package/batteries/tools/data_structure.mjs +30 -10
- package/batteries/tools/data_structure.mjs.map +1 -1
- package/batteries/tools/datetime_extended.cjs +5 -10
- package/batteries/tools/datetime_extended.cjs.map +1 -1
- package/batteries/tools/datetime_extended.mjs +5 -10
- package/batteries/tools/datetime_extended.mjs.map +1 -1
- package/batteries/tools/datetime_math.cjs +2 -2
- package/batteries/tools/datetime_math.mjs +2 -2
- package/batteries/tools/encoding.cjs +13 -4
- package/batteries/tools/encoding.cjs.map +1 -1
- package/batteries/tools/encoding.mjs +13 -4
- package/batteries/tools/encoding.mjs.map +1 -1
- package/batteries/tools/formatting.cjs +4 -4
- package/batteries/tools/formatting.cjs.map +1 -1
- package/batteries/tools/formatting.mjs +4 -4
- package/batteries/tools/formatting.mjs.map +1 -1
- package/batteries/tools/geo_basics.cjs +2 -2
- package/batteries/tools/geo_basics.mjs +2 -2
- package/batteries/tools/index.d.ts +1 -0
- package/batteries/tools/math.cjs +10 -8
- package/batteries/tools/math.cjs.map +1 -1
- package/batteries/tools/math.mjs +10 -8
- package/batteries/tools/math.mjs.map +1 -1
- package/batteries/tools/memory.cjs +5 -5
- package/batteries/tools/memory.mjs +5 -5
- package/batteries/tools/parsing.cjs +9 -5
- package/batteries/tools/parsing.cjs.map +1 -1
- package/batteries/tools/parsing.mjs +9 -5
- package/batteries/tools/parsing.mjs.map +1 -1
- package/batteries/tools/retrievables.cjs +4 -4
- package/batteries/tools/retrievables.mjs +4 -4
- package/batteries/tools/searxng/exceptions.d.ts +21 -0
- package/batteries/tools/searxng/index.d.ts +150 -0
- package/batteries/tools/searxng.cjs +5 -0
- package/batteries/tools/searxng.mjs +2 -0
- package/batteries/tools/standing_instructions.cjs +4 -4
- package/batteries/tools/standing_instructions.mjs +4 -4
- package/batteries/tools/statistics.cjs +54 -43
- package/batteries/tools/statistics.cjs.map +1 -1
- package/batteries/tools/statistics.mjs +54 -43
- package/batteries/tools/statistics.mjs.map +1 -1
- package/batteries/tools/string_processing.cjs +5 -5
- package/batteries/tools/string_processing.cjs.map +1 -1
- package/batteries/tools/string_processing.mjs +5 -5
- package/batteries/tools/string_processing.mjs.map +1 -1
- package/batteries/tools/structured_data.cjs +8 -13
- package/batteries/tools/structured_data.cjs.map +1 -1
- package/batteries/tools/structured_data.mjs +8 -13
- package/batteries/tools/structured_data.mjs.map +1 -1
- package/batteries/tools/text_analysis.cjs +3 -3
- package/batteries/tools/text_analysis.mjs +3 -3
- package/batteries/tools/text_comparison.cjs +2 -2
- package/batteries/tools/text_comparison.mjs +2 -2
- package/batteries/tools/time.cjs +2 -2
- package/batteries/tools/time.mjs +2 -2
- package/batteries/tools/unit_conversion.cjs +10 -8
- package/batteries/tools/unit_conversion.cjs.map +1 -1
- package/batteries/tools/unit_conversion.mjs +10 -8
- package/batteries/tools/unit_conversion.mjs.map +1 -1
- package/batteries/tools.cjs +3 -0
- package/batteries/tools.mjs +2 -1
- package/batteries/vector/arangodb/index.d.ts +2 -0
- package/batteries/vector/arangodb.cjs +2 -1
- package/batteries/vector/arangodb.cjs.map +1 -1
- package/batteries/vector/arangodb.mjs +2 -1
- package/batteries/vector/arangodb.mjs.map +1 -1
- package/batteries/vector/builder.cjs +31 -0
- package/batteries/vector/builder.cjs.map +1 -1
- package/batteries/vector/builder.d.ts +58 -0
- package/batteries/vector/builder.mjs +31 -0
- package/batteries/vector/builder.mjs.map +1 -1
- package/batteries/vector/chroma/index.d.ts +4 -0
- package/batteries/vector/chroma.cjs +3 -0
- package/batteries/vector/chroma.cjs.map +1 -1
- package/batteries/vector/chroma.mjs +3 -0
- package/batteries/vector/chroma.mjs.map +1 -1
- package/batteries/vector/clickhouse/index.d.ts +2 -0
- package/batteries/vector/clickhouse.cjs +2 -1
- package/batteries/vector/clickhouse.cjs.map +1 -1
- package/batteries/vector/clickhouse.mjs +2 -1
- package/batteries/vector/clickhouse.mjs.map +1 -1
- package/batteries/vector/cloudflare/index.d.ts +2 -0
- package/batteries/vector/cloudflare.cjs +2 -1
- package/batteries/vector/cloudflare.cjs.map +1 -1
- package/batteries/vector/cloudflare.mjs +2 -1
- package/batteries/vector/cloudflare.mjs.map +1 -1
- package/batteries/vector/conformance/index.d.ts +22 -0
- package/batteries/vector/conformance.cjs +22 -0
- package/batteries/vector/conformance.cjs.map +1 -1
- package/batteries/vector/conformance.mjs +22 -0
- package/batteries/vector/conformance.mjs.map +1 -1
- package/batteries/vector/contract.cjs +22 -0
- package/batteries/vector/contract.cjs.map +1 -1
- package/batteries/vector/contract.d.ts +51 -0
- package/batteries/vector/contract.mjs +22 -0
- package/batteries/vector/contract.mjs.map +1 -1
- package/batteries/vector/couchbase/index.d.ts +2 -0
- package/batteries/vector/couchbase.cjs +2 -1
- package/batteries/vector/couchbase.cjs.map +1 -1
- package/batteries/vector/couchbase.mjs +2 -1
- package/batteries/vector/couchbase.mjs.map +1 -1
- package/batteries/vector/duckdb/index.d.ts +2 -0
- package/batteries/vector/duckdb.cjs +2 -1
- package/batteries/vector/duckdb.cjs.map +1 -1
- package/batteries/vector/duckdb.mjs +2 -1
- package/batteries/vector/duckdb.mjs.map +1 -1
- package/batteries/vector/elasticsearch/index.d.ts +2 -0
- package/batteries/vector/elasticsearch.cjs +2 -1
- package/batteries/vector/elasticsearch.cjs.map +1 -1
- package/batteries/vector/elasticsearch.mjs +2 -1
- package/batteries/vector/elasticsearch.mjs.map +1 -1
- package/batteries/vector/exceptions.cjs +1 -1
- package/batteries/vector/exceptions.mjs +1 -1
- package/batteries/vector/factory.cjs +6 -0
- package/batteries/vector/factory.cjs.map +1 -1
- package/batteries/vector/factory.d.ts +14 -0
- package/batteries/vector/factory.mjs +6 -0
- package/batteries/vector/factory.mjs.map +1 -1
- package/batteries/vector/filters.cjs +22 -1
- package/batteries/vector/filters.cjs.map +1 -1
- package/batteries/vector/filters.d.ts +38 -0
- package/batteries/vector/filters.mjs +22 -1
- package/batteries/vector/filters.mjs.map +1 -1
- package/batteries/vector/helpers.cjs +13 -0
- package/batteries/vector/helpers.cjs.map +1 -1
- package/batteries/vector/helpers.d.ts +14 -0
- package/batteries/vector/helpers.mjs +13 -0
- package/batteries/vector/helpers.mjs.map +1 -1
- package/batteries/vector/hnswlib/index.d.ts +2 -0
- package/batteries/vector/hnswlib.cjs +2 -1
- package/batteries/vector/hnswlib.cjs.map +1 -1
- package/batteries/vector/hnswlib.mjs +2 -1
- package/batteries/vector/hnswlib.mjs.map +1 -1
- package/batteries/vector/in_memory/index.d.ts +1 -0
- package/batteries/vector/in_memory.cjs +1 -0
- package/batteries/vector/in_memory.cjs.map +1 -1
- package/batteries/vector/in_memory.mjs +1 -0
- package/batteries/vector/in_memory.mjs.map +1 -1
- package/batteries/vector/lancedb/index.d.ts +2 -0
- package/batteries/vector/lancedb.cjs +2 -1
- package/batteries/vector/lancedb.cjs.map +1 -1
- package/batteries/vector/lancedb.mjs +2 -1
- package/batteries/vector/lancedb.mjs.map +1 -1
- package/batteries/vector/mariadb/index.d.ts +2 -0
- package/batteries/vector/mariadb.cjs +2 -1
- package/batteries/vector/mariadb.cjs.map +1 -1
- package/batteries/vector/mariadb.mjs +2 -1
- package/batteries/vector/mariadb.mjs.map +1 -1
- package/batteries/vector/meilisearch/index.d.ts +2 -0
- package/batteries/vector/meilisearch.cjs +2 -1
- package/batteries/vector/meilisearch.cjs.map +1 -1
- package/batteries/vector/meilisearch.mjs +2 -1
- package/batteries/vector/meilisearch.mjs.map +1 -1
- package/batteries/vector/migrate.cjs +18 -1
- package/batteries/vector/migrate.cjs.map +1 -1
- package/batteries/vector/migrate.d.ts +31 -0
- package/batteries/vector/migrate.mjs +18 -1
- package/batteries/vector/migrate.mjs.map +1 -1
- package/batteries/vector/milvus/index.d.ts +5 -0
- package/batteries/vector/milvus.cjs +4 -0
- package/batteries/vector/milvus.cjs.map +1 -1
- package/batteries/vector/milvus.mjs +4 -0
- package/batteries/vector/milvus.mjs.map +1 -1
- package/batteries/vector/mongodb/index.d.ts +2 -0
- package/batteries/vector/mongodb.cjs +2 -1
- package/batteries/vector/mongodb.cjs.map +1 -1
- package/batteries/vector/mongodb.mjs +2 -1
- package/batteries/vector/mongodb.mjs.map +1 -1
- package/batteries/vector/neo4j/index.d.ts +2 -0
- package/batteries/vector/neo4j.cjs +2 -1
- package/batteries/vector/neo4j.cjs.map +1 -1
- package/batteries/vector/neo4j.mjs +2 -1
- package/batteries/vector/neo4j.mjs.map +1 -1
- package/batteries/vector/opensearch/index.d.ts +2 -0
- package/batteries/vector/opensearch.cjs +2 -1
- package/batteries/vector/opensearch.cjs.map +1 -1
- package/batteries/vector/opensearch.mjs +2 -1
- package/batteries/vector/opensearch.mjs.map +1 -1
- package/batteries/vector/oracle23ai/index.d.ts +2 -0
- package/batteries/vector/oracle23ai.cjs +2 -1
- package/batteries/vector/oracle23ai.cjs.map +1 -1
- package/batteries/vector/oracle23ai.mjs +2 -1
- package/batteries/vector/oracle23ai.mjs.map +1 -1
- package/batteries/vector/orama/index.d.ts +1 -0
- package/batteries/vector/orama.cjs +1 -0
- package/batteries/vector/orama.cjs.map +1 -1
- package/batteries/vector/orama.mjs +1 -0
- package/batteries/vector/orama.mjs.map +1 -1
- package/batteries/vector/pgvector/index.d.ts +9 -2
- package/batteries/vector/pgvector.cjs +4 -0
- package/batteries/vector/pgvector.cjs.map +1 -1
- package/batteries/vector/pgvector.mjs +4 -0
- package/batteries/vector/pgvector.mjs.map +1 -1
- package/batteries/vector/pinecone/index.d.ts +5 -0
- package/batteries/vector/pinecone.cjs +3 -1
- package/batteries/vector/pinecone.cjs.map +1 -1
- package/batteries/vector/pinecone.mjs +3 -1
- package/batteries/vector/pinecone.mjs.map +1 -1
- package/batteries/vector/plan.d.ts +27 -0
- package/batteries/vector/qdrant/index.d.ts +5 -0
- package/batteries/vector/qdrant.cjs +4 -0
- package/batteries/vector/qdrant.cjs.map +1 -1
- package/batteries/vector/qdrant.mjs +4 -0
- package/batteries/vector/qdrant.mjs.map +1 -1
- package/batteries/vector/redis/index.d.ts +2 -0
- package/batteries/vector/redis.cjs +2 -1
- package/batteries/vector/redis.cjs.map +1 -1
- package/batteries/vector/redis.mjs +2 -1
- package/batteries/vector/redis.mjs.map +1 -1
- package/batteries/vector/retrievable.cjs +9 -1
- package/batteries/vector/retrievable.cjs.map +1 -1
- package/batteries/vector/retrievable.mjs +9 -1
- package/batteries/vector/retrievable.mjs.map +1 -1
- package/batteries/vector/retrievable_glue.d.ts +21 -0
- package/batteries/vector/s3vectors/index.d.ts +2 -0
- package/batteries/vector/s3vectors.cjs +2 -1
- package/batteries/vector/s3vectors.cjs.map +1 -1
- package/batteries/vector/s3vectors.mjs +2 -1
- package/batteries/vector/s3vectors.mjs.map +1 -1
- package/batteries/vector/schema.cjs +28 -0
- package/batteries/vector/schema.cjs.map +1 -1
- package/batteries/vector/schema.d.ts +39 -0
- package/batteries/vector/schema.mjs +28 -0
- package/batteries/vector/schema.mjs.map +1 -1
- package/batteries/vector/solr/index.d.ts +2 -0
- package/batteries/vector/solr.cjs +2 -1
- package/batteries/vector/solr.cjs.map +1 -1
- package/batteries/vector/solr.mjs +2 -1
- package/batteries/vector/solr.mjs.map +1 -1
- package/batteries/vector/sqlite_vec/index.d.ts +6 -3
- package/batteries/vector/sqlite_vec.cjs +2 -0
- package/batteries/vector/sqlite_vec.cjs.map +1 -1
- package/batteries/vector/sqlite_vec.mjs +2 -0
- package/batteries/vector/sqlite_vec.mjs.map +1 -1
- package/batteries/vector/surrealdb/index.d.ts +2 -0
- package/batteries/vector/surrealdb.cjs +2 -1
- package/batteries/vector/surrealdb.cjs.map +1 -1
- package/batteries/vector/surrealdb.mjs +2 -1
- package/batteries/vector/surrealdb.mjs.map +1 -1
- package/batteries/vector/types.d.ts +27 -0
- package/batteries/vector/typesense/index.d.ts +2 -0
- package/batteries/vector/typesense.cjs +2 -1
- package/batteries/vector/typesense.cjs.map +1 -1
- package/batteries/vector/typesense.mjs +2 -1
- package/batteries/vector/typesense.mjs.map +1 -1
- package/batteries/vector/validation.cjs +14 -0
- package/batteries/vector/validation.cjs.map +1 -1
- package/batteries/vector/validation.d.ts +14 -0
- package/batteries/vector/validation.mjs +14 -0
- package/batteries/vector/validation.mjs.map +1 -1
- package/batteries/vector/vector_store_constructor.cjs +1 -1
- package/batteries/vector/vector_store_constructor.cjs.map +1 -1
- package/batteries/vector/vector_store_constructor.d.ts +1 -1
- package/batteries/vector/vector_store_constructor.mjs +1 -1
- package/batteries/vector/vector_store_constructor.mjs.map +1 -1
- package/batteries/vector/vespa/index.d.ts +2 -0
- package/batteries/vector/vespa.cjs +2 -1
- package/batteries/vector/vespa.cjs.map +1 -1
- package/batteries/vector/vespa.mjs +2 -1
- package/batteries/vector/vespa.mjs.map +1 -1
- package/batteries/vector/weaviate/index.d.ts +2 -0
- package/batteries/vector/weaviate.cjs +2 -1
- package/batteries/vector/weaviate.cjs.map +1 -1
- package/batteries/vector/weaviate.mjs +2 -1
- package/batteries/vector/weaviate.mjs.map +1 -1
- package/batteries.cjs +46 -28
- package/batteries.mjs +10 -5
- package/{common-BT0nfCi9.mjs → common-DYDUi99O.mjs} +9 -9
- package/common-DYDUi99O.mjs.map +1 -0
- package/{common-Cj8TaQ9U.js → common-DZl3ADJs.js} +9 -9
- package/common-DZl3ADJs.js.map +1 -0
- package/common.cjs +7 -7
- package/common.d.ts +1 -1
- package/common.mjs +7 -7
- package/{dispatch_runner-DPcS7Y_M.mjs → dispatch_runner--ZhdDWRZ.mjs} +27 -5
- package/{dispatch_runner-DPcS7Y_M.mjs.map → dispatch_runner--ZhdDWRZ.mjs.map} +1 -1
- package/{dispatch_runner-BHBNupqp.js → dispatch_runner-nHDKkxye.js} +27 -5
- package/{dispatch_runner-BHBNupqp.js.map → dispatch_runner-nHDKkxye.js.map} +1 -1
- package/dispatch_runner.cjs +1 -1
- package/dispatch_runner.d.ts +1 -1
- package/dispatch_runner.mjs +1 -1
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs.map +1 -1
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.d.ts +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs.map +1 -1
- package/eslint/rules/no_model_in_tool_handler.cjs +1 -0
- package/eslint/rules/no_model_in_tool_handler.cjs.map +1 -1
- package/eslint/rules/no_model_in_tool_handler.d.ts +1 -0
- package/eslint/rules/no_model_in_tool_handler.mjs +1 -0
- package/eslint/rules/no_model_in_tool_handler.mjs.map +1 -1
- package/eslint/rules/require_validator_any_required.cjs +1 -0
- package/eslint/rules/require_validator_any_required.cjs.map +1 -1
- package/eslint/rules/require_validator_any_required.d.ts +1 -0
- package/eslint/rules/require_validator_any_required.mjs +1 -0
- package/eslint/rules/require_validator_any_required.mjs.map +1 -1
- package/eslint/rules/thought_payload_requires_replay_tag.cjs +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.cjs.map +1 -1
- package/eslint/rules/thought_payload_requires_replay_tag.d.ts +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.mjs +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.mjs.map +1 -1
- package/eslint/rules/token_encoding_requires_context_window.cjs +1 -0
- package/eslint/rules/token_encoding_requires_context_window.cjs.map +1 -1
- package/eslint/rules/token_encoding_requires_context_window.d.ts +1 -0
- package/eslint/rules/token_encoding_requires_context_window.mjs +1 -0
- package/eslint/rules/token_encoding_requires_context_window.mjs.map +1 -1
- package/eslint.cjs +1 -1
- package/eslint.mjs +1 -1
- package/{exceptions-BeWH2FwP.mjs → exceptions-BDhN0Xzr.mjs} +3 -2
- package/exceptions-BDhN0Xzr.mjs.map +1 -0
- package/{exceptions-CitH5wZI.js → exceptions-BRXrUKiW.js} +3 -2
- package/exceptions-BRXrUKiW.js.map +1 -0
- package/exceptions.cjs +2 -2
- package/exceptions.mjs +2 -2
- package/factories.cjs +1 -1
- package/factories.mjs +1 -1
- package/forge.cjs +4 -4
- package/forge.d.ts +1 -1
- package/forge.mjs +4 -4
- package/guards.cjs +9 -9
- package/guards.mjs +9 -9
- package/helpers-DSTFxTiC.js +497 -0
- package/helpers-DSTFxTiC.js.map +1 -0
- package/helpers-xhrQbMAG.mjs +306 -0
- package/helpers-xhrQbMAG.mjs.map +1 -0
- package/index.cjs +13 -13
- package/index.mjs +13 -13
- package/lib/classes/base_exception.d.ts +1 -0
- package/lib/classes/media.d.ts +10 -0
- package/lib/classes/retrievable.d.ts +1 -1
- package/lib/classes/spooled_json_artifact.d.ts +1 -1
- package/lib/classes/spooled_markdown_artifact.d.ts +1 -0
- package/lib/classes/tokenizable.d.ts +3 -0
- package/lib/classes/tool.d.ts +8 -0
- package/lib/classes/turn_gate.d.ts +6 -0
- package/lib/dispatch_runner.d.ts +4 -32
- package/lib/helpers/bignum.cjs +82 -0
- package/lib/helpers/bignum.cjs.map +1 -0
- package/lib/helpers/bignum.d.ts +52 -0
- package/lib/helpers/bignum.mjs +74 -0
- package/lib/helpers/bignum.mjs.map +1 -0
- package/lib/turn_runner.d.ts +1 -1
- package/lib/types/dispatch_runner.d.ts +83 -0
- package/lib/utils/exceptions.d.ts +1 -1
- package/lib/utils/retry.cjs.map +1 -1
- package/lib/utils/retry.d.ts +2 -0
- package/lib/utils/retry.mjs.map +1 -1
- package/mcp/adk-docs-corpus.json +1 -1
- package/package.json +264 -224
- package/{runtime-j92CNi5z.mjs → runtime-Bz5zA8wc.mjs} +2 -2
- package/{runtime-j92CNi5z.mjs.map → runtime-Bz5zA8wc.mjs.map} +1 -1
- package/{runtime-MFFcJrRv.js → runtime-DslE1aBw.js} +2 -2
- package/{runtime-MFFcJrRv.js.map → runtime-DslE1aBw.js.map} +1 -1
- package/searxng-Bkrwhwhw.js +269 -0
- package/searxng-Bkrwhwhw.js.map +1 -0
- package/searxng-CyA-nEu5.mjs +257 -0
- package/searxng-CyA-nEu5.mjs.map +1 -0
- package/skills/adk-assembly/SKILL.md +2 -2
- package/{spooled_artifact-CHoZgWwI.mjs → spooled_artifact-7eePq7JA.mjs} +5 -5
- package/{spooled_artifact-CHoZgWwI.mjs.map → spooled_artifact-7eePq7JA.mjs.map} +1 -1
- package/{spooled_artifact-BTq6Nzfy.js → spooled_artifact-DX8LLyUX.js} +5 -5
- package/{spooled_artifact-BTq6Nzfy.js.map → spooled_artifact-DX8LLyUX.js.map} +1 -1
- package/spooled_artifact.cjs +2 -2
- package/spooled_artifact.mjs +2 -2
- package/{spooled_markdown_artifact-CALSDxIx.js → spooled_markdown_artifact-ClX72lek.js} +4 -4
- package/spooled_markdown_artifact-ClX72lek.js.map +1 -0
- package/{spooled_markdown_artifact-Ci5UL7l4.mjs → spooled_markdown_artifact-wkrBF3oX.mjs} +4 -4
- package/spooled_markdown_artifact-wkrBF3oX.mjs.map +1 -0
- package/{thought-D34QQZZ9.mjs → thought-B_vxAiKU.mjs} +5 -5
- package/{thought-D34QQZZ9.mjs.map → thought-B_vxAiKU.mjs.map} +1 -1
- package/{thought-BbwhJ1wb.js → thought-DLwpF7MI.js} +5 -5
- package/{thought-BbwhJ1wb.js.map → thought-DLwpF7MI.js.map} +1 -1
- package/{tool-CVyZkFC7.js → tool-D5WGVIcI.js} +4 -4
- package/{tool-CVyZkFC7.js.map → tool-D5WGVIcI.js.map} +1 -1
- package/{tool-CMhaDRNd.mjs → tool-wMYMVl60.mjs} +4 -4
- package/{tool-CMhaDRNd.mjs.map → tool-wMYMVl60.mjs.map} +1 -1
- package/{tool_call-CV5qVNlb.mjs → tool_call-B4-_-vjG.mjs} +5 -5
- package/tool_call-B4-_-vjG.mjs.map +1 -0
- package/{tool_call-Db68hB7y.js → tool_call-DixVlW40.js} +5 -5
- package/tool_call-DixVlW40.js.map +1 -0
- package/{tool_registry-D1pSSlsd.mjs → tool_registry-791Vrjtf.mjs} +4 -3
- package/tool_registry-791Vrjtf.mjs.map +1 -0
- package/{tool_registry-DYUYqXvo.js → tool_registry-CKJPze3j.js} +4 -3
- package/tool_registry-CKJPze3j.js.map +1 -0
- package/{turn_runner-DqWHNP80.js → turn_runner-HXImLGIn.js} +7 -7
- package/turn_runner-HXImLGIn.js.map +1 -0
- package/{turn_runner-fg1Wc3dK.mjs → turn_runner-ZyYO-Kti.mjs} +7 -7
- package/turn_runner-ZyYO-Kti.mjs.map +1 -0
- package/turn_runner.cjs +1 -1
- package/turn_runner.mjs +1 -1
- package/types.d.ts +1 -1
- package/common-BT0nfCi9.mjs.map +0 -1
- package/common-Cj8TaQ9U.js.map +0 -1
- package/exceptions-BeWH2FwP.mjs.map +0 -1
- package/exceptions-CitH5wZI.js.map +0 -1
- package/spooled_markdown_artifact-CALSDxIx.js.map +0 -1
- package/spooled_markdown_artifact-Ci5UL7l4.mjs.map +0 -1
- package/tool_call-CV5qVNlb.mjs.map +0 -1
- package/tool_call-Db68hB7y.js.map +0 -1
- package/tool_registry-D1pSSlsd.mjs.map +0 -1
- package/tool_registry-DYUYqXvo.js.map +0 -1
- package/turn_runner-DqWHNP80.js.map +0 -1
- package/turn_runner-fg1Wc3dK.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encoding.cjs","names":[],"sources":["../../../src/batteries/tools/encoding/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for common text encodings and decoding operations.\n *\n * @module @nhtio/adk/batteries/tools/encoding\n *\n * @remarks\n * Pre-constructed bundled tools for the `encoding` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst utf8ToBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return globalThis.btoa(binary)\n}\n\nconst base64ToUtf8 = (b64: string): string => {\n const binary = globalThis.atob(b64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n}\n\n/**\n * Encode or decode text using common schemes: base64, url (percent-encoding), html_entities.\n *\n * @remarks\n * `base64` uses the portable `globalThis.btoa`/`atob` pair so the tool works in browsers, Node,\n * and edge runtimes. Encoding/decoding errors are returned as `Error:` strings rather than\n * thrown so the model can react in-line.\n */\nexport const encodeTextTool = new Tool({\n name: 'encode_text',\n description:\n 'Encode or decode text using common schemes: base64, url (percent-encoding), html_entities. Specify direction: encode or decode.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to encode or decode'),\n scheme: validator\n .string()\n .valid('base64', 'url', 'html_entities')\n .required()\n .description('Encoding scheme'),\n direction: validator\n .string()\n .valid('encode', 'decode')\n .default('encode')\n .description('Whether to encode or decode (default: encode)'),\n }),\n handler: async (args) => {\n const { text, scheme, direction } = args as {\n text: string\n scheme: string\n direction: string\n }\n\n try {\n if (scheme === 'base64') {\n if (direction === 'encode') return utf8ToBase64(text)\n return base64ToUtf8(text)\n }\n\n if (scheme === 'url') {\n if (direction === 'encode') return encodeURIComponent(text)\n return decodeURIComponent(text)\n }\n\n if (scheme === 'html_entities') {\n if (direction === 'encode') {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&#(\\d+);/g, (_, code: string) => String.fromCharCode(Number.parseInt(code, 10)))\n .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) =>\n String.fromCharCode(Number.parseInt(hex, 16))\n )\n }\n\n return `Error: Unknown scheme \"${scheme}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Escape or unescape special characters for a target context.\n *\n * @remarks\n * Supports `json_string`, `regex`, `csv_field`, `sql_like`, and `markdown` targets. Returns\n * an error string for unknown targets rather than throwing.\n */\nexport const textEscapeTool = new Tool({\n name: 'text_escape',\n description:\n 'Escape or unescape special characters for a target context: json_string, regex, csv_field, sql_like, markdown.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to escape or unescape'),\n target: validator\n .string()\n .valid('json_string', 'regex', 'csv_field', 'sql_like', 'markdown')\n .required()\n .description('Target context for escaping'),\n direction: validator\n .string()\n .valid('escape', 'unescape')\n .default('escape')\n .description('Whether to escape or unescape (default: escape)'),\n }),\n handler: async (args) => {\n const { text, target, direction } = args as {\n text: string\n target: string\n direction: string\n }\n\n try {\n if (target === 'json_string') {\n if (direction === 'escape') return JSON.stringify(text).slice(1, -1)\n return JSON.parse(`\"${text}\"`) as string\n }\n\n if (target === 'regex') {\n if (direction === 'escape') return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n }\n\n if (target === 'csv_field') {\n if (direction === 'escape') {\n if (/[,\"\\n\\r]/.test(text)) return `\"${text.replace(/\"/g, '\"\"')}\"`\n return text\n }\n if (text.startsWith('\"') && text.endsWith('\"')) {\n return text.slice(1, -1).replace(/\"\"/g, '\"')\n }\n return text\n }\n\n if (target === 'sql_like') {\n if (direction === 'escape') return text.replace(/[%_\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([%_\\\\])/g, '$1')\n }\n\n if (target === 'markdown') {\n const mdChars = /[\\\\`*_{}[\\]()#+\\-.!|]/g\n if (direction === 'escape') return text.replace(mdChars, '\\\\$&')\n return text.replace(/\\\\([\\\\`*_{}[\\]()#+\\-.!|])/g, '$1')\n }\n\n return `Error: Unknown target \"${target}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Normalize Unicode text or extract code points.\n *\n * @remarks\n * Operations: NFC, NFD, NFKC, NFKD Unicode normalization forms (via `String.prototype.normalize`),\n * `strip_accents` (NFD-decompose, remove combining diacritics, re-compose to NFC), or\n * `code_points` (one `U+HHHH (char)` per line).\n */\nexport const unicodeNormalizeTool = new Tool({\n name: 'unicode_normalize',\n description:\n 'Normalize Unicode text (NFC, NFD, NFKC, NFKD), strip accents/diacritics, or get Unicode code points for each character.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to process'),\n operation: validator\n .string()\n .valid('nfc', 'nfd', 'nfkc', 'nfkd', 'strip_accents', 'code_points')\n .required()\n .description(\n 'Operation: NFC/NFD/NFKC/NFKD normalization, strip_accents (remove diacritics), or code_points (list hex values)'\n ),\n }),\n handler: async (args) => {\n const { text, operation } = args as { text: string; operation: string }\n\n try {\n if (operation === 'strip_accents') {\n return text.normalize('NFD').replace(/[̀-ͯ]/g, '').normalize('NFC')\n }\n\n if (operation === 'code_points') {\n return [...text]\n .map((ch) => {\n const cp = ch.codePointAt(0)!\n const hex = cp.toString(16).toUpperCase().padStart(4, '0')\n return `U+${hex} (${ch})`\n })\n .join('\\n')\n }\n\n const formMap: Record<string, string> = { nfc: 'NFC', nfd: 'NFD', nfkc: 'NFKC', nfkd: 'NFKD' }\n const form = formMap[operation]\n if (!form) return `Error: Unknown operation \"${operation}\".`\n return text.normalize(form)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,IAAM,gBAAgB,SAAyB;CAC7C,MAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAC5D,OAAO,WAAW,KAAK,MAAM;AAC/B;AAEA,IAAM,gBAAgB,QAAwB;CAC5C,MAAM,SAAS,WAAW,KAAK,GAAG;CAClC,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;;;;;;;;;AAUA,IAAa,iBAAiB,IAAI,aAAA,KAAK;CACrC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,MAAM,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0BAA0B;EAC1E,QAAQ,kBAAA,UACL,OAAO,EACP,MAAM,UAAU,OAAO,eAAe,EACtC,SAAS,EACT,YAAY,iBAAiB;EAChC,WAAW,kBAAA,UACR,OAAO,EACP,MA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kBAAA,UAAU,OAAO;EAC5B,MAAM,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,iBAAiB;EACjE,WAAW,kBAAA,UACR,OAAO,EACP,MAAM,OAAO,OAAO,QAAQ,QAAQ,iBAAiB,aAAa,EAClE,SAAS,EACT,YACC,iHACF;CACJ,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,MAAM,cAAc;EAE5B,IAAI;GACF,IAAI,cAAc,iBAChB,OAAO,KAAK,UAAU,KAAK,EAAE,QAAQ,UAAU,EAAE,EAAE,UAAU,KAAK;GAGpE,IAAI,cAAc,eAChB,OAAO,CAAC,GAAG,IAAI,EACZ,KAAK,OAAO;IAGX,OAAO,KAFI,GAAG,YAAY,CACd,EAAG,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,GAAG,GAC1C,EAAI,IAAI,GAAG;GACzB,CAAC,EACA,KAAK,IAAI;GAId,MAAM,OAAO;IAD6B,KAAK;IAAO,KAAK;IAAO,MAAM;IAAQ,MAAM;GACzE,EAAQ;GACrB,IAAI,CAAC,MAAM,OAAO,6BAA6B,UAAU;GACzD,OAAO,KAAK,UAAU,IAAI;EAC5B,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"encoding.cjs","names":[],"sources":["../../../src/batteries/tools/encoding/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for common text encodings and decoding operations.\n *\n * @module @nhtio/adk/batteries/tools/encoding\n *\n * @remarks\n * Pre-constructed bundled tools for the `encoding` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst utf8ToBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return globalThis.btoa(binary)\n}\n\nconst base64ToUtf8 = (b64: string): string => {\n const binary = globalThis.atob(b64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n}\n\n/**\n * Convert a numeric HTML-entity code point to its string, handling astral characters correctly.\n * Returns the original entity text `fallback` for code points outside the valid Unicode range\n * (0 – 0x10FFFF) so `String.fromCodePoint` never throws a RangeError.\n */\nconst codePointToString = (cp: number, fallback: string): string => {\n if (!Number.isInteger(cp) || cp < 0 || cp > 0x10ffff) return fallback\n return String.fromCodePoint(cp)\n}\n\n/**\n * Encode or decode text using common schemes: base64, url (percent-encoding), html_entities.\n *\n * @remarks\n * `base64` uses the portable `globalThis.btoa`/`atob` pair so the tool works in browsers, Node,\n * and edge runtimes. Encoding/decoding errors are returned as `Error:` strings rather than\n * thrown so the model can react in-line.\n */\nexport const encodeTextTool = new Tool({\n name: 'encode_text',\n description:\n 'Encode or decode text using common schemes: base64, url (percent-encoding), html_entities. Specify direction: encode or decode.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to encode or decode'),\n scheme: validator\n .string()\n .valid('base64', 'url', 'html_entities')\n .required()\n .description('Encoding scheme'),\n direction: validator\n .string()\n .valid('encode', 'decode')\n .default('encode')\n .description('Whether to encode or decode (default: encode)'),\n }),\n handler: async (args) => {\n const { text, scheme, direction } = args as {\n text: string\n scheme: string\n direction: string\n }\n\n try {\n if (scheme === 'base64') {\n if (direction === 'encode') return utf8ToBase64(text)\n return base64ToUtf8(text)\n }\n\n if (scheme === 'url') {\n if (direction === 'encode') return encodeURIComponent(text)\n return decodeURIComponent(text)\n }\n\n if (scheme === 'html_entities') {\n if (direction === 'encode') {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n return (\n text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n // Use fromCodePoint, not fromCharCode: a numeric entity above U+FFFF (e.g. an emoji like\n // 🎉 = 🎉) is an astral code point. fromCharCode truncates to 16 bits and yields a\n // broken/empty character; fromCodePoint produces the correct surrogate pair. Out-of-range\n // code points (> U+10FFFF) are left as-is rather than throwing.\n .replace(/&#(\\d+);/g, (m, code: string) =>\n codePointToString(Number.parseInt(code, 10), m)\n )\n .replace(/&#x([0-9a-fA-F]+);/g, (m, hex: string) =>\n codePointToString(Number.parseInt(hex, 16), m)\n )\n )\n }\n\n return `Error: Unknown scheme \"${scheme}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Escape or unescape special characters for a target context.\n *\n * @remarks\n * Supports `json_string`, `regex`, `csv_field`, `sql_like`, and `markdown` targets. Returns\n * an error string for unknown targets rather than throwing.\n */\nexport const textEscapeTool = new Tool({\n name: 'text_escape',\n description:\n 'Escape or unescape special characters for a target context: json_string, regex, csv_field, sql_like, markdown.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to escape or unescape'),\n target: validator\n .string()\n .valid('json_string', 'regex', 'csv_field', 'sql_like', 'markdown')\n .required()\n .description('Target context for escaping'),\n direction: validator\n .string()\n .valid('escape', 'unescape')\n .default('escape')\n .description('Whether to escape or unescape (default: escape)'),\n }),\n handler: async (args) => {\n const { text, target, direction } = args as {\n text: string\n target: string\n direction: string\n }\n\n try {\n if (target === 'json_string') {\n if (direction === 'escape') return JSON.stringify(text).slice(1, -1)\n return JSON.parse(`\"${text}\"`) as string\n }\n\n if (target === 'regex') {\n if (direction === 'escape') return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n }\n\n if (target === 'csv_field') {\n if (direction === 'escape') {\n if (/[,\"\\n\\r]/.test(text)) return `\"${text.replace(/\"/g, '\"\"')}\"`\n return text\n }\n if (text.startsWith('\"') && text.endsWith('\"')) {\n return text.slice(1, -1).replace(/\"\"/g, '\"')\n }\n return text\n }\n\n if (target === 'sql_like') {\n if (direction === 'escape') return text.replace(/[%_\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([%_\\\\])/g, '$1')\n }\n\n if (target === 'markdown') {\n const mdChars = /[\\\\`*_{}[\\]()#+\\-.!|]/g\n if (direction === 'escape') return text.replace(mdChars, '\\\\$&')\n return text.replace(/\\\\([\\\\`*_{}[\\]()#+\\-.!|])/g, '$1')\n }\n\n return `Error: Unknown target \"${target}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Normalize Unicode text or extract code points.\n *\n * @remarks\n * Operations: NFC, NFD, NFKC, NFKD Unicode normalization forms (via `String.prototype.normalize`),\n * `strip_accents` (NFD-decompose, remove combining diacritics, re-compose to NFC), or\n * `code_points` (one `U+HHHH (char)` per line).\n */\nexport const unicodeNormalizeTool = new Tool({\n name: 'unicode_normalize',\n description:\n 'Normalize Unicode text (NFC, NFD, NFKC, NFKD), strip accents/diacritics, or get Unicode code points for each character.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to process'),\n operation: validator\n .string()\n .valid('nfc', 'nfd', 'nfkc', 'nfkd', 'strip_accents', 'code_points')\n .required()\n .description(\n 'Operation: NFC/NFD/NFKC/NFKD normalization, strip_accents (remove diacritics), or code_points (list hex values)'\n ),\n }),\n handler: async (args) => {\n const { text, operation } = args as { text: string; operation: string }\n\n try {\n if (operation === 'strip_accents') {\n return text.normalize('NFD').replace(/[̀-ͯ]/g, '').normalize('NFC')\n }\n\n if (operation === 'code_points') {\n return [...text]\n .map((ch) => {\n const cp = ch.codePointAt(0)!\n const hex = cp.toString(16).toUpperCase().padStart(4, '0')\n return `U+${hex} (${ch})`\n })\n .join('\\n')\n }\n\n const formMap: Record<string, string> = { nfc: 'NFC', nfd: 'NFD', nfkc: 'NFKC', nfkd: 'NFKD' }\n const form = formMap[operation]\n if (!form) return `Error: Unknown operation \"${operation}\".`\n return text.normalize(form)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,IAAM,gBAAgB,SAAyB;CAC7C,MAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAC5D,OAAO,WAAW,KAAK,MAAM;AAC/B;AAEA,IAAM,gBAAgB,QAAwB;CAC5C,MAAM,SAAS,WAAW,KAAK,GAAG;CAClC,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;;;;;;AAOA,IAAM,qBAAqB,IAAY,aAA6B;CAClE,IAAI,CAAC,OAAO,UAAU,EAAE,KAAK,KAAK,KAAK,KAAK,SAAU,OAAO;CAC7D,OAAO,OAAO,cAAc,EAAE;AAChC;;;;;;;;;AAUA,IAAa,iBAAiB,IAAI,aAAA,KAAK;CACrC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,MAAM,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0BAA0B;EAC1E,QAAQ,kBAAA,UACL,OAAO,EACP,MAAM,UAAU,OAAO,eAAe,EACtC,SAAS,EACT,YAAY,iBAAiB;EAChC,WAAW,kBAAA,UACR,OAAO,EACP,MAAM,UAAU,QAAQ,EACxB,QAAQ,QAAQ,EAChB,YAAY,+CAA+C;CAChE,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,MAAM,QAAQ,cAAc;EAMpC,IAAI;GACF,IAAI,WAAW,UAAU;IACvB,IAAI,cAAc,UAAU,OAAO,aAAa,IAAI;IACpD,OAAO,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AO,SAAS;EACvB,MAAM,EAAE,MAAM,cAAc;EAE5B,IAAI;GACF,IAAI,cAAc,iBAChB,OAAO,KAAK,UAAU,KAAK,EAAE,QAAQ,UAAU,EAAE,EAAE,UAAU,KAAK;GAGpE,IAAI,cAAc,eAChB,OAAO,CAAC,GAAG,IAAI,EACZ,KAAK,OAAO;IAGX,OAAO,KAFI,GAAG,YAAY,CACd,EAAG,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,GAAG,GAC1C,EAAI,IAAI,GAAG;GACzB,CAAC,EACA,KAAK,IAAI;GAId,MAAM,OAAO;IAD6B,KAAK;IAAO,KAAK;IAAO,MAAM;IAAQ,MAAM;GACzE,EAAQ;GACrB,IAAI,CAAC,MAAM,OAAO,6BAA6B,UAAU;GACzD,OAAO,KAAK,UAAU,IAAI;EAC5B,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { o as isError } from "../../tool_registry-
|
|
2
|
-
import { t as Tool } from "../../tool-
|
|
3
|
-
import "../../common-
|
|
1
|
+
import { o as isError } from "../../tool_registry-791Vrjtf.mjs";
|
|
2
|
+
import { t as Tool } from "../../tool-wMYMVl60.mjs";
|
|
3
|
+
import "../../common-DYDUi99O.mjs";
|
|
4
4
|
import "../../guards.mjs";
|
|
5
5
|
import { validator } from "@nhtio/validation";
|
|
6
6
|
//#region src/batteries/tools/encoding/index.ts
|
|
@@ -26,6 +26,15 @@ var base64ToUtf8 = (b64) => {
|
|
|
26
26
|
return new TextDecoder().decode(bytes);
|
|
27
27
|
};
|
|
28
28
|
/**
|
|
29
|
+
* Convert a numeric HTML-entity code point to its string, handling astral characters correctly.
|
|
30
|
+
* Returns the original entity text `fallback` for code points outside the valid Unicode range
|
|
31
|
+
* (0 – 0x10FFFF) so `String.fromCodePoint` never throws a RangeError.
|
|
32
|
+
*/
|
|
33
|
+
var codePointToString = (cp, fallback) => {
|
|
34
|
+
if (!Number.isInteger(cp) || cp < 0 || cp > 1114111) return fallback;
|
|
35
|
+
return String.fromCodePoint(cp);
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
29
38
|
* Encode or decode text using common schemes: base64, url (percent-encoding), html_entities.
|
|
30
39
|
*
|
|
31
40
|
* @remarks
|
|
@@ -54,7 +63,7 @@ var encodeTextTool = new Tool({
|
|
|
54
63
|
}
|
|
55
64
|
if (scheme === "html_entities") {
|
|
56
65
|
if (direction === "encode") return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
57
|
-
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'").replace(/&#(\d+);/g, (
|
|
66
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'").replace(/&#(\d+);/g, (m, code) => codePointToString(Number.parseInt(code, 10), m)).replace(/&#x([0-9a-fA-F]+);/g, (m, hex) => codePointToString(Number.parseInt(hex, 16), m));
|
|
58
67
|
}
|
|
59
68
|
return `Error: Unknown scheme "${scheme}".`;
|
|
60
69
|
} catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encoding.mjs","names":[],"sources":["../../../src/batteries/tools/encoding/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for common text encodings and decoding operations.\n *\n * @module @nhtio/adk/batteries/tools/encoding\n *\n * @remarks\n * Pre-constructed bundled tools for the `encoding` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst utf8ToBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return globalThis.btoa(binary)\n}\n\nconst base64ToUtf8 = (b64: string): string => {\n const binary = globalThis.atob(b64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n}\n\n/**\n * Encode or decode text using common schemes: base64, url (percent-encoding), html_entities.\n *\n * @remarks\n * `base64` uses the portable `globalThis.btoa`/`atob` pair so the tool works in browsers, Node,\n * and edge runtimes. Encoding/decoding errors are returned as `Error:` strings rather than\n * thrown so the model can react in-line.\n */\nexport const encodeTextTool = new Tool({\n name: 'encode_text',\n description:\n 'Encode or decode text using common schemes: base64, url (percent-encoding), html_entities. Specify direction: encode or decode.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to encode or decode'),\n scheme: validator\n .string()\n .valid('base64', 'url', 'html_entities')\n .required()\n .description('Encoding scheme'),\n direction: validator\n .string()\n .valid('encode', 'decode')\n .default('encode')\n .description('Whether to encode or decode (default: encode)'),\n }),\n handler: async (args) => {\n const { text, scheme, direction } = args as {\n text: string\n scheme: string\n direction: string\n }\n\n try {\n if (scheme === 'base64') {\n if (direction === 'encode') return utf8ToBase64(text)\n return base64ToUtf8(text)\n }\n\n if (scheme === 'url') {\n if (direction === 'encode') return encodeURIComponent(text)\n return decodeURIComponent(text)\n }\n\n if (scheme === 'html_entities') {\n if (direction === 'encode') {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&#(\\d+);/g, (_, code: string) => String.fromCharCode(Number.parseInt(code, 10)))\n .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) =>\n String.fromCharCode(Number.parseInt(hex, 16))\n )\n }\n\n return `Error: Unknown scheme \"${scheme}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Escape or unescape special characters for a target context.\n *\n * @remarks\n * Supports `json_string`, `regex`, `csv_field`, `sql_like`, and `markdown` targets. Returns\n * an error string for unknown targets rather than throwing.\n */\nexport const textEscapeTool = new Tool({\n name: 'text_escape',\n description:\n 'Escape or unescape special characters for a target context: json_string, regex, csv_field, sql_like, markdown.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to escape or unescape'),\n target: validator\n .string()\n .valid('json_string', 'regex', 'csv_field', 'sql_like', 'markdown')\n .required()\n .description('Target context for escaping'),\n direction: validator\n .string()\n .valid('escape', 'unescape')\n .default('escape')\n .description('Whether to escape or unescape (default: escape)'),\n }),\n handler: async (args) => {\n const { text, target, direction } = args as {\n text: string\n target: string\n direction: string\n }\n\n try {\n if (target === 'json_string') {\n if (direction === 'escape') return JSON.stringify(text).slice(1, -1)\n return JSON.parse(`\"${text}\"`) as string\n }\n\n if (target === 'regex') {\n if (direction === 'escape') return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n }\n\n if (target === 'csv_field') {\n if (direction === 'escape') {\n if (/[,\"\\n\\r]/.test(text)) return `\"${text.replace(/\"/g, '\"\"')}\"`\n return text\n }\n if (text.startsWith('\"') && text.endsWith('\"')) {\n return text.slice(1, -1).replace(/\"\"/g, '\"')\n }\n return text\n }\n\n if (target === 'sql_like') {\n if (direction === 'escape') return text.replace(/[%_\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([%_\\\\])/g, '$1')\n }\n\n if (target === 'markdown') {\n const mdChars = /[\\\\`*_{}[\\]()#+\\-.!|]/g\n if (direction === 'escape') return text.replace(mdChars, '\\\\$&')\n return text.replace(/\\\\([\\\\`*_{}[\\]()#+\\-.!|])/g, '$1')\n }\n\n return `Error: Unknown target \"${target}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Normalize Unicode text or extract code points.\n *\n * @remarks\n * Operations: NFC, NFD, NFKC, NFKD Unicode normalization forms (via `String.prototype.normalize`),\n * `strip_accents` (NFD-decompose, remove combining diacritics, re-compose to NFC), or\n * `code_points` (one `U+HHHH (char)` per line).\n */\nexport const unicodeNormalizeTool = new Tool({\n name: 'unicode_normalize',\n description:\n 'Normalize Unicode text (NFC, NFD, NFKC, NFKD), strip accents/diacritics, or get Unicode code points for each character.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to process'),\n operation: validator\n .string()\n .valid('nfc', 'nfd', 'nfkc', 'nfkd', 'strip_accents', 'code_points')\n .required()\n .description(\n 'Operation: NFC/NFD/NFKC/NFKD normalization, strip_accents (remove diacritics), or code_points (list hex values)'\n ),\n }),\n handler: async (args) => {\n const { text, operation } = args as { text: string; operation: string }\n\n try {\n if (operation === 'strip_accents') {\n return text.normalize('NFD').replace(/[̀-ͯ]/g, '').normalize('NFC')\n }\n\n if (operation === 'code_points') {\n return [...text]\n .map((ch) => {\n const cp = ch.codePointAt(0)!\n const hex = cp.toString(16).toUpperCase().padStart(4, '0')\n return `U+${hex} (${ch})`\n })\n .join('\\n')\n }\n\n const formMap: Record<string, string> = { nfc: 'NFC', nfd: 'NFD', nfkc: 'NFKC', nfkd: 'NFKD' }\n const form = formMap[operation]\n if (!form) return `Error: Unknown operation \"${operation}\".`\n return text.normalize(form)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAM,gBAAgB,SAAyB;CAC7C,MAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAC5D,OAAO,WAAW,KAAK,MAAM;AAC/B;AAEA,IAAM,gBAAgB,QAAwB;CAC5C,MAAM,SAAS,WAAW,KAAK,GAAG;CAClC,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IA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zB,MAAM,UAAU;IAChB,IAAI,cAAc,UAAU,OAAO,KAAK,QAAQ,SAAS,MAAM;IAC/D,OAAO,KAAK,QAAQ,8BAA8B,IAAI;GACxD;GAEA,OAAO,0BAA0B,OAAO;EAC1C,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;;AAUD,IAAa,uBAAuB,IAAI,KAAK;CAC3C,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO;EAC5B,MAAM,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,iBAAiB;EACjE,WAAW,UACR,OAAO,EACP,MAAM,OAAO,OAAO,QAAQ,QAAQ,iBAAiB,aAAa,EAClE,SAAS,EACT,YACC,iHACF;CACJ,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,MAAM,cAAc;EAE5B,IAAI;GACF,IAAI,cAAc,iBAChB,OAAO,KAAK,UAAU,KAAK,EAAE,QAAQ,UAAU,EAAE,EAAE,UAAU,KAAK;GAGpE,IAAI,cAAc,eAChB,OAAO,CAAC,GAAG,IAAI,EACZ,KAAK,OAAO;IAGX,OAAO,KAFI,GAAG,YAAY,CACd,EAAG,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,GAAG,GAC1C,EAAI,IAAI,GAAG;GACzB,CAAC,EACA,KAAK,IAAI;GAId,MAAM,OAAO;IAD6B,KAAK;IAAO,KAAK;IAAO,MAAM;IAAQ,MAAM;GACzE,EAAQ;GACrB,IAAI,CAAC,MAAM,OAAO,6BAA6B,UAAU;GACzD,OAAO,KAAK,UAAU,IAAI;EAC5B,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"encoding.mjs","names":[],"sources":["../../../src/batteries/tools/encoding/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for common text encodings and decoding operations.\n *\n * @module @nhtio/adk/batteries/tools/encoding\n *\n * @remarks\n * Pre-constructed bundled tools for the `encoding` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\nconst utf8ToBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return globalThis.btoa(binary)\n}\n\nconst base64ToUtf8 = (b64: string): string => {\n const binary = globalThis.atob(b64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return new TextDecoder().decode(bytes)\n}\n\n/**\n * Convert a numeric HTML-entity code point to its string, handling astral characters correctly.\n * Returns the original entity text `fallback` for code points outside the valid Unicode range\n * (0 – 0x10FFFF) so `String.fromCodePoint` never throws a RangeError.\n */\nconst codePointToString = (cp: number, fallback: string): string => {\n if (!Number.isInteger(cp) || cp < 0 || cp > 0x10ffff) return fallback\n return String.fromCodePoint(cp)\n}\n\n/**\n * Encode or decode text using common schemes: base64, url (percent-encoding), html_entities.\n *\n * @remarks\n * `base64` uses the portable `globalThis.btoa`/`atob` pair so the tool works in browsers, Node,\n * and edge runtimes. Encoding/decoding errors are returned as `Error:` strings rather than\n * thrown so the model can react in-line.\n */\nexport const encodeTextTool = new Tool({\n name: 'encode_text',\n description:\n 'Encode or decode text using common schemes: base64, url (percent-encoding), html_entities. Specify direction: encode or decode.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to encode or decode'),\n scheme: validator\n .string()\n .valid('base64', 'url', 'html_entities')\n .required()\n .description('Encoding scheme'),\n direction: validator\n .string()\n .valid('encode', 'decode')\n .default('encode')\n .description('Whether to encode or decode (default: encode)'),\n }),\n handler: async (args) => {\n const { text, scheme, direction } = args as {\n text: string\n scheme: string\n direction: string\n }\n\n try {\n if (scheme === 'base64') {\n if (direction === 'encode') return utf8ToBase64(text)\n return base64ToUtf8(text)\n }\n\n if (scheme === 'url') {\n if (direction === 'encode') return encodeURIComponent(text)\n return decodeURIComponent(text)\n }\n\n if (scheme === 'html_entities') {\n if (direction === 'encode') {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n return (\n text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n // Use fromCodePoint, not fromCharCode: a numeric entity above U+FFFF (e.g. an emoji like\n // 🎉 = 🎉) is an astral code point. fromCharCode truncates to 16 bits and yields a\n // broken/empty character; fromCodePoint produces the correct surrogate pair. Out-of-range\n // code points (> U+10FFFF) are left as-is rather than throwing.\n .replace(/&#(\\d+);/g, (m, code: string) =>\n codePointToString(Number.parseInt(code, 10), m)\n )\n .replace(/&#x([0-9a-fA-F]+);/g, (m, hex: string) =>\n codePointToString(Number.parseInt(hex, 16), m)\n )\n )\n }\n\n return `Error: Unknown scheme \"${scheme}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Escape or unescape special characters for a target context.\n *\n * @remarks\n * Supports `json_string`, `regex`, `csv_field`, `sql_like`, and `markdown` targets. Returns\n * an error string for unknown targets rather than throwing.\n */\nexport const textEscapeTool = new Tool({\n name: 'text_escape',\n description:\n 'Escape or unescape special characters for a target context: json_string, regex, csv_field, sql_like, markdown.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to escape or unescape'),\n target: validator\n .string()\n .valid('json_string', 'regex', 'csv_field', 'sql_like', 'markdown')\n .required()\n .description('Target context for escaping'),\n direction: validator\n .string()\n .valid('escape', 'unescape')\n .default('escape')\n .description('Whether to escape or unescape (default: escape)'),\n }),\n handler: async (args) => {\n const { text, target, direction } = args as {\n text: string\n target: string\n direction: string\n }\n\n try {\n if (target === 'json_string') {\n if (direction === 'escape') return JSON.stringify(text).slice(1, -1)\n return JSON.parse(`\"${text}\"`) as string\n }\n\n if (target === 'regex') {\n if (direction === 'escape') return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([.*+?^${}()|[\\]\\\\])/g, '$1')\n }\n\n if (target === 'csv_field') {\n if (direction === 'escape') {\n if (/[,\"\\n\\r]/.test(text)) return `\"${text.replace(/\"/g, '\"\"')}\"`\n return text\n }\n if (text.startsWith('\"') && text.endsWith('\"')) {\n return text.slice(1, -1).replace(/\"\"/g, '\"')\n }\n return text\n }\n\n if (target === 'sql_like') {\n if (direction === 'escape') return text.replace(/[%_\\\\]/g, '\\\\$&')\n return text.replace(/\\\\([%_\\\\])/g, '$1')\n }\n\n if (target === 'markdown') {\n const mdChars = /[\\\\`*_{}[\\]()#+\\-.!|]/g\n if (direction === 'escape') return text.replace(mdChars, '\\\\$&')\n return text.replace(/\\\\([\\\\`*_{}[\\]()#+\\-.!|])/g, '$1')\n }\n\n return `Error: Unknown target \"${target}\".`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Normalize Unicode text or extract code points.\n *\n * @remarks\n * Operations: NFC, NFD, NFKC, NFKD Unicode normalization forms (via `String.prototype.normalize`),\n * `strip_accents` (NFD-decompose, remove combining diacritics, re-compose to NFC), or\n * `code_points` (one `U+HHHH (char)` per line).\n */\nexport const unicodeNormalizeTool = new Tool({\n name: 'unicode_normalize',\n description:\n 'Normalize Unicode text (NFC, NFD, NFKC, NFKD), strip accents/diacritics, or get Unicode code points for each character.',\n inputSchema: validator.object({\n text: validator.string().required().description('Text to process'),\n operation: validator\n .string()\n .valid('nfc', 'nfd', 'nfkc', 'nfkd', 'strip_accents', 'code_points')\n .required()\n .description(\n 'Operation: NFC/NFD/NFKC/NFKD normalization, strip_accents (remove diacritics), or code_points (list hex values)'\n ),\n }),\n handler: async (args) => {\n const { text, operation } = args as { text: string; operation: string }\n\n try {\n if (operation === 'strip_accents') {\n return text.normalize('NFD').replace(/[̀-ͯ]/g, '').normalize('NFC')\n }\n\n if (operation === 'code_points') {\n return [...text]\n .map((ch) => {\n const cp = ch.codePointAt(0)!\n const hex = cp.toString(16).toUpperCase().padStart(4, '0')\n return `U+${hex} (${ch})`\n })\n .join('\\n')\n }\n\n const formMap: Record<string, string> = { nfc: 'NFC', nfd: 'NFD', nfkc: 'NFKC', nfkd: 'NFKD' }\n const form = formMap[operation]\n if (!form) return `Error: Unknown operation \"${operation}\".`\n return text.normalize(form)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAM,gBAAgB,SAAyB;CAC7C,MAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAC5D,OAAO,WAAW,KAAK,MAAM;AAC/B;AAEA,IAAM,gBAAgB,QAAwB;CAC5C,MAAM,SAAS,WAAW,KAAK,GAAG;CAClC,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;;;;;;AAOA,IAAM,qBAAqB,IAAY,aAA6B;CAClE,IAAI,CAAC,OAAO,UAAU,EAAE,KAAK,KAAK,KAAK,KAAK,SAAU,OAAO;CAC7D,OAAO,OAAO,cAAc,EAAE;AAChC;;;;;;;;;AAUA,IAAa,iBAAiB,IAAI,KAAK;CACrC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO;EAC5B,MAAM,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,0BAA0B;EAC1E,QAAQ,UACL,OAAO,EACP,MAAM,UAAU,OAAO,eAAe,EACtC,SAAS,EACT,YAAY,i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B,MAAM,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,iBAAiB;EACjE,WAAW,UACR,OAAO,EACP,MAAM,OAAO,OAAO,QAAQ,QAAQ,iBAAiB,aAAa,EAClE,SAAS,EACT,YACC,iHACF;CACJ,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EAAE,MAAM,cAAc;EAE5B,IAAI;GACF,IAAI,cAAc,iBAChB,OAAO,KAAK,UAAU,KAAK,EAAE,QAAQ,UAAU,EAAE,EAAE,UAAU,KAAK;GAGpE,IAAI,cAAc,eAChB,OAAO,CAAC,GAAG,IAAI,EACZ,KAAK,OAAO;IAGX,OAAO,KAFI,GAAG,YAAY,CACd,EAAG,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,GAAG,GAC1C,EAAI,IAAI,GAAG;GACzB,CAAC,EACA,KAAK,IAAI;GAId,MAAM,OAAO;IAD6B,KAAK;IAAO,KAAK;IAAO,MAAM;IAAQ,MAAM;GACzE,EAAQ;GACrB,IAAI,CAAC,MAAM,OAAO,6BAA6B,UAAU;GACzD,OAAO,KAAK,UAAU,IAAI;EAC5B,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
require("../../chunk-Ble4zEEl.js");
|
|
3
|
-
const require_tool_registry = require("../../tool_registry-
|
|
4
|
-
const require_tool = require("../../tool-
|
|
5
|
-
require("../../common-
|
|
3
|
+
const require_tool_registry = require("../../tool_registry-CKJPze3j.js");
|
|
4
|
+
const require_tool = require("../../tool-D5WGVIcI.js");
|
|
5
|
+
require("../../common-DZl3ADJs.js");
|
|
6
6
|
require("../../guards.cjs");
|
|
7
7
|
let _nhtio_validation = require("@nhtio/validation");
|
|
8
8
|
//#region src/batteries/tools/formatting/index.ts
|
|
@@ -94,7 +94,7 @@ var formatListTool = new require_tool.Tool({
|
|
|
94
94
|
}),
|
|
95
95
|
handler: async (args) => {
|
|
96
96
|
const { items, style, indent: rawIndent } = args;
|
|
97
|
-
const indent = Math.max(0, Math.floor(rawIndent));
|
|
97
|
+
const indent = Math.min(100, Math.max(0, Math.floor(rawIndent)));
|
|
98
98
|
const pad = " ".repeat(indent);
|
|
99
99
|
if (items.length === 0) return "";
|
|
100
100
|
switch (style) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatting.cjs","names":[],"sources":["../../../src/batteries/tools/formatting/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for locale-aware number, list, table, and text formatting.\n *\n * @module @nhtio/adk/batteries/tools/formatting\n *\n * @remarks\n * Pre-constructed bundled tools for the `formatting` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\n/**\n * Format a number using locale-aware styles.\n *\n * @remarks\n * Supported styles: `decimal`, `currency`, `percent`, `compact` (e.g. `1.2K`), `scientific`\n * (e.g. `1.2e+3`), and `ordinal` (`1st`, `2nd`, `3rd`). Uses `Intl.NumberFormat` and\n * `Intl.PluralRules` from the JS standard library. Returns an error string for non-finite values\n * or invalid currency-without-currency-code.\n */\nexport const formatNumberTool = new Tool({\n name: 'format_number',\n description:\n 'Format a number using locale-aware styles: decimal, currency, percent, compact (1.2K), scientific (1.2e3), or ordinal (1st/2nd/3rd). Supports locale and precision options.',\n inputSchema: validator.object({\n value: validator.number().required().description('The number to format'),\n style: validator\n .string()\n .valid('decimal', 'currency', 'percent', 'compact', 'scientific', 'ordinal')\n .default('decimal')\n .description('Formatting style (default: decimal)'),\n currency: validator\n .string()\n .optional()\n .description(\n 'ISO 4217 currency code — required when style is \"currency\" (e.g. \"USD\", \"EUR\")'\n ),\n locale: validator.string().default('en-US').description('BCP 47 locale tag (default: \"en-US\")'),\n min_decimals: validator\n .number()\n .optional()\n .description('Minimum fraction digits (default: style-dependent)'),\n max_decimals: validator\n .number()\n .optional()\n .description('Maximum fraction digits (default: style-dependent)'),\n }),\n handler: async (args) => {\n const {\n value,\n style,\n locale,\n currency,\n min_decimals: minDec,\n max_decimals: maxDec,\n } = args as {\n value: number\n style: string\n locale: string\n currency?: string\n min_decimals?: number\n max_decimals?: number\n }\n\n if (!Number.isFinite(value)) return `Error: Value must be a finite number (got ${value}).`\n\n try {\n if (style === 'ordinal') {\n const pr = new Intl.PluralRules(locale, { type: 'ordinal' })\n const suffixes: Record<string, string> = { one: 'st', two: 'nd', few: 'rd', other: 'th' }\n const rule = pr.select(value)\n const suffix = suffixes[rule] ?? 'th'\n return `${new Intl.NumberFormat(locale).format(value)}${suffix}`\n }\n\n if (style === 'scientific') {\n const exp = value === 0 ? 0 : Math.floor(Math.log10(Math.abs(value)))\n const mantissa = value / Math.pow(10, exp)\n const mFormatted = new Intl.NumberFormat(locale, {\n minimumFractionDigits: minDec ?? 2,\n maximumFractionDigits: maxDec ?? 6,\n }).format(mantissa)\n return `${mFormatted}e${exp >= 0 ? '+' : ''}${exp}`\n }\n\n const opts: Intl.NumberFormatOptions = {}\n\n if (style === 'currency') {\n if (!currency) return 'Error: \"currency\" parameter is required when style is \"currency\".'\n opts.style = 'currency'\n opts.currency = currency.toUpperCase()\n } else if (style === 'percent') {\n opts.style = 'percent'\n opts.minimumFractionDigits = minDec ?? 1\n opts.maximumFractionDigits = maxDec ?? 2\n } else if (style === 'compact') {\n opts.notation = 'compact'\n opts.compactDisplay = 'short'\n } else {\n opts.style = 'decimal'\n }\n\n if (minDec !== undefined && style !== 'percent') opts.minimumFractionDigits = minDec\n if (maxDec !== undefined && style !== 'percent') opts.maximumFractionDigits = maxDec\n\n return new Intl.NumberFormat(locale, opts).format(value)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Format an array of items as a list.\n *\n * @remarks\n * Supported styles: `bullet` (`• item`), `numbered` (`1. item`), `inline_and`\n * (`a, b, and c`), `inline_or` (`a, b, or c`), `newline` (one per line).\n */\nexport const formatListTool = new Tool({\n name: 'format_list',\n description:\n 'Format an array of items as a list. Styles: bullet (• item), numbered (1. item), inline_and (\"a, b, and c\"), inline_or (\"a, b, or c\"), newline (one per line).',\n inputSchema: validator.object({\n items: validator\n .array()\n .items(validator.string())\n .required()\n .description('Array of items to format'),\n style: validator\n .string()\n .valid('bullet', 'numbered', 'inline_and', 'inline_or', 'newline')\n .default('bullet')\n .description('List format style (default: bullet)'),\n indent: validator.number().default(0).description('Spaces to indent each item (default: 0)'),\n }),\n handler: async (args) => {\n const {\n items,\n style,\n indent: rawIndent,\n } = args as {\n items: string[]\n style: string\n indent: number\n }\n const indent = Math.max(0, Math.floor(rawIndent))\n const pad = ' '.repeat(indent)\n\n if (items.length === 0) return ''\n\n switch (style) {\n case 'bullet':\n return items.map((item) => `${pad}• ${item}`).join('\\n')\n case 'numbered':\n return items.map((item, i) => `${pad}${i + 1}. ${item}`).join('\\n')\n case 'newline':\n return items.map((item) => `${pad}${item}`).join('\\n')\n case 'inline_and':\n case 'inline_or': {\n const conj = style === 'inline_and' ? 'and' : 'or'\n if (items.length === 1) return items[0]\n if (items.length === 2) return `${items[0]} ${conj} ${items[1]}`\n const last = items[items.length - 1]\n const rest = items.slice(0, -1)\n return `${rest.join(', ')}, ${conj} ${last}`\n }\n default:\n return `Error: Unknown style \"${style}\".`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,mBAAmB,IAAI,aAAA,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,OAAO,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,sBAAsB;EACvE,OAAO,kBAAA,UACJ,OAAO,EACP,MAAM,WAAW,YAAY,WAAW,WAAW,cAAc,SAAS,EAC1E,QAAQ,SAAS,EACjB,YA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U;GACzC,OAAO,IAAI,UAAU,WAAW;IAC9B,KAAK,WAAW;IAChB,KAAK,iBAAiB;GACxB,OACE,KAAK,QAAQ;GAGf,IAAI,WAAW,KAAA,KAAa,UAAU,WAAW,KAAK,wBAAwB;GAC9E,IAAI,WAAW,KAAA,KAAa,UAAU,WAAW,KAAK,wBAAwB;GAE9E,OAAO,IAAI,KAAK,aAAa,QAAQ,IAAI,EAAE,OAAO,KAAK;EACzD,SAAS,KAAK;GACZ,OAAO,UAAU,sBAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;AASD,IAAa,iBAAiB,IAAI,aAAA,KAAK;CACrC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,OAAO,kBAAA,UACJ,MAAM,EACN,MAAM,kBAAA,UAAU,OAAO,CAAC,EACxB,SAAS,EACT,YAAY,0BAA0B;EACzC,OAAO,kBAAA,UACJ,OAAO,EACP,MAAM,UAAU,YAAY,cAAc,aAAa,SAAS,EAChE,QAAQ,QAAQ,EAChB,YAAY,qCAAqC;EACpD,QAAQ,kBAAA,UAAU,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,yCAAyC;CAC7F,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QAAQ,cACN;
|
|
1
|
+
{"version":3,"file":"formatting.cjs","names":[],"sources":["../../../src/batteries/tools/formatting/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for locale-aware number, list, table, and text formatting.\n *\n * @module @nhtio/adk/batteries/tools/formatting\n *\n * @remarks\n * Pre-constructed bundled tools for the `formatting` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\n/**\n * Format a number using locale-aware styles.\n *\n * @remarks\n * Supported styles: `decimal`, `currency`, `percent`, `compact` (e.g. `1.2K`), `scientific`\n * (e.g. `1.2e+3`), and `ordinal` (`1st`, `2nd`, `3rd`). Uses `Intl.NumberFormat` and\n * `Intl.PluralRules` from the JS standard library. Returns an error string for non-finite values\n * or invalid currency-without-currency-code.\n */\nexport const formatNumberTool = new Tool({\n name: 'format_number',\n description:\n 'Format a number using locale-aware styles: decimal, currency, percent, compact (1.2K), scientific (1.2e3), or ordinal (1st/2nd/3rd). Supports locale and precision options.',\n inputSchema: validator.object({\n value: validator.number().required().description('The number to format'),\n style: validator\n .string()\n .valid('decimal', 'currency', 'percent', 'compact', 'scientific', 'ordinal')\n .default('decimal')\n .description('Formatting style (default: decimal)'),\n currency: validator\n .string()\n .optional()\n .description(\n 'ISO 4217 currency code — required when style is \"currency\" (e.g. \"USD\", \"EUR\")'\n ),\n locale: validator.string().default('en-US').description('BCP 47 locale tag (default: \"en-US\")'),\n min_decimals: validator\n .number()\n .optional()\n .description('Minimum fraction digits (default: style-dependent)'),\n max_decimals: validator\n .number()\n .optional()\n .description('Maximum fraction digits (default: style-dependent)'),\n }),\n handler: async (args) => {\n const {\n value,\n style,\n locale,\n currency,\n min_decimals: minDec,\n max_decimals: maxDec,\n } = args as {\n value: number\n style: string\n locale: string\n currency?: string\n min_decimals?: number\n max_decimals?: number\n }\n\n if (!Number.isFinite(value)) return `Error: Value must be a finite number (got ${value}).`\n\n try {\n if (style === 'ordinal') {\n const pr = new Intl.PluralRules(locale, { type: 'ordinal' })\n const suffixes: Record<string, string> = { one: 'st', two: 'nd', few: 'rd', other: 'th' }\n const rule = pr.select(value)\n const suffix = suffixes[rule] ?? 'th'\n return `${new Intl.NumberFormat(locale).format(value)}${suffix}`\n }\n\n if (style === 'scientific') {\n const exp = value === 0 ? 0 : Math.floor(Math.log10(Math.abs(value)))\n const mantissa = value / Math.pow(10, exp)\n const mFormatted = new Intl.NumberFormat(locale, {\n minimumFractionDigits: minDec ?? 2,\n maximumFractionDigits: maxDec ?? 6,\n }).format(mantissa)\n return `${mFormatted}e${exp >= 0 ? '+' : ''}${exp}`\n }\n\n const opts: Intl.NumberFormatOptions = {}\n\n if (style === 'currency') {\n if (!currency) return 'Error: \"currency\" parameter is required when style is \"currency\".'\n opts.style = 'currency'\n opts.currency = currency.toUpperCase()\n } else if (style === 'percent') {\n opts.style = 'percent'\n opts.minimumFractionDigits = minDec ?? 1\n opts.maximumFractionDigits = maxDec ?? 2\n } else if (style === 'compact') {\n opts.notation = 'compact'\n opts.compactDisplay = 'short'\n } else {\n opts.style = 'decimal'\n }\n\n if (minDec !== undefined && style !== 'percent') opts.minimumFractionDigits = minDec\n if (maxDec !== undefined && style !== 'percent') opts.maximumFractionDigits = maxDec\n\n return new Intl.NumberFormat(locale, opts).format(value)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Format an array of items as a list.\n *\n * @remarks\n * Supported styles: `bullet` (`• item`), `numbered` (`1. item`), `inline_and`\n * (`a, b, and c`), `inline_or` (`a, b, or c`), `newline` (one per line).\n */\nexport const formatListTool = new Tool({\n name: 'format_list',\n description:\n 'Format an array of items as a list. Styles: bullet (• item), numbered (1. item), inline_and (\"a, b, and c\"), inline_or (\"a, b, or c\"), newline (one per line).',\n inputSchema: validator.object({\n items: validator\n .array()\n .items(validator.string())\n .required()\n .description('Array of items to format'),\n style: validator\n .string()\n .valid('bullet', 'numbered', 'inline_and', 'inline_or', 'newline')\n .default('bullet')\n .description('List format style (default: bullet)'),\n indent: validator.number().default(0).description('Spaces to indent each item (default: 0)'),\n }),\n handler: async (args) => {\n const {\n items,\n style,\n indent: rawIndent,\n } = args as {\n items: string[]\n style: string\n indent: number\n }\n // Clamp indent to a sane maximum: an unbounded value reaches `' '.repeat(indent)` and throws\n // RangeError (Invalid string length). 100 spaces is far past any real formatting need.\n const indent = Math.min(100, Math.max(0, Math.floor(rawIndent)))\n const pad = ' '.repeat(indent)\n\n if (items.length === 0) return ''\n\n switch (style) {\n case 'bullet':\n return items.map((item) => `${pad}• ${item}`).join('\\n')\n case 'numbered':\n return items.map((item, i) => `${pad}${i + 1}. ${item}`).join('\\n')\n case 'newline':\n return items.map((item) => `${pad}${item}`).join('\\n')\n case 'inline_and':\n case 'inline_or': {\n const conj = style === 'inline_and' ? 'and' : 'or'\n if (items.length === 1) return items[0]\n if (items.length === 2) return `${items[0]} ${conj} ${items[1]}`\n const last = items[items.length - 1]\n const rest = items.slice(0, -1)\n return `${rest.join(', ')}, ${conj} ${last}`\n }\n default:\n return `Error: Unknown style \"${style}\".`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,mBAAmB,IAAI,aAAA,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,kBAAA,UAAU,OAAO;EAC5B,OAAO,kBAAA,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,sBAAsB;EACvE,OAAO,kBAAA,UACJ,OAAO,EACP,MAAM,WAAW,YAAY,WAAW,WAAW,cAAc,SAAS,EAC1E,QAAQ,SAAS,EACjB,YAAY,qCAAqC;EACpD,UAAU,kBAAA,UACP,OAAO,EACP,SAAS,EACT,YACC,sFACF;EACF,QAAQ,kBAAA,UAAU,OAAO,EAAE,QAAQ,OAAO,EAAE,YAAY,wCAAsC;EAC9F,cAAc,kBAAA,UACX,OAAO,EACP,SAAS,EACT,YAAY,oDAAoD;EACnE,cAAc,kBAAA,UACX,OAAO,EACP,SAAS,EACT,YAAY,oDAAoD;CACrE,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QACA,UACA,cAAc,QACd,cAAc,WACZ;EASJ,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,6CAA6C,MAAM;EAEvF,IAAI;GACF,IAAI,UAAU,WAAW;IAIvB,MAAM,SAAS;KAF4B,KAAK;KAAM,KAAK;KAAM,KAAK;KAAM,OAAO;IAEpE,EADF,IAFE,KAAK,YAAY,QAAQ,EAAE,MAAM,UAAU,CAE7C,EAAG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,kBAAA,UACJ,OAAO,EACP,MAAM,UAAU,YAAY,cAAc,aAAa,SAAS,EAChE,QAAQ,QAAQ,EAChB,YAAY,qCAAqC;EACpD,QAAQ,kBAAA,UAAU,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,yCAAyC;CAC7F,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QAAQ,cACN;EAOJ,MAAM,SAAS,KAAK,IAAI,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,CAAC,CAAC;EAC/D,MAAM,MAAM,IAAI,OAAO,MAAM;EAE7B,IAAI,MAAM,WAAW,GAAG,OAAO;EAE/B,QAAQ,OAAR;GACE,KAAK,UACH,OAAO,MAAM,KAAK,SAAS,GAAG,IAAI,IAAI,MAAM,EAAE,KAAK,IAAI;GACzD,KAAK,YACH,OAAO,MAAM,KAAK,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,IAAI,MAAM,EAAE,KAAK,IAAI;GACpE,KAAK,WACH,OAAO,MAAM,KAAK,SAAS,GAAG,MAAM,MAAM,EAAE,KAAK,IAAI;GACvD,KAAK;GACL,KAAK,aAAa;IAChB,MAAM,OAAO,UAAU,eAAe,QAAQ;IAC9C,IAAI,MAAM,WAAW,GAAG,OAAO,MAAM;IACrC,IAAI,MAAM,WAAW,GAAG,OAAO,GAAG,MAAM,GAAG,GAAG,KAAK,GAAG,MAAM;IAC5D,MAAM,OAAO,MAAM,MAAM,SAAS;IAElC,OAAO,GADM,MAAM,MAAM,GAAG,EAClB,EAAK,KAAK,IAAI,EAAE,IAAI,KAAK,GAAG;GACxC;GACA,SACE,OAAO,yBAAyB,MAAM;EAC1C;CACF;AACF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { o as isError } from "../../tool_registry-
|
|
2
|
-
import { t as Tool } from "../../tool-
|
|
3
|
-
import "../../common-
|
|
1
|
+
import { o as isError } from "../../tool_registry-791Vrjtf.mjs";
|
|
2
|
+
import { t as Tool } from "../../tool-wMYMVl60.mjs";
|
|
3
|
+
import "../../common-DYDUi99O.mjs";
|
|
4
4
|
import "../../guards.mjs";
|
|
5
5
|
import { validator } from "@nhtio/validation";
|
|
6
6
|
//#region src/batteries/tools/formatting/index.ts
|
|
@@ -92,7 +92,7 @@ var formatListTool = new Tool({
|
|
|
92
92
|
}),
|
|
93
93
|
handler: async (args) => {
|
|
94
94
|
const { items, style, indent: rawIndent } = args;
|
|
95
|
-
const indent = Math.max(0, Math.floor(rawIndent));
|
|
95
|
+
const indent = Math.min(100, Math.max(0, Math.floor(rawIndent)));
|
|
96
96
|
const pad = " ".repeat(indent);
|
|
97
97
|
if (items.length === 0) return "";
|
|
98
98
|
switch (style) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatting.mjs","names":[],"sources":["../../../src/batteries/tools/formatting/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for locale-aware number, list, table, and text formatting.\n *\n * @module @nhtio/adk/batteries/tools/formatting\n *\n * @remarks\n * Pre-constructed bundled tools for the `formatting` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\n/**\n * Format a number using locale-aware styles.\n *\n * @remarks\n * Supported styles: `decimal`, `currency`, `percent`, `compact` (e.g. `1.2K`), `scientific`\n * (e.g. `1.2e+3`), and `ordinal` (`1st`, `2nd`, `3rd`). Uses `Intl.NumberFormat` and\n * `Intl.PluralRules` from the JS standard library. Returns an error string for non-finite values\n * or invalid currency-without-currency-code.\n */\nexport const formatNumberTool = new Tool({\n name: 'format_number',\n description:\n 'Format a number using locale-aware styles: decimal, currency, percent, compact (1.2K), scientific (1.2e3), or ordinal (1st/2nd/3rd). Supports locale and precision options.',\n inputSchema: validator.object({\n value: validator.number().required().description('The number to format'),\n style: validator\n .string()\n .valid('decimal', 'currency', 'percent', 'compact', 'scientific', 'ordinal')\n .default('decimal')\n .description('Formatting style (default: decimal)'),\n currency: validator\n .string()\n .optional()\n .description(\n 'ISO 4217 currency code — required when style is \"currency\" (e.g. \"USD\", \"EUR\")'\n ),\n locale: validator.string().default('en-US').description('BCP 47 locale tag (default: \"en-US\")'),\n min_decimals: validator\n .number()\n .optional()\n .description('Minimum fraction digits (default: style-dependent)'),\n max_decimals: validator\n .number()\n .optional()\n .description('Maximum fraction digits (default: style-dependent)'),\n }),\n handler: async (args) => {\n const {\n value,\n style,\n locale,\n currency,\n min_decimals: minDec,\n max_decimals: maxDec,\n } = args as {\n value: number\n style: string\n locale: string\n currency?: string\n min_decimals?: number\n max_decimals?: number\n }\n\n if (!Number.isFinite(value)) return `Error: Value must be a finite number (got ${value}).`\n\n try {\n if (style === 'ordinal') {\n const pr = new Intl.PluralRules(locale, { type: 'ordinal' })\n const suffixes: Record<string, string> = { one: 'st', two: 'nd', few: 'rd', other: 'th' }\n const rule = pr.select(value)\n const suffix = suffixes[rule] ?? 'th'\n return `${new Intl.NumberFormat(locale).format(value)}${suffix}`\n }\n\n if (style === 'scientific') {\n const exp = value === 0 ? 0 : Math.floor(Math.log10(Math.abs(value)))\n const mantissa = value / Math.pow(10, exp)\n const mFormatted = new Intl.NumberFormat(locale, {\n minimumFractionDigits: minDec ?? 2,\n maximumFractionDigits: maxDec ?? 6,\n }).format(mantissa)\n return `${mFormatted}e${exp >= 0 ? '+' : ''}${exp}`\n }\n\n const opts: Intl.NumberFormatOptions = {}\n\n if (style === 'currency') {\n if (!currency) return 'Error: \"currency\" parameter is required when style is \"currency\".'\n opts.style = 'currency'\n opts.currency = currency.toUpperCase()\n } else if (style === 'percent') {\n opts.style = 'percent'\n opts.minimumFractionDigits = minDec ?? 1\n opts.maximumFractionDigits = maxDec ?? 2\n } else if (style === 'compact') {\n opts.notation = 'compact'\n opts.compactDisplay = 'short'\n } else {\n opts.style = 'decimal'\n }\n\n if (minDec !== undefined && style !== 'percent') opts.minimumFractionDigits = minDec\n if (maxDec !== undefined && style !== 'percent') opts.maximumFractionDigits = maxDec\n\n return new Intl.NumberFormat(locale, opts).format(value)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Format an array of items as a list.\n *\n * @remarks\n * Supported styles: `bullet` (`• item`), `numbered` (`1. item`), `inline_and`\n * (`a, b, and c`), `inline_or` (`a, b, or c`), `newline` (one per line).\n */\nexport const formatListTool = new Tool({\n name: 'format_list',\n description:\n 'Format an array of items as a list. Styles: bullet (• item), numbered (1. item), inline_and (\"a, b, and c\"), inline_or (\"a, b, or c\"), newline (one per line).',\n inputSchema: validator.object({\n items: validator\n .array()\n .items(validator.string())\n .required()\n .description('Array of items to format'),\n style: validator\n .string()\n .valid('bullet', 'numbered', 'inline_and', 'inline_or', 'newline')\n .default('bullet')\n .description('List format style (default: bullet)'),\n indent: validator.number().default(0).description('Spaces to indent each item (default: 0)'),\n }),\n handler: async (args) => {\n const {\n items,\n style,\n indent: rawIndent,\n } = args as {\n items: string[]\n style: string\n indent: number\n }\n const indent = Math.max(0, Math.floor(rawIndent))\n const pad = ' '.repeat(indent)\n\n if (items.length === 0) return ''\n\n switch (style) {\n case 'bullet':\n return items.map((item) => `${pad}• ${item}`).join('\\n')\n case 'numbered':\n return items.map((item, i) => `${pad}${i + 1}. ${item}`).join('\\n')\n case 'newline':\n return items.map((item) => `${pad}${item}`).join('\\n')\n case 'inline_and':\n case 'inline_or': {\n const conj = style === 'inline_and' ? 'and' : 'or'\n if (items.length === 1) return items[0]\n if (items.length === 2) return `${items[0]} ${conj} ${items[1]}`\n const last = items[items.length - 1]\n const rest = items.slice(0, -1)\n return `${rest.join(', ')}, ${conj} ${last}`\n }\n default:\n return `Error: Unknown style \"${style}\".`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,mBAAmB,IAAI,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO;EAC5B,OAAO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AAW,SAAS,YAAY;GACvC,OAAO,IAAI,UAAU,WAAW;IAC9B,KAAK,QAAQ;IACb,KAAK,wBAAwB,UAAU;IACvC,KAAK,wBAAwB,UAAU;GACzC,OAAO,IAAI,UAAU,WAAW;IAC9B,KAAK,WAAW;IAChB,KAAK,iBAAiB;GACxB,OACE,KAAK,QAAQ;GAGf,IAAI,WAAW,KAAA,KAAa,UAAU,WAAW,KAAK,wBAAwB;GAC9E,IAAI,WAAW,KAAA,KAAa,UAAU,WAAW,KAAK,wBAAwB;GAE9E,OAAO,IAAI,KAAK,aAAa,QAAQ,IAAI,EAAE,OAAO,KAAK;EACzD,SAAS,KAAK;GACZ,OAAO,UAAU,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG;EAC1D;CACF;AACF,CAAC;;;;;;;;AASD,IAAa,iBAAiB,IAAI,KAAK;CACrC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO;EAC5B,OAAO,UACJ,MAAM,EACN,MAAM,UAAU,OAAO,CAAC,EACxB,SAAS,EACT,YAAY,0BAA0B;EACzC,OAAO,UACJ,OAAO,EACP,MAAM,UAAU,YAAY,cAAc,aAAa,SAAS,EAChE,QAAQ,QAAQ,EAChB,YAAY,qCAAqC;EACpD,QAAQ,UAAU,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,yCAAyC;CAC7F,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QAAQ,cACN;
|
|
1
|
+
{"version":3,"file":"formatting.mjs","names":[],"sources":["../../../src/batteries/tools/formatting/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for locale-aware number, list, table, and text formatting.\n *\n * @module @nhtio/adk/batteries/tools/formatting\n *\n * @remarks\n * Pre-constructed bundled tools for the `formatting` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { Tool } from '@nhtio/adk/common'\nimport { isError } from '@nhtio/adk/guards'\nimport { validator } from '@nhtio/validation'\n\n/**\n * Format a number using locale-aware styles.\n *\n * @remarks\n * Supported styles: `decimal`, `currency`, `percent`, `compact` (e.g. `1.2K`), `scientific`\n * (e.g. `1.2e+3`), and `ordinal` (`1st`, `2nd`, `3rd`). Uses `Intl.NumberFormat` and\n * `Intl.PluralRules` from the JS standard library. Returns an error string for non-finite values\n * or invalid currency-without-currency-code.\n */\nexport const formatNumberTool = new Tool({\n name: 'format_number',\n description:\n 'Format a number using locale-aware styles: decimal, currency, percent, compact (1.2K), scientific (1.2e3), or ordinal (1st/2nd/3rd). Supports locale and precision options.',\n inputSchema: validator.object({\n value: validator.number().required().description('The number to format'),\n style: validator\n .string()\n .valid('decimal', 'currency', 'percent', 'compact', 'scientific', 'ordinal')\n .default('decimal')\n .description('Formatting style (default: decimal)'),\n currency: validator\n .string()\n .optional()\n .description(\n 'ISO 4217 currency code — required when style is \"currency\" (e.g. \"USD\", \"EUR\")'\n ),\n locale: validator.string().default('en-US').description('BCP 47 locale tag (default: \"en-US\")'),\n min_decimals: validator\n .number()\n .optional()\n .description('Minimum fraction digits (default: style-dependent)'),\n max_decimals: validator\n .number()\n .optional()\n .description('Maximum fraction digits (default: style-dependent)'),\n }),\n handler: async (args) => {\n const {\n value,\n style,\n locale,\n currency,\n min_decimals: minDec,\n max_decimals: maxDec,\n } = args as {\n value: number\n style: string\n locale: string\n currency?: string\n min_decimals?: number\n max_decimals?: number\n }\n\n if (!Number.isFinite(value)) return `Error: Value must be a finite number (got ${value}).`\n\n try {\n if (style === 'ordinal') {\n const pr = new Intl.PluralRules(locale, { type: 'ordinal' })\n const suffixes: Record<string, string> = { one: 'st', two: 'nd', few: 'rd', other: 'th' }\n const rule = pr.select(value)\n const suffix = suffixes[rule] ?? 'th'\n return `${new Intl.NumberFormat(locale).format(value)}${suffix}`\n }\n\n if (style === 'scientific') {\n const exp = value === 0 ? 0 : Math.floor(Math.log10(Math.abs(value)))\n const mantissa = value / Math.pow(10, exp)\n const mFormatted = new Intl.NumberFormat(locale, {\n minimumFractionDigits: minDec ?? 2,\n maximumFractionDigits: maxDec ?? 6,\n }).format(mantissa)\n return `${mFormatted}e${exp >= 0 ? '+' : ''}${exp}`\n }\n\n const opts: Intl.NumberFormatOptions = {}\n\n if (style === 'currency') {\n if (!currency) return 'Error: \"currency\" parameter is required when style is \"currency\".'\n opts.style = 'currency'\n opts.currency = currency.toUpperCase()\n } else if (style === 'percent') {\n opts.style = 'percent'\n opts.minimumFractionDigits = minDec ?? 1\n opts.maximumFractionDigits = maxDec ?? 2\n } else if (style === 'compact') {\n opts.notation = 'compact'\n opts.compactDisplay = 'short'\n } else {\n opts.style = 'decimal'\n }\n\n if (minDec !== undefined && style !== 'percent') opts.minimumFractionDigits = minDec\n if (maxDec !== undefined && style !== 'percent') opts.maximumFractionDigits = maxDec\n\n return new Intl.NumberFormat(locale, opts).format(value)\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Format an array of items as a list.\n *\n * @remarks\n * Supported styles: `bullet` (`• item`), `numbered` (`1. item`), `inline_and`\n * (`a, b, and c`), `inline_or` (`a, b, or c`), `newline` (one per line).\n */\nexport const formatListTool = new Tool({\n name: 'format_list',\n description:\n 'Format an array of items as a list. Styles: bullet (• item), numbered (1. item), inline_and (\"a, b, and c\"), inline_or (\"a, b, or c\"), newline (one per line).',\n inputSchema: validator.object({\n items: validator\n .array()\n .items(validator.string())\n .required()\n .description('Array of items to format'),\n style: validator\n .string()\n .valid('bullet', 'numbered', 'inline_and', 'inline_or', 'newline')\n .default('bullet')\n .description('List format style (default: bullet)'),\n indent: validator.number().default(0).description('Spaces to indent each item (default: 0)'),\n }),\n handler: async (args) => {\n const {\n items,\n style,\n indent: rawIndent,\n } = args as {\n items: string[]\n style: string\n indent: number\n }\n // Clamp indent to a sane maximum: an unbounded value reaches `' '.repeat(indent)` and throws\n // RangeError (Invalid string length). 100 spaces is far past any real formatting need.\n const indent = Math.min(100, Math.max(0, Math.floor(rawIndent)))\n const pad = ' '.repeat(indent)\n\n if (items.length === 0) return ''\n\n switch (style) {\n case 'bullet':\n return items.map((item) => `${pad}• ${item}`).join('\\n')\n case 'numbered':\n return items.map((item, i) => `${pad}${i + 1}. ${item}`).join('\\n')\n case 'newline':\n return items.map((item) => `${pad}${item}`).join('\\n')\n case 'inline_and':\n case 'inline_or': {\n const conj = style === 'inline_and' ? 'and' : 'or'\n if (items.length === 1) return items[0]\n if (items.length === 2) return `${items[0]} ${conj} ${items[1]}`\n const last = items[items.length - 1]\n const rest = items.slice(0, -1)\n return `${rest.join(', ')}, ${conj} ${last}`\n }\n default:\n return `Error: Unknown style \"${style}\".`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,mBAAmB,IAAI,KAAK;CACvC,MAAM;CACN,aACE;CACF,aAAa,UAAU,OAAO;EAC5B,OAAO,UAAU,OAAO,EAAE,SAAS,EAAE,YAAY,sBAAsB;EACvE,OAAO,UACJ,OAAO,EACP,MAAM,WAAW,YAAY,WAAW,WAAW,cAAc,SAAS,EAC1E,QAAQ,SAAS,EACjB,YAAY,qCAAqC;EACpD,UAAU,UACP,OAAO,EACP,SAAS,EACT,YACC,sFACF;EACF,QAAQ,UAAU,OAAO,EAAE,QAAQ,OAAO,EAAE,YAAY,wCAAsC;EAC9F,cAAc,UACX,OAAO,EACP,SAAS,EACT,YAAY,oDAAoD;EACnE,cAAc,UACX,OAAO,EACP,SAAS,EACT,YAAY,oDAAoD;CACrE,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QACA,UACA,cAAc,QACd,cAAc,WACZ;EASJ,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,6CAA6C,MAAM;EAEvF,IAAI;GACF,IAAI,UAAU,WAAW;IAIvB,MAAM,SAAS;KAF4B,KAAK;KAAM,KAAK;KAAM,KAAK;KAAM,OAAO;IAEpE,EADF,IAFE,KAAK,YAAY,QAAQ,EAAE,MAAM,UAAU,CAE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AU,YAAY,cAAc,aAAa,SAAS,EAChE,QAAQ,QAAQ,EAChB,YAAY,qCAAqC;EACpD,QAAQ,UAAU,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,yCAAyC;CAC7F,CAAC;CACD,SAAS,OAAO,SAAS;EACvB,MAAM,EACJ,OACA,OACA,QAAQ,cACN;EAOJ,MAAM,SAAS,KAAK,IAAI,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,CAAC,CAAC;EAC/D,MAAM,MAAM,IAAI,OAAO,MAAM;EAE7B,IAAI,MAAM,WAAW,GAAG,OAAO;EAE/B,QAAQ,OAAR;GACE,KAAK,UACH,OAAO,MAAM,KAAK,SAAS,GAAG,IAAI,IAAI,MAAM,EAAE,KAAK,IAAI;GACzD,KAAK,YACH,OAAO,MAAM,KAAK,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,IAAI,MAAM,EAAE,KAAK,IAAI;GACpE,KAAK,WACH,OAAO,MAAM,KAAK,SAAS,GAAG,MAAM,MAAM,EAAE,KAAK,IAAI;GACvD,KAAK;GACL,KAAK,aAAa;IAChB,MAAM,OAAO,UAAU,eAAe,QAAQ;IAC9C,IAAI,MAAM,WAAW,GAAG,OAAO,MAAM;IACrC,IAAI,MAAM,WAAW,GAAG,OAAO,GAAG,MAAM,GAAG,GAAG,KAAK,GAAG,MAAM;IAC5D,MAAM,OAAO,MAAM,MAAM,SAAS;IAElC,OAAO,GADM,MAAM,MAAM,GAAG,EAClB,EAAK,KAAK,IAAI,EAAE,IAAI,KAAK,GAAG;GACxC;GACA,SACE,OAAO,yBAAyB,MAAM;EAC1C;CACF;AACF,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
require("../../chunk-Ble4zEEl.js");
|
|
3
|
-
const require_tool = require("../../tool-
|
|
4
|
-
require("../../common-
|
|
3
|
+
const require_tool = require("../../tool-D5WGVIcI.js");
|
|
4
|
+
require("../../common-DZl3ADJs.js");
|
|
5
5
|
let _nhtio_validation = require("@nhtio/validation");
|
|
6
6
|
//#region src/batteries/tools/geo_basics/index.ts
|
|
7
7
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Tool } from "../../tool-
|
|
2
|
-
import "../../common-
|
|
1
|
+
import { t as Tool } from "../../tool-wMYMVl60.mjs";
|
|
2
|
+
import "../../common-DYDUi99O.mjs";
|
|
3
3
|
import { validator } from "@nhtio/validation";
|
|
4
4
|
//#region src/batteries/tools/geo_basics/index.ts
|
|
5
5
|
/**
|
|
@@ -22,6 +22,7 @@ export * from "./math/index";
|
|
|
22
22
|
export * from "./memory/index";
|
|
23
23
|
export * from "./parsing/index";
|
|
24
24
|
export * from "./retrievables/index";
|
|
25
|
+
export * from "./searxng/index";
|
|
25
26
|
export * from "./standing_instructions/index";
|
|
26
27
|
export * from "./statistics/index";
|
|
27
28
|
export * from "./string_processing/index";
|
package/batteries/tools/math.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_chunk = require("../../chunk-Ble4zEEl.js");
|
|
3
|
-
const require_tool_registry = require("../../tool_registry-
|
|
4
|
-
const require_tool = require("../../tool-
|
|
5
|
-
require("../../common-
|
|
3
|
+
const require_tool_registry = require("../../tool_registry-CKJPze3j.js");
|
|
4
|
+
const require_tool = require("../../tool-D5WGVIcI.js");
|
|
5
|
+
require("../../common-DZl3ADJs.js");
|
|
6
6
|
require("../../guards.cjs");
|
|
7
7
|
let _nhtio_validation = require("@nhtio/validation");
|
|
8
8
|
let mathjs = require("mathjs");
|
|
@@ -83,12 +83,12 @@ function evaluateLatex(latex) {
|
|
|
83
83
|
expr = expr.replace(/\\arccos/g, "acos");
|
|
84
84
|
expr = expr.replace(/\\arctan/g, "atan");
|
|
85
85
|
expr = expr.replace(/\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, "$1");
|
|
86
|
-
expr = expr.replace(/log_\{?(\w+)\}?\(/g, (_, base) => {
|
|
86
|
+
expr = expr.replace(/log_\{?(\w+)\}?\(((?:[^()]|\([^()]*\))*)\)/g, (_, base, arg) => {
|
|
87
87
|
const baseLower = base.toLowerCase();
|
|
88
|
-
if (baseLower === "10") return
|
|
89
|
-
if (baseLower === "2") return
|
|
90
|
-
if (baseLower === "e") return
|
|
91
|
-
return `ln(/ln(${base})`;
|
|
88
|
+
if (baseLower === "10") return `log10(${arg})`;
|
|
89
|
+
if (baseLower === "2") return `log2(${arg})`;
|
|
90
|
+
if (baseLower === "e") return `ln(${arg})`;
|
|
91
|
+
return `(ln(${arg})/ln(${base}))`;
|
|
92
92
|
});
|
|
93
93
|
expr = expr.replace(/_\{[^}]*\}/g, "");
|
|
94
94
|
expr = expr.replace(/_\w/g, "");
|
|
@@ -108,6 +108,7 @@ function evaluateLatex(latex) {
|
|
|
108
108
|
expr = expr.replace(/\\quad/g, " ");
|
|
109
109
|
expr = expr.replace(/\\qquad/g, " ");
|
|
110
110
|
expr = expr.replace(/\\text\{([^{}]*)\}/g, "");
|
|
111
|
+
expr = expr.replace(/(\d(?:\.\d+)?)[eE]([+-]?\d+)/g, "($1*10^($2))");
|
|
111
112
|
expr = expr.replace(/(\d)([a-zA-Z(])/g, "$1*$2");
|
|
112
113
|
expr = expr.replace(/\)\s*\(/g, ")*(");
|
|
113
114
|
expr = expr.replace(/\s+/g, " ").trim();
|
|
@@ -402,6 +403,7 @@ var calculateTool = new require_tool.Tool({
|
|
|
402
403
|
if (lengthError) return lengthError;
|
|
403
404
|
try {
|
|
404
405
|
const result = math.evaluate(expression);
|
|
406
|
+
if (typeof result === "number" && !Number.isFinite(result)) return `Error: result is not finite (${result}) — the value overflows JavaScript's numeric range.`;
|
|
405
407
|
return `Result: ${result}\nKaTeX: $${math.parse(expression).toTex()} = ${result}$`;
|
|
406
408
|
} catch (err) {
|
|
407
409
|
return `Error: ${require_tool_registry.isError(err) ? err.message : String(err)}`;
|
|
@@ -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 { 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,KAAA;CACP,SAAS,KAAA;CACT,OAAO,KAAA;CACP,QAAQ,KAAA;CACR,IAAI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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
|
+
{"version":3,"file":"math.cjs","names":[],"sources":["../../../src/batteries/tools/math/index.ts"],"sourcesContent":["/**\n * Pre-constructed tools for safe arithmetic, expression evaluation, and numeric operations.\n *\n * @module @nhtio/adk/batteries/tools/math\n *\n * @remarks\n * Pre-constructed bundled tools for the `math` category. Import individually, the whole\n * category, or import every tool via `@nhtio/adk/batteries`.\n */\n\nimport { create, all } from 'mathjs'\nimport { Tool } from '@nhtio/adk/common'\nimport { validator } from '@nhtio/validation'\nimport { default as evaluatex } from 'evaluatex'\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\n\nconst math = create(all)\n\nconst BLOCKED_FUNCTIONS = [\n 'import',\n 'createUnit',\n 'simplify',\n 'derivative',\n 'compile',\n 'chain',\n 'reviver',\n 'replacer',\n]\n\nfor (const fn of BLOCKED_FUNCTIONS) {\n if (fn in math) {\n ;(math as any)[fn] = undefined\n }\n}\n\nconst MAX_EXPRESSION_LENGTH = 1000\n\nfunction validateExpression(expr: string): string | undefined {\n if (expr.length > MAX_EXPRESSION_LENGTH) {\n return `Expression too long (max ${MAX_EXPRESSION_LENGTH} characters).`\n }\n return undefined\n}\n\n/**\n * EvaluateX scope providing constants and function aliases that evaluatex does not ship\n * out-of-the-box, matching the capabilities that were previously provided by the mathjs\n * translation layer.\n */\nconst EVALUATEX_SCOPE: Record<string, unknown> = {\n // Mathematical constants\n pi: Math.PI,\n e: Math.E,\n infinity: Infinity,\n // Greek letters as named constants (matching LaTeX macro names)\n alpha: undefined,\n beta: undefined,\n gamma: undefined,\n delta: undefined,\n epsilon: undefined,\n theta: undefined,\n lambda: undefined,\n mu: undefined,\n sigma: undefined,\n tau: undefined,\n phi: undefined,\n omega: undefined,\n // Function aliases — evaluatex uses log for natural log; provide ln as alias,\n // plus common log bases and nthRoot for \\sqrt[n]{...}.\n ln: Math.log,\n log10: (x: number) => Math.log(x) / Math.LN10,\n log2: (x: number) => Math.log(x) / Math.LN2,\n nthRoot: (x: number, n: number) => Math.pow(x, 1 / n),\n // Determinant (identity for scalars — det([a,b;c,d]) is not supported in the scalar path)\n det: (x: number) => x,\n}\n\n/**\n * Translate a LaTeX/KaTeX expression to evaluatex-compatible syntax and evaluate it.\n *\n * The translation is a lightweight pass over the LaTeX source that handles common constructs\n * (frac, sqrt, trig, Greek macros, delimiters, etc.) and feeds the result to evaluatex with\n * a pre-built scope providing constants and function aliases. This replaces the previous\n * hand-rolled regex → mathjs pipeline.\n */\nfunction evaluateLatex(latex: string): number {\n let expr = latex.trim()\n\n // Strip display/inline math delimiters: $$...$$ or $...$\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n // Strip \\[ ... \\] or \\( ... \\) delimiters\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n // ---- LaTeX command translation ----\n\n // \\frac{a}{b} → (a)/(b) — iterates to handle nested fractions\n for (let i = 0; i < 20; i++) {\n const before = expr\n expr = expr.replace(/\\\\frac\\s*\\{([^}]*)\\}\\s*\\{([^}]*)\\}/g, '($1)/($2)')\n if (expr === before) break\n }\n\n // \\sqrt[n]{x} → nthRoot(x, n)\n expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^}]*)\\}/g, 'nthRoot($2, $1)')\n // \\sqrt{x} → sqrt(x)\n expr = expr.replace(/\\\\sqrt\\s*\\{([^}]*)\\}/g, 'sqrt($1)')\n\n // Inverse trig: \\arcsin → asin (evaluatex uses asin/acos/atan natively)\n expr = expr.replace(/\\\\arcsin/g, 'asin')\n expr = expr.replace(/\\\\arccos/g, 'acos')\n expr = expr.replace(/\\\\arctan/g, 'atan')\n\n // Strip backslash from known function macros: \\sin, \\cos, \\tan, \\cot, \\sec, \\csc,\n // \\sinh, \\cosh, \\tanh, \\ln, \\log, \\exp, \\abs, etc.\n expr = expr.replace(/\\\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, '$1')\n\n // Subscript-based log: \\log_2(x) → log2(x), \\log_10(x) → log10(x), \\log_e(x) → ln(x), and a\n // generic base \\log_b(arg) → (ln(arg)/ln(b)) via change of base. The argument is captured here\n // (single level of nested parens) so the change-of-base form is well-formed — previously the\n // argument was not captured and the output was the malformed `ln(/ln(b)`.\n expr = expr.replace(\n /log_\\{?(\\w+)\\}?\\(((?:[^()]|\\([^()]*\\))*)\\)/g,\n (_, base: string, arg: string) => {\n const baseLower = base.toLowerCase()\n if (baseLower === '10') return `log10(${arg})`\n if (baseLower === '2') return `log2(${arg})`\n if (baseLower === 'e') return `ln(${arg})`\n return `(ln(${arg})/ln(${base}))`\n }\n )\n // Strip any remaining subscripts (e.g. x_1, a_n)\n expr = expr.replace(/_\\{[^}]*\\}/g, '')\n expr = expr.replace(/_\\w/g, '')\n\n // Powers: ^{...} → ^(...)\n expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n\n // Greek letter macros\n expr = expr.replace(/\\\\pi/g, 'pi')\n expr = expr.replace(\n /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n '$1'\n )\n\n // Spacing and operators\n expr = expr.replace(/\\\\cdot/g, '*')\n expr = expr.replace(/\\\\times/g, '*')\n expr = expr.replace(/\\\\div/g, '/')\n expr = expr.replace(/\\\\infty/g, 'infinity')\n expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n expr = expr.replace(/\\\\sum/g, 'sum')\n expr = expr.replace(/\\\\prod/g, 'prod')\n expr = expr.replace(/\\\\,/g, ' ')\n expr = expr.replace(/\\\\;/g, ' ')\n expr = expr.replace(/\\\\quad/g, ' ')\n expr = expr.replace(/\\\\qquad/g, ' ')\n // Strip \\text{...} blocks entirely\n expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n\n // Scientific notation: evaluatex doesn't understand `2e3` natively (it reads `e3` as a symbol),\n // so rewrite a numeric literal's exponent into an explicit power: `2e3` → `(2*10^(3))`,\n // `1.5e-8` → `(1.5*10^(-8))`. Done BEFORE implicit-multiplication insertion.\n expr = expr.replace(/(\\d(?:\\.\\d+)?)[eE]([+-]?\\d+)/g, '($1*10^($2))')\n\n // Implicit multiplication: 2x, 3(x+1), etc.\n expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n\n // Collapse whitespace\n expr = expr.replace(/\\s+/g, ' ').trim()\n\n const fn = evaluatex(expr, EVALUATEX_SCOPE)\n const result = fn()\n if (typeof result !== 'number' || !Number.isFinite(result)) {\n throw new Error('Result is not finite')\n }\n return result\n}\n\n/**\n * Lightweight LaTeX-to-string translator for internal use by the numeric calculus path.\n *\n * This is the same translation pass as {@link evaluateLatex}, but returns the translated string\n * (compatible with mathjs syntax) rather than evaluating it. Used by the calculus handlers to\n * convert integrands, function bodies, and bound expressions before passing them to\n * `math.evaluate` for specific-point evaluation.\n */\nfunction translateLatex(latex: string): string {\n let expr = latex.trim()\n expr = expr.replace(/^\\$\\$?|\\$\\$?$/g, '')\n expr = expr.replace(/^\\\\[[(]|\\\\[\\])]$/g, '')\n\n for (let i = 0; i < 20; i++) {\n const before = expr\n expr = expr.replace(/\\\\frac\\s*\\{([^}]*)\\}\\s*\\{([^}]*)\\}/g, '($1)/($2)')\n if (expr === before) break\n }\n\n expr = expr.replace(/\\\\sqrt\\[([^\\]]+)\\]\\s*\\{([^}]*)\\}/g, 'nthRoot($2, $1)')\n expr = expr.replace(/\\\\sqrt\\s*\\{([^}]*)\\}/g, 'sqrt($1)')\n\n expr = expr.replace(/\\\\arcsin/g, 'asin')\n expr = expr.replace(/\\\\arccos/g, 'acos')\n expr = expr.replace(/\\\\arctan/g, 'atan')\n\n expr = expr.replace(/\\\\(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|ln|log|exp|abs|det)/g, '$1')\n\n expr = expr.replace(/log_\\{?(\\w+)\\}?\\s*\\(([^)]+)\\)/g, 'log($2, $1)')\n expr = expr.replace(/\\^{([^{}]*)}/g, '^($1)')\n expr = expr.replace(/_\\{[^{}]*\\}/g, '')\n expr = expr.replace(/_\\w/g, '')\n\n expr = expr.replace(/\\\\pi/g, 'pi')\n expr = expr.replace(\n /\\\\(alpha|beta|gamma|delta|epsilon|theta|lambda|mu|sigma|tau|phi|omega)/g,\n '$1'\n )\n\n expr = expr.replace(/\\\\cdot/g, '*')\n expr = expr.replace(/\\\\times/g, '*')\n expr = expr.replace(/\\\\div/g, '/')\n expr = expr.replace(/\\\\infty/g, 'Infinity')\n expr = expr.replace(/\\\\left\\s*([([{|])/g, '$1')\n expr = expr.replace(/\\\\right\\s*([)\\]}|])/g, '$1')\n expr = expr.replace(/\\\\sum/g, 'sum')\n expr = expr.replace(/\\\\prod/g, 'prod')\n expr = expr.replace(/\\\\,/g, ' ')\n expr = expr.replace(/\\\\;/g, ' ')\n expr = expr.replace(/\\\\quad/g, ' ')\n expr = expr.replace(/\\\\qquad/g, ' ')\n expr = expr.replace(/\\\\text\\{([^{}]*)\\}/g, '')\n expr = expr.replace(/(\\d)([a-zA-Z(])/g, '$1*$2')\n expr = expr.replace(/\\)\\s*\\(/g, ')*(')\n expr = expr.replace(/\\s+/g, ' ').trim()\n\n return expr\n}\n\n// ─── Numeric calculus ─────────────────────────────────────────────────────────\n//\n// `evaluate_katex` is a numeric evaluator. mathjs has no symbolic integration, and its symbolic\n// `derivative` is intentionally blocklisted above, so calculus is computed NUMERICALLY: definite\n// integrals via composite Simpson quadrature, derivatives via central finite differences, and limits\n// via a two-sided approach. These are approximations (correct to ~1e-9 for the smooth expressions a\n// model emits), surfaced under a `Result (numeric):` label so the distinction is explicit.\n//\n// Detection runs on the RAW LaTeX, before `translateLatex` flattens it — its subscript stripping\n// would otherwise destroy integral bounds (`\\int_{0}^{1}` → `\\int^(1)`) and limit targets. The\n// extracted sub-expressions (integrand, bounds, body, point) are then translated by the existing\n// `translateLatex` and evaluated per-point with a scope, which works under the security blocklist.\n\n/** A tagged error whose message is surfaced to the model verbatim (caught by {@link tryCalculus}). */\nclass CalculusError extends Error {}\n\n/** Evaluate a mathjs expression at a single point, guarding against non-finite results. */\nfunction evalAt(expr: string, varName: string, x: number): number {\n const y = math.evaluate!(expr, { [varName]: x })\n if (typeof y !== 'number' || !Number.isFinite(y)) {\n throw new CalculusError('NON_FINITE')\n }\n return y\n}\n\n/** Composite Simpson's rule over a finite interval. Throws {@link CalculusError} on a singularity. */\nfunction simpson(fn: (x: number) => number, a: number, b: number, n = 1000): number {\n if (n % 2 === 1) n++\n const h = (b - a) / n\n let sum = fn(a) + fn(b)\n for (let i = 1; i < n; i++) {\n sum += (i % 2 === 1 ? 4 : 2) * fn(a + i * h)\n }\n const result = (h / 3) * sum\n if (!Number.isFinite(result)) throw new CalculusError('NON_FINITE')\n return result\n}\n\n/** Round numeric output to 12 significant digits, collapsing floating-point noise. */\nfunction formatNumeric(n: number): string {\n // Snap values that are zero-to-within-tolerance to exactly 0 (e.g. lim_{x->inf} 1/x ≈ 1e-8).\n if (Math.abs(n) < 1e-9) return '0'\n return math.format!(n, { precision: 12 })\n}\n\n/**\n * Reads a single `_`/`^` script starting at `i`, supporting braced (`_{0}`, `^{\\pi}`), command\n * (`^\\pi`), and bare-token (`_0`, `^1`) forms. Returns the mark, its raw-LaTeX value, and the next\n * index, or `null` when there is no script at `i`.\n */\nfunction readScript(s: string, i: number): { mark: '_' | '^'; val: string; next: number } | null {\n while (s[i] === ' ') i++\n const mark = s[i]\n if (mark !== '_' && mark !== '^') return null\n i++\n while (s[i] === ' ') i++\n if (s[i] === '{') {\n let depth = 0\n const start = ++i\n for (; i < s.length; i++) {\n if (s[i] === '{') depth++\n else if (s[i] === '}') {\n if (depth === 0) break\n depth--\n }\n }\n return { mark, val: s.slice(start, i), next: i + 1 }\n }\n if (s[i] === '\\\\') {\n const m = /^\\\\[a-zA-Z]+/.exec(s.slice(i))\n if (!m) return null\n return { mark, val: m[0], next: i + m[0].length }\n }\n const m = /^[A-Za-z0-9.]+/.exec(s.slice(i))\n if (!m) return null\n return { mark, val: m[0], next: i + m[0].length }\n}\n\n/** Translate a raw-LaTeX bound/target fragment and evaluate it to a finite number. */\nfunction evalBound(latex: string): number {\n const trimmed = latex.trim()\n if (/\\\\infty/.test(trimmed)) throw new CalculusError('INFINITE_BOUND')\n const mathjsExpr = translateLatex(trimmed)\n const value = math.evaluate!(mathjsExpr)\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new CalculusError('BAD_BOUND')\n }\n return value\n}\n\n/** Evaluate a definite integral `\\int_{a}^{b} f \\,dx` by Simpson quadrature. */\nfunction evalIntegral(s: string): string {\n // Strip the operator (\\int, optionally with \\limits).\n const m = /\\\\int(?:\\\\limits)?/.exec(s)\n if (!m) throw new CalculusError('NOT_INTEGRAL')\n let i = m.index + m[0].length\n\n // Read up to two scripts (bounds), in either order.\n const scripts: Record<'_' | '^', string | undefined> = { '_': undefined, '^': undefined }\n for (let k = 0; k < 2; k++) {\n const sc = readScript(s, i)\n if (!sc) break\n scripts[sc.mark] = sc.val\n i = sc.next\n }\n if (scripts._ === undefined || scripts['^'] === undefined) {\n throw new CalculusError('INDEFINITE')\n }\n\n // The remainder is `integrand … d<var>`. Pull the trailing differential off the end.\n const rest = s.slice(i)\n const diff = /\\\\?,?\\s*\\bd\\s*([a-zA-Z])\\s*$/.exec(rest)\n if (!diff) throw new CalculusError('NO_DIFFERENTIAL')\n const variable = diff[1]\n const integrandLatex = rest.slice(0, diff.index)\n if (integrandLatex.trim().length === 0) throw new CalculusError('NO_INTEGRAND')\n\n const a = evalBound(scripts._)\n const b = evalBound(scripts['^'])\n const integrand = translateLatex(integrandLatex)\n const fn = (x: number) => evalAt(integrand, variable, x)\n\n let result: number\n if (a === b) result = 0\n else if (a < b) result = simpson(fn, a, b)\n else result = -simpson(fn, b, a)\n\n return `Converted: ∫(${integrand}) d${variable} from ${formatNumeric(a)} to ${formatNumeric(b)}\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Evaluate a derivative `\\frac{d}{dx} f \\big|_{x=a}` at a point via central finite difference. */\nfunction evalDerivative(s: string): string {\n // Operator + variable: \\frac{d}{dx} … or bare d/dx ….\n let variable: string | undefined\n let body = s\n const fracOp = /\\\\frac\\s*\\{\\s*d\\s*\\}\\s*\\{\\s*d\\s*([a-zA-Z])\\s*\\}/.exec(s)\n if (fracOp) {\n variable = fracOp[1]\n body = s.slice(fracOp.index + fracOp[0].length)\n } else {\n const bareOp = /(?:^|[^a-zA-Z])d\\s*\\/\\s*d([a-zA-Z])/.exec(s)\n if (bareOp) {\n variable = bareOp[1]\n body = s.slice(bareOp.index + bareOp[0].length)\n }\n }\n if (!variable) throw new CalculusError('NOT_DERIVATIVE')\n\n // Remove pure \\left. / \\right. delimiters.\n body = body.replace(/\\\\left\\.?/g, '').replace(/\\\\right\\.?/g, '')\n\n // Evaluation bar + point at the end: …|_{x=3} (optionally \\Big| etc.).\n const bar = /\\\\?(?:Big|big|bigg|Bigg)?\\s*\\|\\s*_\\s*\\{?\\s*([a-zA-Z])\\s*=\\s*([^}]+?)\\s*\\}?\\s*$/.exec(\n body\n )\n if (!bar) throw new CalculusError('NO_POINT')\n const point = evalBound(bar[2])\n let fnLatex = body.slice(0, bar.index).trim()\n\n // Strip one layer of wrapping parentheses/brackets around the function body.\n fnLatex = fnLatex\n .replace(/^\\\\?\\(([\\s\\S]*)\\\\?\\)$/, '$1')\n .replace(/^\\[([\\s\\S]*)\\]$/, '$1')\n .trim()\n if (fnLatex.length === 0) throw new CalculusError('NO_FUNCTION')\n\n const expr = translateLatex(fnLatex)\n const h = 1e-6\n const fn = (x: number) => evalAt(expr, variable, x)\n const result = (fn(point + h) - fn(point - h)) / (2 * h)\n if (!Number.isFinite(result)) throw new CalculusError('NON_FINITE')\n\n return `Converted: d/d${variable}(${expr}) at ${variable}=${formatNumeric(point)}\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Evaluate a limit `\\lim_{x \\to a} f(x)` by a two-sided numeric approach. */\nfunction evalLimit(s: string): string {\n const head = /\\\\lim\\s*_\\s*\\{\\s*([a-zA-Z])\\s*\\\\to\\s*([\\s\\S]+?)\\s*\\}/.exec(s)\n if (!head) throw new CalculusError('NOT_LIMIT')\n const variable = head[1]\n let targetLatex = head[2].trim()\n const bodyLatex = s.slice(head.index + head[0].length).trim()\n if (bodyLatex.length === 0) throw new CalculusError('NO_FUNCTION')\n\n // One-sided markers (0^+, 0^-, 0^{+}) — record the side, strip the marker.\n let side: 'both' | 'plus' | 'minus' = 'both'\n const oneSided = /\\^\\s*\\{?\\s*([+-])\\s*\\}?\\s*$/.exec(targetLatex)\n if (oneSided) {\n side = oneSided[1] === '+' ? 'plus' : 'minus'\n targetLatex = targetLatex.slice(0, oneSided.index).trim()\n }\n\n const expr = translateLatex(bodyLatex)\n const fn = (x: number) => evalAt(expr, variable, x)\n const eps = 1e-6\n\n // Infinite targets via large-magnitude substitution.\n let result: number\n let targetLabel: string\n if (/^-\\s*\\\\infty$/.test(targetLatex)) {\n result = fn(-1e8)\n targetLabel = '-∞'\n } else if (/^\\\\infty$/.test(targetLatex)) {\n result = fn(1e8)\n targetLabel = '∞'\n } else {\n const target = evalBound(targetLatex)\n targetLabel = formatNumeric(target)\n if (side === 'plus') {\n result = fn(target + eps)\n } else if (side === 'minus') {\n result = fn(target - eps)\n } else {\n const lo = fn(target - eps)\n const hi = fn(target + eps)\n const avg = (lo + hi) / 2\n if (Math.abs(hi - lo) > 1e-3 * Math.max(1, Math.abs(avg))) {\n throw new CalculusError('LIMIT_MISMATCH')\n }\n result = avg\n }\n }\n if (!Number.isFinite(result)) throw new CalculusError('LIMIT_UNBOUNDED')\n\n // Infinite-target substitution (±1e8) and the eps offset leave more residue than Simpson or the\n // derivative difference, so snap a limit result to a nearby round value before formatting:\n // 0.99999998 → 1, 1e-8 → 0. The tolerance is loose enough to absorb the substitution error yet\n // far tighter than the divergence check that already rejected genuinely non-convergent limits.\n const nearest = Math.round(result)\n if (Math.abs(result - nearest) < 1e-6) result = nearest\n\n return `Converted: lim ${variable}→${targetLabel} of (${expr})\\nResult (numeric): ${formatNumeric(result)}`\n}\n\n/** Human-readable, model-actionable message for each {@link CalculusError} tag. */\nfunction calculusErrorMessage(tag: string): string {\n switch (tag) {\n case 'INDEFINITE':\n return 'Cannot evaluate an indefinite integral numerically. Provide bounds, e.g. \\\\int_{0}^{1} x dx.'\n case 'NO_DIFFERENTIAL':\n return \"Could not find the integration variable. Expected a trailing differential like 'dx'.\"\n case 'NO_INTEGRAND':\n return 'The integral has no integrand to evaluate.'\n case 'INFINITE_BOUND':\n return 'Infinite integration bounds are not supported. Provide finite numeric bounds, e.g. \\\\int_{0}^{1} f dx.'\n case 'BAD_BOUND':\n return 'Could not evaluate the integration bounds to numbers.'\n case 'NO_POINT':\n return 'Cannot evaluate a derivative numerically without a point. Specify where, e.g. \\\\frac{d}{dx}(x^2)\\\\Big|_{x=3}.'\n case 'NO_FUNCTION':\n return 'Could not find the function to evaluate.'\n case 'LIMIT_MISMATCH':\n return 'The limit may not exist (left and right values disagree).'\n case 'LIMIT_UNBOUNDED':\n return 'The limit appears to diverge (function is unbounded near the target).'\n case 'NON_FINITE':\n return 'The expression is not finite over the requested range (possible singularity); cannot evaluate numerically.'\n default:\n return 'Could not evaluate the calculus expression.'\n }\n}\n\n/**\n * Detects a calculus construct in raw LaTeX and routes it to the matching numeric handler. Returns\n * the result/error string, or `null` when the input is not a calculus expression (so the caller\n * falls through to the scalar evaluation path unchanged).\n */\nfunction tryCalculus(latex: string): string | null {\n let s = latex.trim()\n s = s.replace(/^\\$\\$?|\\$\\$?$/g, '')\n s = s.replace(/^\\\\[[(]|\\\\[\\])]$/g, '').trim()\n\n let handler: ((expr: string) => string) | undefined\n if (/\\\\int/.test(s)) handler = evalIntegral\n else if (/\\\\lim/.test(s)) handler = evalLimit\n else if (\n /\\\\frac\\s*\\{\\s*d\\s*\\}\\s*\\{\\s*d\\s*[a-zA-Z]\\s*\\}/.test(s) ||\n /(?:^|[^a-zA-Z])d\\s*\\/\\s*d[a-zA-Z]/.test(s)\n )\n handler = evalDerivative\n if (!handler) return null\n\n try {\n return handler(s)\n } catch (err) {\n if (isInstanceOf(err, 'CalculusError', CalculusError)) {\n return `Error: ${calculusErrorMessage(err.message)}`\n }\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n}\n\n/**\n * Evaluates a mathjs-syntax expression and returns the numeric result alongside the KaTeX\n * representation of the parsed expression.\n *\n * @remarks\n * Supports arithmetic, trigonometric, logarithmic, exponential, factorial, matrix, and unit\n * operations via `mathjs`. The mathjs instance is hardened: dangerous functions (`import`,\n * `createUnit`, `simplify`, `derivative`, `compile`, `chain`, `reviver`, `replacer`) are\n * disabled to prevent interpreter-surface exposure.\n *\n * Expressions over 1000 characters are rejected with an error string (not thrown). Parse and\n * evaluation errors are also returned as error strings — the tool surfaces math errors as\n * content rather than exceptions, so the model can react to them in-line.\n */\nexport const calculateTool = new Tool({\n name: 'calculate',\n description:\n 'Evaluate a math expression. Supports arithmetic, trig, log, sqrt, factorial, matrices.',\n inputSchema: validator.object({\n expression: validator.string().required().description('Math expression, e.g. \"sin(pi/4) + 5!\"'),\n }),\n handler: async (args) => {\n const { expression } = args as { expression: string }\n\n const lengthError = validateExpression(expression)\n if (lengthError) return lengthError\n\n try {\n const result = math.evaluate!(expression)\n // A scalar that overflowed float64 (e.g. `2^5000`, `factorial(200)`) comes back as\n // `Infinity`/`NaN`. Surface that as a clear error rather than printing `Result: Infinity`,\n // which reads like a genuine answer.\n if (typeof result === 'number' && !Number.isFinite(result)) {\n return `Error: result is not finite (${result}) — the value overflows JavaScript's numeric range.`\n }\n const node = math.parse!(expression)\n const katex = node.toTex()\n return `Result: ${result}\\nKaTeX: $${katex} = ${result}$`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n\n/**\n * Translates a LaTeX/KaTeX expression using evaluatex and returns the numeric result.\n *\n * @remarks\n * Uses the evaluatex library to parse and evaluate LaTeX expressions. Handles common constructs\n * (`\\frac{a}{b}`, `\\sqrt{...}`, `\\cdot`, `\\times`, Greek macros like `\\pi`, inverse trig,\n * `\\left`/`\\right` delimiters, `\\text{...}`, subscripts, etc.) with a proper parser rather than\n * brittle regex.\n *\n * Also evaluates three calculus constructs **numerically** (mathjs has no symbolic integration, and\n * its symbolic `derivative` is blocklisted here for safety):\n * - Definite integrals — `\\int_{a}^{b} f \\,dx` via composite Simpson quadrature.\n * - Derivatives at a point — `\\frac{d}{dx} f \\big|_{x=a}` via central finite difference.\n * - Limits — `\\lim_{x \\to a} f` (including `a = \\pm\\infty`) via a two-sided numeric approach.\n *\n * Numeric results are rounded with `math.format(..., { precision: 12 })` and labelled\n * `Result (numeric):` to flag that they are approximations. Constructs that cannot be evaluated\n * numerically (indefinite integrals, derivatives without a point, infinite integration bounds,\n * singular integrands, divergent limits) return a specific, guiding error string.\n *\n * Parse and evaluation errors are returned as error strings rather than thrown.\n */\nexport const evaluateKatexTool = new Tool({\n name: 'evaluate_katex',\n description:\n 'Evaluate a KaTeX/LaTeX math expression and return the numeric result. Supports arithmetic, trig, logs, roots, and numeric calculus: definite integrals (\\\\int_{a}^{b} f dx), derivatives at a point (\\\\frac{d}{dx} f|_{x=a}), and limits (\\\\lim_{x \\\\to a} f).',\n inputSchema: validator.object({\n katex: validator\n .string()\n .required()\n .description('LaTeX expression, e.g. \"\\\\frac{1}{2} + \\\\sqrt{9}\" or \"\\\\int_{0}^{1} x^2 dx\"'),\n }),\n handler: async (args) => {\n const { katex } = args as { katex: string }\n\n const lengthError = validateExpression(katex)\n if (lengthError) return lengthError\n\n try {\n // Calculus (\\int, \\lim, d/dx) is detected on the raw LaTeX and evaluated numerically before\n // the scalar flattening path, which would otherwise mangle bounds/targets. Returns null for\n // non-calculus input, falling through to the scalar evaluator below unchanged.\n const calculus = tryCalculus(katex)\n if (calculus !== null) return calculus\n\n const result = evaluateLatex(katex)\n return `Result: ${result}`\n } catch (err) {\n return `Error: ${isError(err) ? err.message : String(err)}`\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,QAAA,GAAA,OAAA,QAAc,OAAA,GAAG;AAavB,KAAK,MAAM,MAAM;CAVf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAGe,GACf,IAAI,MAAM,MACP,KAAc,MAAM,KAAA;AAIzB,IAAM,wBAAwB;AAE9B,SAAS,mBAAmB,MAAkC;CAC5D,IAAI,KAA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