@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
|
@@ -41,6 +41,7 @@ export interface MarkdownCodeEntry {
|
|
|
41
41
|
* requests it via `cat(bodyStartLine, bodyEndLine + 1)`.
|
|
42
42
|
*/
|
|
43
43
|
export interface MarkdownSection {
|
|
44
|
+
/** ATX heading depth: 1 (`#`) through 6 (`######`). */
|
|
44
45
|
depth: 1 | 2 | 3 | 4 | 5 | 6;
|
|
45
46
|
/** The heading text. */
|
|
46
47
|
heading: string;
|
|
@@ -54,6 +54,7 @@ export type TokenEncoding = (typeof TokenEncoding)[number];
|
|
|
54
54
|
*/
|
|
55
55
|
export declare class Tokenizable {
|
|
56
56
|
#private;
|
|
57
|
+
/** The set of supported token-encoding identifiers, re-exposed as a static for convenience. */
|
|
57
58
|
static TokenEncoding: readonly [
|
|
58
59
|
"gpt2",
|
|
59
60
|
"r50k_base",
|
|
@@ -77,7 +78,9 @@ export declare class Tokenizable {
|
|
|
77
78
|
toString: () => string;
|
|
78
79
|
valueOf: () => string;
|
|
79
80
|
toLocaleString: () => string;
|
|
81
|
+
/** Replace the wrapped string value (and invalidate the cached token estimates). */
|
|
80
82
|
set: (value: string) => void;
|
|
83
|
+
/** Estimate the token count of the wrapped string under the given {@link TokenEncoding}. */
|
|
81
84
|
estimateTokens: (encoding: TokenEncoding) => number;
|
|
82
85
|
/**
|
|
83
86
|
* @param value - The initial string value to wrap.
|
package/lib/classes/tool.d.ts
CHANGED
|
@@ -164,13 +164,21 @@ export declare class Tool<A extends SpooledArtifact = SpooledArtifact> {
|
|
|
164
164
|
* @returns `true` when `value` is a {@link Tool} instance.
|
|
165
165
|
*/
|
|
166
166
|
static isTool(value: unknown): value is Tool;
|
|
167
|
+
/** The tool's unique name, as exposed to the model in the tool definition. */
|
|
167
168
|
readonly name: string;
|
|
169
|
+
/** Human/model-facing description of what the tool does. */
|
|
168
170
|
readonly description: string;
|
|
171
|
+
/** Validation schema for the tool's arguments; also drives the generated parameter definition. */
|
|
169
172
|
readonly inputSchema: Schema;
|
|
173
|
+
/** Resolver for the artifact constructor used to wrap the handler's output, if any. */
|
|
170
174
|
readonly artifactConstructor: ArtifactConstructorResolver<A> | undefined;
|
|
175
|
+
/** Arbitrary per-tool metadata registry, passed through to the handler. */
|
|
171
176
|
readonly meta: Registry;
|
|
177
|
+
/** When `true`, the tool's results are not persisted to history (transient/one-shot). */
|
|
172
178
|
readonly ephemeral: boolean;
|
|
179
|
+
/** When `true`, the tool's output is treated as trusted content by the LLM battery's envelopes. */
|
|
173
180
|
readonly trusted: boolean;
|
|
181
|
+
/** How registration resolves a name clash in a {@link ToolRegistry}: throw, replace, or keep the existing. */
|
|
174
182
|
readonly onCollision: 'throw' | 'replace' | 'keep';
|
|
175
183
|
/**
|
|
176
184
|
* @param raw - The raw tool input validated against `rawToolSchema`.
|
|
@@ -63,11 +63,17 @@ export declare class TurnGate<T = unknown> {
|
|
|
63
63
|
* @returns `true` when `value` is a {@link TurnGate} instance.
|
|
64
64
|
*/
|
|
65
65
|
static isTurnGate(value: unknown): value is TurnGate;
|
|
66
|
+
/** Unique identifier for this gate instance. */
|
|
66
67
|
readonly id: string;
|
|
68
|
+
/** Id of the turn this gate belongs to. */
|
|
67
69
|
readonly turnId: string;
|
|
70
|
+
/** Human-readable reason the gate was opened. */
|
|
68
71
|
readonly reason: string;
|
|
72
|
+
/** Optional caller-supplied payload describing what the gate is waiting on. */
|
|
69
73
|
readonly payload: unknown;
|
|
74
|
+
/** When the gate was created. */
|
|
70
75
|
readonly createdAt: DateTime;
|
|
76
|
+
/** Whether the gate has been settled (resolved or rejected) and no longer blocks the turn. */
|
|
71
77
|
readonly isSettled: boolean;
|
|
72
78
|
/**
|
|
73
79
|
* @param raw - The raw gate input validated against `rawTurnGateSchema`.
|
package/lib/dispatch_runner.d.ts
CHANGED
|
@@ -35,40 +35,13 @@ export interface RawDispatchRunnerInput {
|
|
|
35
35
|
observers?: DispatchRunnerObservabilityHookRegistrations;
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* @remarks
|
|
43
|
-
* `DispatchRunner` has a private constructor and is invoked via the static `dispatch()`
|
|
44
|
-
* method. Each dispatch creates a fresh single-use runner that is garbage-collected after the
|
|
45
|
-
* call completes — matching the `@nhtio/hooks` GC rationale already baked into the context.
|
|
46
|
-
*
|
|
47
|
-
* The runner owns the relationship between an {@link @nhtio/adk!DispatchContext} and its parent
|
|
48
|
-
* {@link @nhtio/adk!TurnContext} (when given a source). It subscribes to the context's mutation hooks,
|
|
49
|
-
* queues `ContextDelta` entries, and flushes them to the parent's Sets at the end of every
|
|
50
|
-
* iteration. Emits propagate from the context's hooks → the runner's hooks → (optionally) the
|
|
51
|
-
* parent `TurnContext`'s emit methods → the `TurnRunner`'s buses.
|
|
52
|
-
*
|
|
53
|
-
* Two hook buses, mirroring `TurnRunner`'s pattern:
|
|
54
|
-
*
|
|
55
|
-
* - **Functional** (`hooks`): `message`, `thought`, `toolCall` — pipeline-affecting events
|
|
56
|
-
* - **Observability** (`observers`): `iterationStart`, `iterationEnd`, `dispatchStart`,
|
|
57
|
-
* `dispatchEnd`, `error`, `toolExecutionStart`, `toolExecutionEnd` — instrumentation only
|
|
58
|
-
*
|
|
59
|
-
* The runner has no `maxIterations`, no `maxToolCallChecksumRepeats`. Implementers use the
|
|
60
|
-
* primitives — `ctx.iteration`, `ctx.toolCallCount(checksum)`, `ctx.ack()`, `ctx.nack()`,
|
|
61
|
-
* `ctx.abortSignal` — to build any termination bounds they need in their own middleware.
|
|
62
|
-
*/
|
|
63
|
-
/**
|
|
64
|
-
* Module-private token gating direct construction of {@link DispatchRunner}. Callers must use
|
|
65
|
-
* {@link DispatchRunner.dispatch}; the symbol is not exported, so external code cannot satisfy
|
|
66
|
-
* the guard at runtime.
|
|
38
|
+
* Runs a single dispatch iteration of an agentic turn: it drives the executor through the
|
|
39
|
+
* input/output middleware pipelines, emitting functional and observability hook events along the
|
|
40
|
+
* way. Construction is gated — obtain one via the static {@link DispatchRunner.dispatch} entry
|
|
41
|
+
* point rather than `new`.
|
|
67
42
|
*/
|
|
68
|
-
declare const CONSTRUCT_TOKEN: unique symbol;
|
|
69
43
|
export declare class DispatchRunner {
|
|
70
44
|
#private;
|
|
71
|
-
constructor(token: typeof CONSTRUCT_TOKEN, sourceCtx: TurnContext | undefined, turnInputPipeline: DispatchPipelineMiddlewareFn[], turnOutputPipeline: DispatchPipelineMiddlewareFn[], hooks: DispatchRunnerFunctionalHookRegistrations | undefined, observers: DispatchRunnerObservabilityHookRegistrations | undefined);
|
|
72
45
|
/**
|
|
73
46
|
* Returns `true` if `value` is a {@link DispatchRunner} instance.
|
|
74
47
|
*
|
|
@@ -95,4 +68,3 @@ export declare class DispatchRunner {
|
|
|
95
68
|
*/
|
|
96
69
|
static dispatch(input: RawDispatchRunnerInput): Promise<void>;
|
|
97
70
|
}
|
|
98
|
-
export {};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("../../chunk-Ble4zEEl.js");
|
|
3
|
+
let mathjs = require("mathjs");
|
|
4
|
+
//#region src/lib/helpers/bignum.ts
|
|
5
|
+
/**
|
|
6
|
+
* Arbitrary-precision numeric helpers for the bundled tools.
|
|
7
|
+
*
|
|
8
|
+
* @module @nhtio/adk/lib/helpers/bignum
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* ECMAScript numbers are IEEE-754 float64: arithmetic on user-supplied values can overflow to
|
|
12
|
+
* `Infinity`, underflow to `0`, or silently lose precision (`0.1 + 0.2 === 0.30000000000000004`).
|
|
13
|
+
* The numeric tool batteries (`statistics`, `data_structure`, `unit_conversion`, `math`) route
|
|
14
|
+
* their aggregations and result formatting through this module so that:
|
|
15
|
+
*
|
|
16
|
+
* - large in-range sums stay exact instead of overflowing (`sum([1e308, 1e308]) → 2e308`),
|
|
17
|
+
* - precision is preserved end-to-end (`sum([0.1, 0.2]) → 0.3`),
|
|
18
|
+
* - output is rendered to a caller-chosen number of significant digits (default 8) without the
|
|
19
|
+
* lossy `Number.prototype.toPrecision`/`toFixed` round-trip that mangles even safe integers
|
|
20
|
+
* (e.g. `9007199254740991` rendered as `9007199255000`).
|
|
21
|
+
*
|
|
22
|
+
* Internally this is backed by a single {@link https://mathjs.org | mathjs} instance configured
|
|
23
|
+
* for `BigNumber` (which bundles `decimal.js`) at 64 significant digits — comfortably more than
|
|
24
|
+
* float64's ~15-17 and enough for the tools' needs without unbounded growth.
|
|
25
|
+
*
|
|
26
|
+
* The tools still RECEIVE float64 numbers (the model's tool-call arguments are JSON-parsed to
|
|
27
|
+
* float64 upstream, and the typed-array input schemas reject `NaN`/`Infinity`/`> 2^53` before the
|
|
28
|
+
* handler runs). BigNumber's job is the math and formatting in between, not the input boundary.
|
|
29
|
+
*/
|
|
30
|
+
/**
|
|
31
|
+
* Precision (significant digits) the internal BigNumber engine computes with. Distinct from the
|
|
32
|
+
* per-call display precision passed to {@link formatBig} — this is the working precision so that
|
|
33
|
+
* intermediate results don't accumulate rounding error before they are formatted down.
|
|
34
|
+
*/
|
|
35
|
+
var WORKING_PRECISION = 64;
|
|
36
|
+
/** Default display precision (significant digits) for tool output. */
|
|
37
|
+
var DEFAULT_PRECISION = 8;
|
|
38
|
+
var math = (0, mathjs.create)(mathjs.all, {
|
|
39
|
+
number: "BigNumber",
|
|
40
|
+
precision: WORKING_PRECISION
|
|
41
|
+
});
|
|
42
|
+
/** Coerce a JS number to a {@link BigNumber}. Non-finite inputs are a caller bug (schemas reject them). */
|
|
43
|
+
var toBig = (n) => math.bignumber(n);
|
|
44
|
+
/** Exact sum of a numeric array as a {@link BigNumber} (no float64 overflow/precision loss). */
|
|
45
|
+
var bigSum = (nums) => nums.reduce((acc, n) => math.add(acc, math.bignumber(n)), math.bignumber(0));
|
|
46
|
+
/** Exact arithmetic mean as a {@link BigNumber}. Caller guarantees `nums.length > 0`. */
|
|
47
|
+
var bigMean = (nums) => math.divide(bigSum(nums), nums.length);
|
|
48
|
+
/** `value * fromFactor / toFactor` computed without intermediate float64 over/underflow. */
|
|
49
|
+
var bigScale = (value, fromFactor, toFactor) => math.divide(math.multiply(math.bignumber(value), math.bignumber(fromFactor)), math.bignumber(toFactor));
|
|
50
|
+
/**
|
|
51
|
+
* Render a {@link BigNumber} (or JS number) to a string at `precision` significant digits.
|
|
52
|
+
*
|
|
53
|
+
* @remarks
|
|
54
|
+
* - An EXACT INTEGER is rendered in full fixed notation regardless of `precision`: an integer
|
|
55
|
+
* carries no fractional precision to lose, so `8000000000000` stays `8000000000000` rather than
|
|
56
|
+
* being truncated to `8e+12`. (Bounded at 30 digits to avoid pathological astronomically-large
|
|
57
|
+
* integers printing thousands of characters; beyond that, sig-fig exponential is used.)
|
|
58
|
+
* - Non-integers are rendered at `precision` significant digits (default 8), stripping trailing
|
|
59
|
+
* zeros — avoiding the `toPrecision` artifact that mangled safe values, while still giving the
|
|
60
|
+
* caller control over how many digits they want (raise `precision` for more).
|
|
61
|
+
* - Exact zero renders as `'0'`. (Genuinely tiny values like `2.54e-5` are preserved, NOT snapped.)
|
|
62
|
+
*/
|
|
63
|
+
var formatBig = (value, precision = 8) => {
|
|
64
|
+
const b = typeof value === "number" ? math.bignumber(value) : value;
|
|
65
|
+
if (math.equal(b, 0)) return "0";
|
|
66
|
+
const p = Number.isFinite(precision) ? Math.max(1, Math.min(64, Math.floor(precision))) : 8;
|
|
67
|
+
const fixed = math.format(b, { notation: "fixed" });
|
|
68
|
+
if (!fixed.includes(".") && fixed.replace("-", "").length <= 31) return fixed;
|
|
69
|
+
return math.format(b, { precision: p });
|
|
70
|
+
};
|
|
71
|
+
/** Convert a {@link BigNumber} back to a JS number (for cases that must hand off a float64). */
|
|
72
|
+
var bigToNumber = (b) => math.number(b);
|
|
73
|
+
//#endregion
|
|
74
|
+
exports.DEFAULT_PRECISION = DEFAULT_PRECISION;
|
|
75
|
+
exports.bigMean = bigMean;
|
|
76
|
+
exports.bigScale = bigScale;
|
|
77
|
+
exports.bigSum = bigSum;
|
|
78
|
+
exports.bigToNumber = bigToNumber;
|
|
79
|
+
exports.formatBig = formatBig;
|
|
80
|
+
exports.toBig = toBig;
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=bignum.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bignum.cjs","names":[],"sources":["../../../src/lib/helpers/bignum.ts"],"sourcesContent":["/**\n * Arbitrary-precision numeric helpers for the bundled tools.\n *\n * @module @nhtio/adk/lib/helpers/bignum\n *\n * @remarks\n * ECMAScript numbers are IEEE-754 float64: arithmetic on user-supplied values can overflow to\n * `Infinity`, underflow to `0`, or silently lose precision (`0.1 + 0.2 === 0.30000000000000004`).\n * The numeric tool batteries (`statistics`, `data_structure`, `unit_conversion`, `math`) route\n * their aggregations and result formatting through this module so that:\n *\n * - large in-range sums stay exact instead of overflowing (`sum([1e308, 1e308]) → 2e308`),\n * - precision is preserved end-to-end (`sum([0.1, 0.2]) → 0.3`),\n * - output is rendered to a caller-chosen number of significant digits (default 8) without the\n * lossy `Number.prototype.toPrecision`/`toFixed` round-trip that mangles even safe integers\n * (e.g. `9007199254740991` rendered as `9007199255000`).\n *\n * Internally this is backed by a single {@link https://mathjs.org | mathjs} instance configured\n * for `BigNumber` (which bundles `decimal.js`) at 64 significant digits — comfortably more than\n * float64's ~15-17 and enough for the tools' needs without unbounded growth.\n *\n * The tools still RECEIVE float64 numbers (the model's tool-call arguments are JSON-parsed to\n * float64 upstream, and the typed-array input schemas reject `NaN`/`Infinity`/`> 2^53` before the\n * handler runs). BigNumber's job is the math and formatting in between, not the input boundary.\n */\n\nimport { create, all, type BigNumber } from 'mathjs'\n\n/**\n * Precision (significant digits) the internal BigNumber engine computes with. Distinct from the\n * per-call display precision passed to {@link formatBig} — this is the working precision so that\n * intermediate results don't accumulate rounding error before they are formatted down.\n */\nconst WORKING_PRECISION = 64\n\n/** Default display precision (significant digits) for tool output. */\nexport const DEFAULT_PRECISION = 8\n\nconst math = create(all, { number: 'BigNumber', precision: WORKING_PRECISION })\n\n/** Coerce a JS number to a {@link BigNumber}. Non-finite inputs are a caller bug (schemas reject them). */\nexport const toBig = (n: number): BigNumber => math.bignumber(n)\n\n/** Exact sum of a numeric array as a {@link BigNumber} (no float64 overflow/precision loss). */\nexport const bigSum = (nums: number[]): BigNumber =>\n nums.reduce<BigNumber>((acc, n) => math.add(acc, math.bignumber(n)), math.bignumber(0))\n\n/** Exact arithmetic mean as a {@link BigNumber}. Caller guarantees `nums.length > 0`. */\nexport const bigMean = (nums: number[]): BigNumber =>\n math.divide(bigSum(nums), nums.length) as BigNumber\n\n/** `value * fromFactor / toFactor` computed without intermediate float64 over/underflow. */\nexport const bigScale = (value: number, fromFactor: number, toFactor: number): BigNumber =>\n math.divide(\n math.multiply(math.bignumber(value), math.bignumber(fromFactor)),\n math.bignumber(toFactor)\n ) as BigNumber\n\n/**\n * Render a {@link BigNumber} (or JS number) to a string at `precision` significant digits.\n *\n * @remarks\n * - An EXACT INTEGER is rendered in full fixed notation regardless of `precision`: an integer\n * carries no fractional precision to lose, so `8000000000000` stays `8000000000000` rather than\n * being truncated to `8e+12`. (Bounded at 30 digits to avoid pathological astronomically-large\n * integers printing thousands of characters; beyond that, sig-fig exponential is used.)\n * - Non-integers are rendered at `precision` significant digits (default 8), stripping trailing\n * zeros — avoiding the `toPrecision` artifact that mangled safe values, while still giving the\n * caller control over how many digits they want (raise `precision` for more).\n * - Exact zero renders as `'0'`. (Genuinely tiny values like `2.54e-5` are preserved, NOT snapped.)\n */\nexport const formatBig = (\n value: BigNumber | number,\n precision: number = DEFAULT_PRECISION\n): string => {\n const b = typeof value === 'number' ? math.bignumber(value) : value\n if (math.equal(b, 0)) return '0'\n const p = Number.isFinite(precision)\n ? Math.max(1, Math.min(64, Math.floor(precision)))\n : DEFAULT_PRECISION\n // Exact integers up to 30 digits: print in full, no precision truncation, no exponent. The\n // fixed-notation full string is the source of truth for \"is this an exact integer\" — mathjs's\n // `isInteger` is unreliable for Decimals carrying a fractional part under some configs.\n const fixed = math.format(b, { notation: 'fixed' })\n if (!fixed.includes('.') && fixed.replace('-', '').length <= 31) {\n return fixed\n }\n return math.format(b, { precision: p })\n}\n\n/** Convert a {@link BigNumber} back to a JS number (for cases that must hand off a float64). */\nexport const bigToNumber = (b: BigNumber): number => math.number(b)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,oBAAoB;;AAG1B,IAAa,oBAAoB;AAEjC,IAAM,QAAA,GAAA,OAAA,QAAc,OAAA,KAAK;CAAE,QAAQ;CAAa,WAAW;AAAkB,CAAC;;AAG9E,IAAa,SAAS,MAAyB,KAAK,UAAU,CAAC;;AAG/D,IAAa,UAAU,SACrB,KAAK,QAAmB,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,UAAU,CAAC,CAAC,GAAG,KAAK,UAAU,CAAC,CAAC;;AAGxF,IAAa,WAAW,SACtB,KAAK,OAAO,OAAO,IAAI,GAAG,KAAK,MAAM;;AAGvC,IAAa,YAAY,OAAe,YAAoB,aAC1D,KAAK,OACH,KAAK,SAAS,KAAK,UAAU,KAAK,GAAG,KAAK,UAAU,UAAU,CAAC,GAC/D,KAAK,UAAU,QAAQ,CACzB;;;;;;;;;;;;;;AAeF,IAAa,aACX,OACA,YAAA,MACW;CACX,MAAM,IAAI,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI;CAC9D,IAAI,KAAK,MAAM,GAAG,CAAC,GAAG,OAAO;CAC7B,MAAM,IAAI,OAAO,SAAS,SAAS,IAC/B,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS,CAAC,CAAC,IAAA;CAKnD,MAAM,QAAQ,KAAK,OAAO,GAAG,EAAE,UAAU,QAAQ,CAAC;CAClD,IAAI,CAAC,MAAM,SAAS,GAAG,KAAK,MAAM,QAAQ,KAAK,EAAE,EAAE,UAAU,IAC3D,OAAO;CAET,OAAO,KAAK,OAAO,GAAG,EAAE,WAAW,EAAE,CAAC;AACxC;;AAGA,IAAa,eAAe,MAAyB,KAAK,OAAO,CAAC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Arbitrary-precision numeric helpers for the bundled tools.
|
|
3
|
+
*
|
|
4
|
+
* @module @nhtio/adk/lib/helpers/bignum
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* ECMAScript numbers are IEEE-754 float64: arithmetic on user-supplied values can overflow to
|
|
8
|
+
* `Infinity`, underflow to `0`, or silently lose precision (`0.1 + 0.2 === 0.30000000000000004`).
|
|
9
|
+
* The numeric tool batteries (`statistics`, `data_structure`, `unit_conversion`, `math`) route
|
|
10
|
+
* their aggregations and result formatting through this module so that:
|
|
11
|
+
*
|
|
12
|
+
* - large in-range sums stay exact instead of overflowing (`sum([1e308, 1e308]) → 2e308`),
|
|
13
|
+
* - precision is preserved end-to-end (`sum([0.1, 0.2]) → 0.3`),
|
|
14
|
+
* - output is rendered to a caller-chosen number of significant digits (default 8) without the
|
|
15
|
+
* lossy `Number.prototype.toPrecision`/`toFixed` round-trip that mangles even safe integers
|
|
16
|
+
* (e.g. `9007199254740991` rendered as `9007199255000`).
|
|
17
|
+
*
|
|
18
|
+
* Internally this is backed by a single {@link https://mathjs.org | mathjs} instance configured
|
|
19
|
+
* for `BigNumber` (which bundles `decimal.js`) at 64 significant digits — comfortably more than
|
|
20
|
+
* float64's ~15-17 and enough for the tools' needs without unbounded growth.
|
|
21
|
+
*
|
|
22
|
+
* The tools still RECEIVE float64 numbers (the model's tool-call arguments are JSON-parsed to
|
|
23
|
+
* float64 upstream, and the typed-array input schemas reject `NaN`/`Infinity`/`> 2^53` before the
|
|
24
|
+
* handler runs). BigNumber's job is the math and formatting in between, not the input boundary.
|
|
25
|
+
*/
|
|
26
|
+
import { type BigNumber } from 'mathjs';
|
|
27
|
+
/** Default display precision (significant digits) for tool output. */
|
|
28
|
+
export declare const DEFAULT_PRECISION = 8;
|
|
29
|
+
/** Coerce a JS number to a {@link BigNumber}. Non-finite inputs are a caller bug (schemas reject them). */
|
|
30
|
+
export declare const toBig: (n: number) => BigNumber;
|
|
31
|
+
/** Exact sum of a numeric array as a {@link BigNumber} (no float64 overflow/precision loss). */
|
|
32
|
+
export declare const bigSum: (nums: number[]) => BigNumber;
|
|
33
|
+
/** Exact arithmetic mean as a {@link BigNumber}. Caller guarantees `nums.length > 0`. */
|
|
34
|
+
export declare const bigMean: (nums: number[]) => BigNumber;
|
|
35
|
+
/** `value * fromFactor / toFactor` computed without intermediate float64 over/underflow. */
|
|
36
|
+
export declare const bigScale: (value: number, fromFactor: number, toFactor: number) => BigNumber;
|
|
37
|
+
/**
|
|
38
|
+
* Render a {@link BigNumber} (or JS number) to a string at `precision` significant digits.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* - An EXACT INTEGER is rendered in full fixed notation regardless of `precision`: an integer
|
|
42
|
+
* carries no fractional precision to lose, so `8000000000000` stays `8000000000000` rather than
|
|
43
|
+
* being truncated to `8e+12`. (Bounded at 30 digits to avoid pathological astronomically-large
|
|
44
|
+
* integers printing thousands of characters; beyond that, sig-fig exponential is used.)
|
|
45
|
+
* - Non-integers are rendered at `precision` significant digits (default 8), stripping trailing
|
|
46
|
+
* zeros — avoiding the `toPrecision` artifact that mangled safe values, while still giving the
|
|
47
|
+
* caller control over how many digits they want (raise `precision` for more).
|
|
48
|
+
* - Exact zero renders as `'0'`. (Genuinely tiny values like `2.54e-5` are preserved, NOT snapped.)
|
|
49
|
+
*/
|
|
50
|
+
export declare const formatBig: (value: BigNumber | number, precision?: number) => string;
|
|
51
|
+
/** Convert a {@link BigNumber} back to a JS number (for cases that must hand off a float64). */
|
|
52
|
+
export declare const bigToNumber: (b: BigNumber) => number;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { all, create } from "mathjs";
|
|
2
|
+
//#region src/lib/helpers/bignum.ts
|
|
3
|
+
/**
|
|
4
|
+
* Arbitrary-precision numeric helpers for the bundled tools.
|
|
5
|
+
*
|
|
6
|
+
* @module @nhtio/adk/lib/helpers/bignum
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* ECMAScript numbers are IEEE-754 float64: arithmetic on user-supplied values can overflow to
|
|
10
|
+
* `Infinity`, underflow to `0`, or silently lose precision (`0.1 + 0.2 === 0.30000000000000004`).
|
|
11
|
+
* The numeric tool batteries (`statistics`, `data_structure`, `unit_conversion`, `math`) route
|
|
12
|
+
* their aggregations and result formatting through this module so that:
|
|
13
|
+
*
|
|
14
|
+
* - large in-range sums stay exact instead of overflowing (`sum([1e308, 1e308]) → 2e308`),
|
|
15
|
+
* - precision is preserved end-to-end (`sum([0.1, 0.2]) → 0.3`),
|
|
16
|
+
* - output is rendered to a caller-chosen number of significant digits (default 8) without the
|
|
17
|
+
* lossy `Number.prototype.toPrecision`/`toFixed` round-trip that mangles even safe integers
|
|
18
|
+
* (e.g. `9007199254740991` rendered as `9007199255000`).
|
|
19
|
+
*
|
|
20
|
+
* Internally this is backed by a single {@link https://mathjs.org | mathjs} instance configured
|
|
21
|
+
* for `BigNumber` (which bundles `decimal.js`) at 64 significant digits — comfortably more than
|
|
22
|
+
* float64's ~15-17 and enough for the tools' needs without unbounded growth.
|
|
23
|
+
*
|
|
24
|
+
* The tools still RECEIVE float64 numbers (the model's tool-call arguments are JSON-parsed to
|
|
25
|
+
* float64 upstream, and the typed-array input schemas reject `NaN`/`Infinity`/`> 2^53` before the
|
|
26
|
+
* handler runs). BigNumber's job is the math and formatting in between, not the input boundary.
|
|
27
|
+
*/
|
|
28
|
+
/**
|
|
29
|
+
* Precision (significant digits) the internal BigNumber engine computes with. Distinct from the
|
|
30
|
+
* per-call display precision passed to {@link formatBig} — this is the working precision so that
|
|
31
|
+
* intermediate results don't accumulate rounding error before they are formatted down.
|
|
32
|
+
*/
|
|
33
|
+
var WORKING_PRECISION = 64;
|
|
34
|
+
/** Default display precision (significant digits) for tool output. */
|
|
35
|
+
var DEFAULT_PRECISION = 8;
|
|
36
|
+
var math = create(all, {
|
|
37
|
+
number: "BigNumber",
|
|
38
|
+
precision: WORKING_PRECISION
|
|
39
|
+
});
|
|
40
|
+
/** Coerce a JS number to a {@link BigNumber}. Non-finite inputs are a caller bug (schemas reject them). */
|
|
41
|
+
var toBig = (n) => math.bignumber(n);
|
|
42
|
+
/** Exact sum of a numeric array as a {@link BigNumber} (no float64 overflow/precision loss). */
|
|
43
|
+
var bigSum = (nums) => nums.reduce((acc, n) => math.add(acc, math.bignumber(n)), math.bignumber(0));
|
|
44
|
+
/** Exact arithmetic mean as a {@link BigNumber}. Caller guarantees `nums.length > 0`. */
|
|
45
|
+
var bigMean = (nums) => math.divide(bigSum(nums), nums.length);
|
|
46
|
+
/** `value * fromFactor / toFactor` computed without intermediate float64 over/underflow. */
|
|
47
|
+
var bigScale = (value, fromFactor, toFactor) => math.divide(math.multiply(math.bignumber(value), math.bignumber(fromFactor)), math.bignumber(toFactor));
|
|
48
|
+
/**
|
|
49
|
+
* Render a {@link BigNumber} (or JS number) to a string at `precision` significant digits.
|
|
50
|
+
*
|
|
51
|
+
* @remarks
|
|
52
|
+
* - An EXACT INTEGER is rendered in full fixed notation regardless of `precision`: an integer
|
|
53
|
+
* carries no fractional precision to lose, so `8000000000000` stays `8000000000000` rather than
|
|
54
|
+
* being truncated to `8e+12`. (Bounded at 30 digits to avoid pathological astronomically-large
|
|
55
|
+
* integers printing thousands of characters; beyond that, sig-fig exponential is used.)
|
|
56
|
+
* - Non-integers are rendered at `precision` significant digits (default 8), stripping trailing
|
|
57
|
+
* zeros — avoiding the `toPrecision` artifact that mangled safe values, while still giving the
|
|
58
|
+
* caller control over how many digits they want (raise `precision` for more).
|
|
59
|
+
* - Exact zero renders as `'0'`. (Genuinely tiny values like `2.54e-5` are preserved, NOT snapped.)
|
|
60
|
+
*/
|
|
61
|
+
var formatBig = (value, precision = 8) => {
|
|
62
|
+
const b = typeof value === "number" ? math.bignumber(value) : value;
|
|
63
|
+
if (math.equal(b, 0)) return "0";
|
|
64
|
+
const p = Number.isFinite(precision) ? Math.max(1, Math.min(64, Math.floor(precision))) : 8;
|
|
65
|
+
const fixed = math.format(b, { notation: "fixed" });
|
|
66
|
+
if (!fixed.includes(".") && fixed.replace("-", "").length <= 31) return fixed;
|
|
67
|
+
return math.format(b, { precision: p });
|
|
68
|
+
};
|
|
69
|
+
/** Convert a {@link BigNumber} back to a JS number (for cases that must hand off a float64). */
|
|
70
|
+
var bigToNumber = (b) => math.number(b);
|
|
71
|
+
//#endregion
|
|
72
|
+
export { DEFAULT_PRECISION, bigMean, bigScale, bigSum, bigToNumber, formatBig, toBig };
|
|
73
|
+
|
|
74
|
+
//# sourceMappingURL=bignum.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bignum.mjs","names":[],"sources":["../../../src/lib/helpers/bignum.ts"],"sourcesContent":["/**\n * Arbitrary-precision numeric helpers for the bundled tools.\n *\n * @module @nhtio/adk/lib/helpers/bignum\n *\n * @remarks\n * ECMAScript numbers are IEEE-754 float64: arithmetic on user-supplied values can overflow to\n * `Infinity`, underflow to `0`, or silently lose precision (`0.1 + 0.2 === 0.30000000000000004`).\n * The numeric tool batteries (`statistics`, `data_structure`, `unit_conversion`, `math`) route\n * their aggregations and result formatting through this module so that:\n *\n * - large in-range sums stay exact instead of overflowing (`sum([1e308, 1e308]) → 2e308`),\n * - precision is preserved end-to-end (`sum([0.1, 0.2]) → 0.3`),\n * - output is rendered to a caller-chosen number of significant digits (default 8) without the\n * lossy `Number.prototype.toPrecision`/`toFixed` round-trip that mangles even safe integers\n * (e.g. `9007199254740991` rendered as `9007199255000`).\n *\n * Internally this is backed by a single {@link https://mathjs.org | mathjs} instance configured\n * for `BigNumber` (which bundles `decimal.js`) at 64 significant digits — comfortably more than\n * float64's ~15-17 and enough for the tools' needs without unbounded growth.\n *\n * The tools still RECEIVE float64 numbers (the model's tool-call arguments are JSON-parsed to\n * float64 upstream, and the typed-array input schemas reject `NaN`/`Infinity`/`> 2^53` before the\n * handler runs). BigNumber's job is the math and formatting in between, not the input boundary.\n */\n\nimport { create, all, type BigNumber } from 'mathjs'\n\n/**\n * Precision (significant digits) the internal BigNumber engine computes with. Distinct from the\n * per-call display precision passed to {@link formatBig} — this is the working precision so that\n * intermediate results don't accumulate rounding error before they are formatted down.\n */\nconst WORKING_PRECISION = 64\n\n/** Default display precision (significant digits) for tool output. */\nexport const DEFAULT_PRECISION = 8\n\nconst math = create(all, { number: 'BigNumber', precision: WORKING_PRECISION })\n\n/** Coerce a JS number to a {@link BigNumber}. Non-finite inputs are a caller bug (schemas reject them). */\nexport const toBig = (n: number): BigNumber => math.bignumber(n)\n\n/** Exact sum of a numeric array as a {@link BigNumber} (no float64 overflow/precision loss). */\nexport const bigSum = (nums: number[]): BigNumber =>\n nums.reduce<BigNumber>((acc, n) => math.add(acc, math.bignumber(n)), math.bignumber(0))\n\n/** Exact arithmetic mean as a {@link BigNumber}. Caller guarantees `nums.length > 0`. */\nexport const bigMean = (nums: number[]): BigNumber =>\n math.divide(bigSum(nums), nums.length) as BigNumber\n\n/** `value * fromFactor / toFactor` computed without intermediate float64 over/underflow. */\nexport const bigScale = (value: number, fromFactor: number, toFactor: number): BigNumber =>\n math.divide(\n math.multiply(math.bignumber(value), math.bignumber(fromFactor)),\n math.bignumber(toFactor)\n ) as BigNumber\n\n/**\n * Render a {@link BigNumber} (or JS number) to a string at `precision` significant digits.\n *\n * @remarks\n * - An EXACT INTEGER is rendered in full fixed notation regardless of `precision`: an integer\n * carries no fractional precision to lose, so `8000000000000` stays `8000000000000` rather than\n * being truncated to `8e+12`. (Bounded at 30 digits to avoid pathological astronomically-large\n * integers printing thousands of characters; beyond that, sig-fig exponential is used.)\n * - Non-integers are rendered at `precision` significant digits (default 8), stripping trailing\n * zeros — avoiding the `toPrecision` artifact that mangled safe values, while still giving the\n * caller control over how many digits they want (raise `precision` for more).\n * - Exact zero renders as `'0'`. (Genuinely tiny values like `2.54e-5` are preserved, NOT snapped.)\n */\nexport const formatBig = (\n value: BigNumber | number,\n precision: number = DEFAULT_PRECISION\n): string => {\n const b = typeof value === 'number' ? math.bignumber(value) : value\n if (math.equal(b, 0)) return '0'\n const p = Number.isFinite(precision)\n ? Math.max(1, Math.min(64, Math.floor(precision)))\n : DEFAULT_PRECISION\n // Exact integers up to 30 digits: print in full, no precision truncation, no exponent. The\n // fixed-notation full string is the source of truth for \"is this an exact integer\" — mathjs's\n // `isInteger` is unreliable for Decimals carrying a fractional part under some configs.\n const fixed = math.format(b, { notation: 'fixed' })\n if (!fixed.includes('.') && fixed.replace('-', '').length <= 31) {\n return fixed\n }\n return math.format(b, { precision: p })\n}\n\n/** Convert a {@link BigNumber} back to a JS number (for cases that must hand off a float64). */\nexport const bigToNumber = (b: BigNumber): number => math.number(b)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,oBAAoB;;AAG1B,IAAa,oBAAoB;AAEjC,IAAM,OAAO,OAAO,KAAK;CAAE,QAAQ;CAAa,WAAW;AAAkB,CAAC;;AAG9E,IAAa,SAAS,MAAyB,KAAK,UAAU,CAAC;;AAG/D,IAAa,UAAU,SACrB,KAAK,QAAmB,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,UAAU,CAAC,CAAC,GAAG,KAAK,UAAU,CAAC,CAAC;;AAGxF,IAAa,WAAW,SACtB,KAAK,OAAO,OAAO,IAAI,GAAG,KAAK,MAAM;;AAGvC,IAAa,YAAY,OAAe,YAAoB,aAC1D,KAAK,OACH,KAAK,SAAS,KAAK,UAAU,KAAK,GAAG,KAAK,UAAU,UAAU,CAAC,GAC/D,KAAK,UAAU,QAAQ,CACzB;;;;;;;;;;;;;;AAeF,IAAa,aACX,OACA,YAAA,MACW;CACX,MAAM,IAAI,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI;CAC9D,IAAI,KAAK,MAAM,GAAG,CAAC,GAAG,OAAO;CAC7B,MAAM,IAAI,OAAO,SAAS,SAAS,IAC/B,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS,CAAC,CAAC,IAAA;CAKnD,MAAM,QAAQ,KAAK,OAAO,GAAG,EAAE,UAAU,QAAQ,CAAC;CAClD,IAAI,CAAC,MAAM,SAAS,GAAG,KAAK,MAAM,QAAQ,KAAK,EAAE,EAAE,UAAU,IAC3D,OAAO;CAET,OAAO,KAAK,OAAO,GAAG,EAAE,WAAW,EAAE,CAAC;AACxC;;AAGA,IAAa,eAAe,MAAyB,KAAK,OAAO,CAAC"}
|
package/lib/turn_runner.d.ts
CHANGED
|
@@ -63,7 +63,7 @@ export declare class TurnRunner {
|
|
|
63
63
|
*/
|
|
64
64
|
static isTurnRunner(value: unknown): value is TurnRunner;
|
|
65
65
|
/**
|
|
66
|
-
* @param config - Construction-time configuration validated against
|
|
66
|
+
* @param config - Construction-time configuration validated against the turn-runner config schema.
|
|
67
67
|
* @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.
|
|
68
68
|
*/
|
|
69
69
|
constructor(config: TurnRunnerConfig);
|
|
@@ -118,6 +118,24 @@ export interface DispatchExecutorHelpers {
|
|
|
118
118
|
* warnings, context-window perBucket breakdowns. Use it instead of `console.*`.
|
|
119
119
|
*/
|
|
120
120
|
log: DispatchExecutorLogChannel;
|
|
121
|
+
/**
|
|
122
|
+
* Emit a provider-agnostic {@link GenerationStats} record for the generation that just
|
|
123
|
+
* completed this iteration (token usage, wall-clock durations, finish reason).
|
|
124
|
+
*
|
|
125
|
+
* @remarks
|
|
126
|
+
* A dedicated egress for *generation accounting*, distinct from the diagnostic `log` channel:
|
|
127
|
+
* subscribers (cost meters, latency dashboards, token-budget guards) listen on the runner's
|
|
128
|
+
* `generationStats` observability hook without string-matching a log `kind`. The runner
|
|
129
|
+
* enriches every emission with the active `dispatchId` and 0-based `iteration` index, mirroring
|
|
130
|
+
* {@link DispatchExecutorHelpers.log}.
|
|
131
|
+
*
|
|
132
|
+
* Emit-only and side-effect-only — like `log`, it never throws, never mutates the
|
|
133
|
+
* {@link @nhtio/adk!DispatchContext}, and never participates in ack / nack flow. Every field on
|
|
134
|
+
* {@link GenerationStats} is optional, so a provider supplies only what its wire format reports
|
|
135
|
+
* (e.g. OpenAI surfaces token counts but no durations; Ollama surfaces both). Call it at most
|
|
136
|
+
* once per generation, after the response (or stream) has settled.
|
|
137
|
+
*/
|
|
138
|
+
reportGenerationStats(stats: GenerationStats): void;
|
|
121
139
|
}
|
|
122
140
|
/**
|
|
123
141
|
* Severity of a structured log event emitted by an executor via {@link DispatchExecutorHelpers.log}.
|
|
@@ -190,6 +208,63 @@ export interface LogEvent {
|
|
|
190
208
|
/** Optional structured detail block. */
|
|
191
209
|
payload?: Record<string, unknown>;
|
|
192
210
|
}
|
|
211
|
+
/**
|
|
212
|
+
* Provider-agnostic generation accounting for a single completed generation, emitted via
|
|
213
|
+
* {@link DispatchExecutorHelpers.reportGenerationStats}.
|
|
214
|
+
*
|
|
215
|
+
* @remarks
|
|
216
|
+
* Every field is optional so each battery supplies only what its wire format reports — OpenAI
|
|
217
|
+
* Chat Completions surfaces token counts (its `usage` block) but no wall-clock durations; Ollama's
|
|
218
|
+
* native `/api/chat` surfaces both token counts and nanosecond durations on its terminal chunk.
|
|
219
|
+
*
|
|
220
|
+
* Durations are carried in their **native nanosecond** unit (the `Ns` suffix is load-bearing) and
|
|
221
|
+
* are never normalised here — normalising to milliseconds would be lossy and providers without
|
|
222
|
+
* durations would gain meaningless zeros. `raw` preserves the full provider-native stats object
|
|
223
|
+
* verbatim for forward-compatibility, so a subscriber can read a field this shape has not yet
|
|
224
|
+
* promoted to a typed member.
|
|
225
|
+
*/
|
|
226
|
+
export interface GenerationStats {
|
|
227
|
+
/** Tokens in the prompt / input (OpenAI `usage.prompt_tokens`, Ollama `prompt_eval_count`). */
|
|
228
|
+
promptTokens?: number;
|
|
229
|
+
/** Tokens in the completion / output (OpenAI `usage.completion_tokens`, Ollama `eval_count`). */
|
|
230
|
+
completionTokens?: number;
|
|
231
|
+
/** Total tokens, when the provider reports a combined figure. */
|
|
232
|
+
totalTokens?: number;
|
|
233
|
+
/** Total wall-clock generation time in nanoseconds (Ollama `total_duration`). */
|
|
234
|
+
totalDurationNs?: number;
|
|
235
|
+
/** Time spent loading the model in nanoseconds (Ollama `load_duration`). */
|
|
236
|
+
loadDurationNs?: number;
|
|
237
|
+
/** Time spent evaluating the prompt in nanoseconds (Ollama `prompt_eval_duration`). */
|
|
238
|
+
promptEvalDurationNs?: number;
|
|
239
|
+
/** Time spent generating the response in nanoseconds (Ollama `eval_duration`). */
|
|
240
|
+
evalDurationNs?: number;
|
|
241
|
+
/** Why generation stopped (Ollama `done_reason`, OpenAI `finish_reason`). */
|
|
242
|
+
finishReason?: string;
|
|
243
|
+
/** Model identifier the provider echoed back. */
|
|
244
|
+
model?: string;
|
|
245
|
+
/** Stable provider discriminator (e.g. `'ollama'`, `'openai_chat_completions'`). */
|
|
246
|
+
provider?: string;
|
|
247
|
+
/** Full provider-native stats object, verbatim, for forward-compatibility. */
|
|
248
|
+
raw?: Record<string, unknown>;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Payload fired on the observability `generationStats` hook for every record emitted via
|
|
252
|
+
* {@link DispatchExecutorHelpers.reportGenerationStats}.
|
|
253
|
+
*
|
|
254
|
+
* @remarks
|
|
255
|
+
* The runner enriches the executor-supplied {@link GenerationStats} with the active `dispatchId`
|
|
256
|
+
* and 0-based `iteration` index (and an `emittedAt` timestamp) so subscribers can correlate stats
|
|
257
|
+
* across multiple in-flight dispatches without threading extra context — exactly as {@link LogEvent}
|
|
258
|
+
* does for the `log` channel.
|
|
259
|
+
*/
|
|
260
|
+
export interface GenerationStatsEvent extends GenerationStats {
|
|
261
|
+
/** Stable identifier for the dispatch that produced the event. */
|
|
262
|
+
dispatchId: string;
|
|
263
|
+
/** 0-based iteration index within the dispatch. */
|
|
264
|
+
iteration: number;
|
|
265
|
+
/** When the event was emitted. */
|
|
266
|
+
emittedAt: DateTime;
|
|
267
|
+
}
|
|
193
268
|
/**
|
|
194
269
|
* The user-supplied callback that performs the actual LLM API call within a dispatch.
|
|
195
270
|
*
|
|
@@ -372,6 +447,14 @@ export type DispatchRunnerObservabilityHooks = {
|
|
|
372
447
|
[
|
|
373
448
|
]
|
|
374
449
|
];
|
|
450
|
+
/** Fired for every generation-stats record emitted via {@link DispatchExecutorHelpers.reportGenerationStats}. */
|
|
451
|
+
generationStats: [
|
|
452
|
+
[
|
|
453
|
+
GenerationStatsEvent
|
|
454
|
+
],
|
|
455
|
+
[
|
|
456
|
+
]
|
|
457
|
+
];
|
|
375
458
|
};
|
|
376
459
|
/**
|
|
377
460
|
* Optional functional hook registrations supplied to {@link @nhtio/adk!DispatchRunner.dispatch}.
|
|
@@ -36,7 +36,7 @@ export type CreatedException<T extends any[] = [
|
|
|
36
36
|
* @typeParam T - Tuple of printf format argument types. Pass a non-empty tuple to require
|
|
37
37
|
* callers to supply interpolation values at the throw site.
|
|
38
38
|
*
|
|
39
|
-
* @param name - The `name` property set on thrown instances (used by
|
|
39
|
+
* @param name - The `name` property set on thrown instances (used by `isNamedException`).
|
|
40
40
|
* @param message - Printf-style template string for the error message.
|
|
41
41
|
* @param code - Machine-readable error code stored on the static and instance `code` property.
|
|
42
42
|
* @param status - HTTP status code associated with this exception class.
|
package/lib/utils/retry.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.cjs","names":[],"sources":["../../../src/lib/utils/retry.ts"],"sourcesContent":["/**\n * Environment-neutral retry/backoff/timeout primitives shared across HTTP-backed batteries.\n *\n * @module @nhtio/adk/lib/utils/retry\n *\n * @remarks\n * These are pure helpers — no DOM, no Node built-ins, only `setTimeout`, `AbortController`, and\n * `AbortSignal`, all of which exist in every target runtime (Node, browser, edge, workers). They\n * are shared (not duplicated) by the OpenAI Chat Completions battery and the OpenAI Embeddings\n * battery so retry behavior stays identical across the bundled batteries. The bundler inlines this\n * module into each consumer, so sharing introduces no build coupling.\n */\n\n/**\n * Minimal backoff configuration shape. Any retry config carrying `baseDelayMs`/`maxDelayMs`\n * satisfies it structurally, so batteries can pass their own richer config objects directly.\n */\nexport interface BackoffConfig {\n baseDelayMs?: number\n maxDelayMs?: number\n}\n\n/**\n * Exponential backoff with a ceiling: `min(baseDelayMs * 2^(attempt-1), maxDelayMs)`.\n *\n * @param attempt - 1-based attempt number.\n * @param cfg - Carries `baseDelayMs` (default 500) and `maxDelayMs` (default 30_000).\n * @returns The (un-jittered) delay in ms.\n */\nexport const computeBackoff = (attempt: number, cfg: BackoffConfig): number => {\n const base = cfg.baseDelayMs ?? 500\n const max = cfg.maxDelayMs ?? 30_000\n return Math.min(base * Math.pow(2, attempt - 1), max)\n}\n\n/**\n * Abort-aware jittered sleep used for retry backoff.\n *\n * @remarks\n * Resolves (never rejects) the instant `signal` aborts, so an aborted caller does not stay parked\n * in a backoff delay — the caller's retry loop re-checks abort state immediately after and bails.\n * The timer and the abort listener are both torn down on whichever fires first, so nothing leaks.\n *\n * @param ms - Base delay in ms; jittered by ±10%.\n * @param signal - Optional abort signal that short-circuits the sleep.\n */\nexport const sleepWithJitter = (ms: number, signal?: AbortSignal): Promise<void> => {\n const jittered = ms * (0.9 + Math.random() * 0.2)\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, jittered)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Parses an HTTP `Retry-After` header value (delta-seconds or HTTP-date) into milliseconds.\n *\n * @param raw - The header value.\n * @returns Milliseconds to wait, or `0` when the value cannot be parsed or is in the past.\n */\nexport const parseRetryAfter = (raw: string): number => {\n const asNum = Number(raw)\n if (Number.isFinite(asNum)) return asNum * 1000\n const asDate = Date.parse(raw)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return 0\n}\n\n/**\n * Combines several abort signals into one.\n *\n * @remarks\n * Returns the linked signal plus a `dispose` that detaches any listeners the fallback path\n * attached, so repeated links on a long-lived signal (one per retry attempt) do not accumulate\n * listeners. The native `AbortSignal.any` path self-manages its listeners, so `dispose` is a no-op\n * there.\n *\n * @param signals - The signals to combine.\n * @returns The linked signal and a `dispose` to tear down fallback listeners.\n */\nexport const linkAbortSignals = (\n signals: ReadonlyArray<AbortSignal>\n): { signal: AbortSignal; dispose: () => void } => {\n const anyFn = (AbortSignal as unknown as { any?: (sigs: AbortSignal[]) => AbortSignal }).any\n if (typeof anyFn === 'function') {\n return { signal: anyFn(signals as AbortSignal[]), dispose: () => {} }\n }\n // Fallback for older runtimes: hand-link via a fresh controller.\n const ctrl = new AbortController()\n const links: Array<{ sig: AbortSignal; handler: () => void }> = []\n for (const sig of signals) {\n if (sig.aborted) {\n ctrl.abort()\n break\n }\n const handler = () => ctrl.abort()\n sig.addEventListener('abort', handler, { once: true })\n links.push({ sig, handler })\n }\n return {\n signal: ctrl.signal,\n dispose: () => {\n for (const { sig, handler } of links) sig.removeEventListener('abort', handler)\n links.length = 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"retry.cjs","names":[],"sources":["../../../src/lib/utils/retry.ts"],"sourcesContent":["/**\n * Environment-neutral retry/backoff/timeout primitives shared across HTTP-backed batteries.\n *\n * @module @nhtio/adk/lib/utils/retry\n *\n * @remarks\n * These are pure helpers — no DOM, no Node built-ins, only `setTimeout`, `AbortController`, and\n * `AbortSignal`, all of which exist in every target runtime (Node, browser, edge, workers). They\n * are shared (not duplicated) by the OpenAI Chat Completions battery and the OpenAI Embeddings\n * battery so retry behavior stays identical across the bundled batteries. The bundler inlines this\n * module into each consumer, so sharing introduces no build coupling.\n */\n\n/**\n * Minimal backoff configuration shape. Any retry config carrying `baseDelayMs`/`maxDelayMs`\n * satisfies it structurally, so batteries can pass their own richer config objects directly.\n */\nexport interface BackoffConfig {\n /** Base delay in milliseconds for the first retry; doubles each attempt (default 500). */\n baseDelayMs?: number\n /** Upper bound in milliseconds on any single backoff delay (default 30_000). */\n maxDelayMs?: number\n}\n\n/**\n * Exponential backoff with a ceiling: `min(baseDelayMs * 2^(attempt-1), maxDelayMs)`.\n *\n * @param attempt - 1-based attempt number.\n * @param cfg - Carries `baseDelayMs` (default 500) and `maxDelayMs` (default 30_000).\n * @returns The (un-jittered) delay in ms.\n */\nexport const computeBackoff = (attempt: number, cfg: BackoffConfig): number => {\n const base = cfg.baseDelayMs ?? 500\n const max = cfg.maxDelayMs ?? 30_000\n return Math.min(base * Math.pow(2, attempt - 1), max)\n}\n\n/**\n * Abort-aware jittered sleep used for retry backoff.\n *\n * @remarks\n * Resolves (never rejects) the instant `signal` aborts, so an aborted caller does not stay parked\n * in a backoff delay — the caller's retry loop re-checks abort state immediately after and bails.\n * The timer and the abort listener are both torn down on whichever fires first, so nothing leaks.\n *\n * @param ms - Base delay in ms; jittered by ±10%.\n * @param signal - Optional abort signal that short-circuits the sleep.\n */\nexport const sleepWithJitter = (ms: number, signal?: AbortSignal): Promise<void> => {\n const jittered = ms * (0.9 + Math.random() * 0.2)\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, jittered)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Parses an HTTP `Retry-After` header value (delta-seconds or HTTP-date) into milliseconds.\n *\n * @param raw - The header value.\n * @returns Milliseconds to wait, or `0` when the value cannot be parsed or is in the past.\n */\nexport const parseRetryAfter = (raw: string): number => {\n const asNum = Number(raw)\n if (Number.isFinite(asNum)) return asNum * 1000\n const asDate = Date.parse(raw)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return 0\n}\n\n/**\n * Combines several abort signals into one.\n *\n * @remarks\n * Returns the linked signal plus a `dispose` that detaches any listeners the fallback path\n * attached, so repeated links on a long-lived signal (one per retry attempt) do not accumulate\n * listeners. The native `AbortSignal.any` path self-manages its listeners, so `dispose` is a no-op\n * there.\n *\n * @param signals - The signals to combine.\n * @returns The linked signal and a `dispose` to tear down fallback listeners.\n */\nexport const linkAbortSignals = (\n signals: ReadonlyArray<AbortSignal>\n): { signal: AbortSignal; dispose: () => void } => {\n const anyFn = (AbortSignal as unknown as { any?: (sigs: AbortSignal[]) => AbortSignal }).any\n if (typeof anyFn === 'function') {\n return { signal: anyFn(signals as AbortSignal[]), dispose: () => {} }\n }\n // Fallback for older runtimes: hand-link via a fresh controller.\n const ctrl = new AbortController()\n const links: Array<{ sig: AbortSignal; handler: () => void }> = []\n for (const sig of signals) {\n if (sig.aborted) {\n ctrl.abort()\n break\n }\n const handler = () => ctrl.abort()\n sig.addEventListener('abort', handler, { once: true })\n links.push({ sig, handler })\n }\n return {\n signal: ctrl.signal,\n dispose: () => {\n for (const { sig, handler } of links) sig.removeEventListener('abort', handler)\n links.length = 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA+BA,IAAa,kBAAkB,SAAiB,QAA+B;CAC7E,MAAM,OAAO,IAAI,eAAe;CAChC,MAAM,MAAM,IAAI,cAAc;CAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,IAAI,GAAG,UAAU,CAAC,GAAG,GAAG;AACtD;;;;;;;;;;;;AAaA,IAAa,mBAAmB,IAAY,WAAwC;CAClF,MAAM,WAAW,MAAM,KAAM,KAAK,OAAO,IAAI;CAC7C,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,QAAQ,SAAS;GACnB,QAAQ;GACR;EACF;EACA,IAAI;EACJ,MAAM,QAAQ,iBAAiB;GAC7B,IAAI,WAAW,QAAQ,OAAO,oBAAoB,SAAS,OAAO;GAClE,QAAQ;EACV,GAAG,QAAQ;EACX,IAAI,QAAQ;GACV,gBAAgB;IACd,aAAa,KAAK;IAClB,QAAQ;GACV;GACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D;CACF,CAAC;AACH;;;;;;;AAQA,IAAa,mBAAmB,QAAwB;CACtD,MAAM,QAAQ,OAAO,GAAG;CACxB,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,QAAQ;CAC3C,MAAM,SAAS,KAAK,MAAM,GAAG;CAC7B,IAAI,OAAO,SAAS,MAAM,GAAG,OAAO,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;CACnE,OAAO;AACT;;;;;;;;;;;;;AAcA,IAAa,oBACX,YACiD;CACjD,MAAM,QAAS,YAA0E;CACzF,IAAI,OAAO,UAAU,YACnB,OAAO;EAAE,QAAQ,MAAM,OAAwB;EAAG,eAAe,CAAC;CAAE;CAGtE,MAAM,OAAO,IAAI,gBAAgB;CACjC,MAAM,QAA0D,CAAC;CACjE,KAAK,MAAM,OAAO,SAAS;EACzB,IAAI,IAAI,SAAS;GACf,KAAK,MAAM;GACX;EACF;EACA,MAAM,gBAAgB,KAAK,MAAM;EACjC,IAAI,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACrD,MAAM,KAAK;GAAE;GAAK;EAAQ,CAAC;CAC7B;CACA,OAAO;EACL,QAAQ,KAAK;EACb,eAAe;GACb,KAAK,MAAM,EAAE,KAAK,aAAa,OAAO,IAAI,oBAAoB,SAAS,OAAO;GAC9E,MAAM,SAAS;EACjB;CACF;AACF"}
|
package/lib/utils/retry.d.ts
CHANGED
|
@@ -15,7 +15,9 @@
|
|
|
15
15
|
* satisfies it structurally, so batteries can pass their own richer config objects directly.
|
|
16
16
|
*/
|
|
17
17
|
export interface BackoffConfig {
|
|
18
|
+
/** Base delay in milliseconds for the first retry; doubles each attempt (default 500). */
|
|
18
19
|
baseDelayMs?: number;
|
|
20
|
+
/** Upper bound in milliseconds on any single backoff delay (default 30_000). */
|
|
19
21
|
maxDelayMs?: number;
|
|
20
22
|
}
|
|
21
23
|
/**
|
package/lib/utils/retry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.mjs","names":[],"sources":["../../../src/lib/utils/retry.ts"],"sourcesContent":["/**\n * Environment-neutral retry/backoff/timeout primitives shared across HTTP-backed batteries.\n *\n * @module @nhtio/adk/lib/utils/retry\n *\n * @remarks\n * These are pure helpers — no DOM, no Node built-ins, only `setTimeout`, `AbortController`, and\n * `AbortSignal`, all of which exist in every target runtime (Node, browser, edge, workers). They\n * are shared (not duplicated) by the OpenAI Chat Completions battery and the OpenAI Embeddings\n * battery so retry behavior stays identical across the bundled batteries. The bundler inlines this\n * module into each consumer, so sharing introduces no build coupling.\n */\n\n/**\n * Minimal backoff configuration shape. Any retry config carrying `baseDelayMs`/`maxDelayMs`\n * satisfies it structurally, so batteries can pass their own richer config objects directly.\n */\nexport interface BackoffConfig {\n baseDelayMs?: number\n maxDelayMs?: number\n}\n\n/**\n * Exponential backoff with a ceiling: `min(baseDelayMs * 2^(attempt-1), maxDelayMs)`.\n *\n * @param attempt - 1-based attempt number.\n * @param cfg - Carries `baseDelayMs` (default 500) and `maxDelayMs` (default 30_000).\n * @returns The (un-jittered) delay in ms.\n */\nexport const computeBackoff = (attempt: number, cfg: BackoffConfig): number => {\n const base = cfg.baseDelayMs ?? 500\n const max = cfg.maxDelayMs ?? 30_000\n return Math.min(base * Math.pow(2, attempt - 1), max)\n}\n\n/**\n * Abort-aware jittered sleep used for retry backoff.\n *\n * @remarks\n * Resolves (never rejects) the instant `signal` aborts, so an aborted caller does not stay parked\n * in a backoff delay — the caller's retry loop re-checks abort state immediately after and bails.\n * The timer and the abort listener are both torn down on whichever fires first, so nothing leaks.\n *\n * @param ms - Base delay in ms; jittered by ±10%.\n * @param signal - Optional abort signal that short-circuits the sleep.\n */\nexport const sleepWithJitter = (ms: number, signal?: AbortSignal): Promise<void> => {\n const jittered = ms * (0.9 + Math.random() * 0.2)\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, jittered)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Parses an HTTP `Retry-After` header value (delta-seconds or HTTP-date) into milliseconds.\n *\n * @param raw - The header value.\n * @returns Milliseconds to wait, or `0` when the value cannot be parsed or is in the past.\n */\nexport const parseRetryAfter = (raw: string): number => {\n const asNum = Number(raw)\n if (Number.isFinite(asNum)) return asNum * 1000\n const asDate = Date.parse(raw)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return 0\n}\n\n/**\n * Combines several abort signals into one.\n *\n * @remarks\n * Returns the linked signal plus a `dispose` that detaches any listeners the fallback path\n * attached, so repeated links on a long-lived signal (one per retry attempt) do not accumulate\n * listeners. The native `AbortSignal.any` path self-manages its listeners, so `dispose` is a no-op\n * there.\n *\n * @param signals - The signals to combine.\n * @returns The linked signal and a `dispose` to tear down fallback listeners.\n */\nexport const linkAbortSignals = (\n signals: ReadonlyArray<AbortSignal>\n): { signal: AbortSignal; dispose: () => void } => {\n const anyFn = (AbortSignal as unknown as { any?: (sigs: AbortSignal[]) => AbortSignal }).any\n if (typeof anyFn === 'function') {\n return { signal: anyFn(signals as AbortSignal[]), dispose: () => {} }\n }\n // Fallback for older runtimes: hand-link via a fresh controller.\n const ctrl = new AbortController()\n const links: Array<{ sig: AbortSignal; handler: () => void }> = []\n for (const sig of signals) {\n if (sig.aborted) {\n ctrl.abort()\n break\n }\n const handler = () => ctrl.abort()\n sig.addEventListener('abort', handler, { once: true })\n links.push({ sig, handler })\n }\n return {\n signal: ctrl.signal,\n dispose: () => {\n for (const { sig, handler } of links) sig.removeEventListener('abort', handler)\n links.length = 0\n },\n }\n}\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"retry.mjs","names":[],"sources":["../../../src/lib/utils/retry.ts"],"sourcesContent":["/**\n * Environment-neutral retry/backoff/timeout primitives shared across HTTP-backed batteries.\n *\n * @module @nhtio/adk/lib/utils/retry\n *\n * @remarks\n * These are pure helpers — no DOM, no Node built-ins, only `setTimeout`, `AbortController`, and\n * `AbortSignal`, all of which exist in every target runtime (Node, browser, edge, workers). They\n * are shared (not duplicated) by the OpenAI Chat Completions battery and the OpenAI Embeddings\n * battery so retry behavior stays identical across the bundled batteries. The bundler inlines this\n * module into each consumer, so sharing introduces no build coupling.\n */\n\n/**\n * Minimal backoff configuration shape. Any retry config carrying `baseDelayMs`/`maxDelayMs`\n * satisfies it structurally, so batteries can pass their own richer config objects directly.\n */\nexport interface BackoffConfig {\n /** Base delay in milliseconds for the first retry; doubles each attempt (default 500). */\n baseDelayMs?: number\n /** Upper bound in milliseconds on any single backoff delay (default 30_000). */\n maxDelayMs?: number\n}\n\n/**\n * Exponential backoff with a ceiling: `min(baseDelayMs * 2^(attempt-1), maxDelayMs)`.\n *\n * @param attempt - 1-based attempt number.\n * @param cfg - Carries `baseDelayMs` (default 500) and `maxDelayMs` (default 30_000).\n * @returns The (un-jittered) delay in ms.\n */\nexport const computeBackoff = (attempt: number, cfg: BackoffConfig): number => {\n const base = cfg.baseDelayMs ?? 500\n const max = cfg.maxDelayMs ?? 30_000\n return Math.min(base * Math.pow(2, attempt - 1), max)\n}\n\n/**\n * Abort-aware jittered sleep used for retry backoff.\n *\n * @remarks\n * Resolves (never rejects) the instant `signal` aborts, so an aborted caller does not stay parked\n * in a backoff delay — the caller's retry loop re-checks abort state immediately after and bails.\n * The timer and the abort listener are both torn down on whichever fires first, so nothing leaks.\n *\n * @param ms - Base delay in ms; jittered by ±10%.\n * @param signal - Optional abort signal that short-circuits the sleep.\n */\nexport const sleepWithJitter = (ms: number, signal?: AbortSignal): Promise<void> => {\n const jittered = ms * (0.9 + Math.random() * 0.2)\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, jittered)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Parses an HTTP `Retry-After` header value (delta-seconds or HTTP-date) into milliseconds.\n *\n * @param raw - The header value.\n * @returns Milliseconds to wait, or `0` when the value cannot be parsed or is in the past.\n */\nexport const parseRetryAfter = (raw: string): number => {\n const asNum = Number(raw)\n if (Number.isFinite(asNum)) return asNum * 1000\n const asDate = Date.parse(raw)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return 0\n}\n\n/**\n * Combines several abort signals into one.\n *\n * @remarks\n * Returns the linked signal plus a `dispose` that detaches any listeners the fallback path\n * attached, so repeated links on a long-lived signal (one per retry attempt) do not accumulate\n * listeners. The native `AbortSignal.any` path self-manages its listeners, so `dispose` is a no-op\n * there.\n *\n * @param signals - The signals to combine.\n * @returns The linked signal and a `dispose` to tear down fallback listeners.\n */\nexport const linkAbortSignals = (\n signals: ReadonlyArray<AbortSignal>\n): { signal: AbortSignal; dispose: () => void } => {\n const anyFn = (AbortSignal as unknown as { any?: (sigs: AbortSignal[]) => AbortSignal }).any\n if (typeof anyFn === 'function') {\n return { signal: anyFn(signals as AbortSignal[]), dispose: () => {} }\n }\n // Fallback for older runtimes: hand-link via a fresh controller.\n const ctrl = new AbortController()\n const links: Array<{ sig: AbortSignal; handler: () => void }> = []\n for (const sig of signals) {\n if (sig.aborted) {\n ctrl.abort()\n break\n }\n const handler = () => ctrl.abort()\n sig.addEventListener('abort', handler, { once: true })\n links.push({ sig, handler })\n }\n return {\n signal: ctrl.signal,\n dispose: () => {\n for (const { sig, handler } of links) sig.removeEventListener('abort', handler)\n links.length = 0\n },\n }\n}\n"],"mappings":";;;;;;;;AA+BA,IAAa,kBAAkB,SAAiB,QAA+B;CAC7E,MAAM,OAAO,IAAI,eAAe;CAChC,MAAM,MAAM,IAAI,cAAc;CAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,IAAI,GAAG,UAAU,CAAC,GAAG,GAAG;AACtD;;;;;;;;;;;;AAaA,IAAa,mBAAmB,IAAY,WAAwC;CAClF,MAAM,WAAW,MAAM,KAAM,KAAK,OAAO,IAAI;CAC7C,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,QAAQ,SAAS;GACnB,QAAQ;GACR;EACF;EACA,IAAI;EACJ,MAAM,QAAQ,iBAAiB;GAC7B,IAAI,WAAW,QAAQ,OAAO,oBAAoB,SAAS,OAAO;GAClE,QAAQ;EACV,GAAG,QAAQ;EACX,IAAI,QAAQ;GACV,gBAAgB;IACd,aAAa,KAAK;IAClB,QAAQ;GACV;GACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D;CACF,CAAC;AACH;;;;;;;AAQA,IAAa,mBAAmB,QAAwB;CACtD,MAAM,QAAQ,OAAO,GAAG;CACxB,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,QAAQ;CAC3C,MAAM,SAAS,KAAK,MAAM,GAAG;CAC7B,IAAI,OAAO,SAAS,MAAM,GAAG,OAAO,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;CACnE,OAAO;AACT;;;;;;;;;;;;;AAcA,IAAa,oBACX,YACiD;CACjD,MAAM,QAAS,YAA0E;CACzF,IAAI,OAAO,UAAU,YACnB,OAAO;EAAE,QAAQ,MAAM,OAAwB;EAAG,eAAe,CAAC;CAAE;CAGtE,MAAM,OAAO,IAAI,gBAAgB;CACjC,MAAM,QAA0D,CAAC;CACjE,KAAK,MAAM,OAAO,SAAS;EACzB,IAAI,IAAI,SAAS;GACf,KAAK,MAAM;GACX;EACF;EACA,MAAM,gBAAgB,KAAK,MAAM;EACjC,IAAI,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACrD,MAAM,KAAK;GAAE;GAAK;EAAQ,CAAC;CAC7B;CACA,OAAO;EACL,QAAQ,KAAK;EACb,eAAe;GACb,KAAK,MAAM,EAAE,KAAK,aAAa,OAAO,IAAI,oBAAoB,SAAS,OAAO;GAC9E,MAAM,SAAS;EACjB;CACF;AACF"}
|