@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":"typesense.mjs","names":["#opts","#client","#ensure","#dims","#project","#parseMeta"],"sources":["../../../src/batteries/vector/typesense/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/typesense\n *\n * Typesense adapter. Each collection is a Typesense collection with a `float[]` vector field\n * (native `vector_query` KNN). Metadata is stored as a JSON string field and filtered with\n * the neutral filter tree's JS reference evaluator for exact cross-adapter parity (Typesense\n * filter_by requires per-field schema declaration, which the neutral metadata model doesn't\n * have). Document + id are plain fields.\n *\n * Driver: `typesense` (pure JS).\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { BaseVectorStore } from '../contract'\nimport { validateRecords } from '../validation'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport {\n E_VECTOR_STORE_DRIVER_UNAVAILABLE,\n E_VECTOR_STORE_CONNECTION_FAILED,\n E_VECTOR_STORE_COLLECTION_FAILED,\n E_VECTOR_STORE_UPSERT_FAILED,\n E_VECTOR_STORE_SEARCH_FAILED,\n E_VECTOR_STORE_DELETE_FAILED,\n E_VECTOR_STORE_DIMENSION_MISMATCH,\n E_VECTOR_STORE_UNSUPPORTED_OPERATION,\n} from '../exceptions'\nimport type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from '../plan'\nimport type {\n VectorMatch,\n VectorStoreCapabilities,\n BaseVectorStoreOptions,\n VectorMetadata,\n DistanceMetric,\n} from '../types'\n\nexport interface TypesenseVectorStoreOptions extends BaseVectorStoreOptions {\n connection?: {\n host?: string\n port?: number\n protocol?: string\n apiKey?: string\n url?: string\n }\n}\n\nconst getTypesense = async () => {\n try {\n const mod = await import('typesense')\n return (mod as any).default ?? mod\n } catch {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['typesense'])\n }\n}\n\nexport class TypesenseVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: false,\n namedVectors: false,\n rename: false,\n rawSql: false,\n builtInEncoding: false,\n // Typesense indexes writes synchronously (searchable on resolve). The option is a no-op.\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #client: any | null = null\n #dims: Map<string, number> = new Map()\n\n get #opts(): TypesenseVectorStoreOptions {\n return this.options as TypesenseVectorStoreOptions\n }\n\n static isAvailable(): boolean {\n return typeof process !== 'undefined'\n }\n isAvailable(): boolean {\n return typeof process !== 'undefined'\n }\n\n async connect(): Promise<void> {\n if (this.#client) return\n const Typesense = await getTypesense()\n const c = this.#opts.connection || {}\n let node: any\n if (c.url) {\n const u = new URL(c.url)\n node = {\n host: u.hostname,\n port: Number(u.port) || (u.protocol === 'https:' ? 443 : 8108),\n protocol: u.protocol.replace(':', ''),\n }\n } else {\n node = { host: c.host ?? 'localhost', port: c.port ?? 8108, protocol: c.protocol ?? 'http' }\n }\n try {\n this.#client = new Typesense.Client({\n nodes: [node],\n apiKey: c.apiKey ?? 'xyz',\n connectionTimeoutSeconds: 5,\n })\n } catch (err) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([String(err)])\n }\n }\n\n async close(): Promise<void> {\n this.#client = null\n }\n\n async #ensure(): Promise<any> {\n if (!this.#client) await this.connect()\n return this.#client!\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n const client = await this.#ensure()\n this.#dims.set(spec.collection, spec.vector.dimensions)\n if (ifNotExists && (await this.hasCollection(spec.collection))) return\n try {\n await client.collections().create({\n name: spec.collection,\n fields: [\n { name: 'id', type: 'string' },\n { name: 'vec', type: 'float[]', num_dim: spec.vector.dimensions },\n { name: 'document', type: 'string', optional: true },\n { name: 'metadata', type: 'string', optional: true },\n ],\n })\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['createCollection', String(err)])\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n const client = await this.#ensure()\n if (ifExists && !(await this.hasCollection(collection))) return\n try {\n await client.collections(collection).delete()\n this.#dims.delete(collection)\n } catch (err) {\n const msg = String(err)\n if (ifExists && msg.includes('Not Found')) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['dropCollection', msg])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n const client = await this.#ensure()\n try {\n await client.collections(collection).retrieve()\n return true\n } catch {\n return false\n }\n }\n\n async renameCollection(_from: string, _to: string): Promise<void> {\n throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(['renameCollection', 'typesense'])\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n if (plan.records.length === 0) return\n validateRecords(plan.records)\n const client = await this.#ensure()\n const expected = this.#opts.dimensions ?? this.#dims.get(plan.collection)\n try {\n const docs: any[] = []\n for (const r of plan.records) {\n let vector = r.vector\n if (!vector && r.document) {\n const [v] = await this.encode([r.document], 'document')\n vector = v\n }\n if (!vector) {\n throw new E_VECTOR_STORE_UPSERT_FAILED(['Record missing vector and document'])\n }\n if (expected !== undefined && vector.length !== expected) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([expected, vector.length])\n }\n docs.push({\n id: r.id,\n vec: vector,\n document: r.document ?? '',\n metadata: r.metadata ? JSON.stringify(r.metadata) : '{}',\n })\n }\n await client.collections(plan.collection).documents().import(docs, { action: 'upsert' })\n } catch (err) {\n if (\n isInstanceOf(err, 'E_VECTOR_STORE_DIMENSION_MISMATCH', E_VECTOR_STORE_DIMENSION_MISMATCH) ||\n isInstanceOf(err, 'E_VECTOR_STORE_UPSERT_FAILED', E_VECTOR_STORE_UPSERT_FAILED)\n ) {\n throw err\n }\n throw new E_VECTOR_STORE_UPSERT_FAILED([String(err)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n const client = await this.#ensure()\n const metric = this.#opts.metric ?? 'cosine'\n let queryVector: number[] | undefined\n if (plan.near) {\n if ('vector' in plan.near) {\n queryVector = plan.near.vector\n } else if ('serverText' in plan.near) {\n const [v] = await this.encode([plan.near.serverText], 'query')\n queryVector = v\n } else if ('id' in plan.near) {\n try {\n const doc = await client.collections(plan.collection).documents(plan.near.id).retrieve()\n queryVector = doc.vec as number[]\n } catch {\n queryVector = undefined\n }\n if (!queryVector) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n }\n }\n\n const offset = plan.offset ?? 0\n try {\n const coll = client.collections(plan.collection).documents()\n if (queryVector) {\n // Over-fetch then JS-filter for exact cross-adapter filter semantics.\n const k = Math.max(plan.topK + offset, plan.topK) + (plan.filter ? 250 : 0)\n const res = await coll.search({\n q: '*',\n vector_query: `vec:([${queryVector.join(',')}], k:${k})`,\n per_page: Math.min(250, k),\n })\n const hits = (res.hits ?? []) as any[]\n const mapped = hits.map((hit) => ({\n match: this.#project(hit.document, plan, metric, hit.vector_distance),\n meta: this.#parseMeta(hit.document.metadata),\n }))\n const filtered = plan.filter\n ? mapped.filter((m) => evaluateFilter(plan.filter!, m.meta))\n : mapped\n return filtered.slice(offset, offset + plan.topK).map((m) => m.match)\n } else {\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n const mapped = hits.map((hit) => ({\n match: this.#project(hit.document, plan, metric, undefined),\n meta: this.#parseMeta(hit.document.metadata),\n }))\n const filtered = plan.filter\n ? mapped.filter((m) => evaluateFilter(plan.filter!, m.meta))\n : mapped\n return filtered.slice(offset, offset + plan.topK).map((m) => m.match)\n }\n } catch (err) {\n throw new E_VECTOR_STORE_SEARCH_FAILED([String(err)])\n }\n }\n\n #parseMeta(val: unknown): VectorMetadata {\n if (typeof val === 'string') {\n try {\n return JSON.parse(val) as VectorMetadata\n } catch {\n return {}\n }\n }\n if (val && typeof val === 'object') return val as VectorMetadata\n return {}\n }\n\n #project(doc: any, plan: SearchPlan, metric: string, dist: number | undefined): VectorMatch {\n const proj = plan.projection\n const out: VectorMatch = {}\n if (proj.id) out.id = doc.id as string\n if (proj.vector && Array.isArray(doc.vec)) out.vector = doc.vec as number[]\n if (proj.document) out.document = (doc.document ?? undefined) as string | undefined\n if (proj.metadata) out.metadata = this.#parseMeta(doc.metadata)\n if (dist !== undefined && dist !== null) {\n out.score = normalizeScore(Number(dist), metric as DistanceMetric, 'distance')\n }\n return out\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n const client = await this.#ensure()\n const collection = client.collections(plan.collection)\n const coll = collection.documents()\n // Delete a single document by id: documents(id).delete() (NOT documents().delete(id),\n // which targets the bulk filter endpoint).\n const deleteOne = async (id: string): Promise<void> => {\n await collection\n .documents(id)\n .delete()\n .catch(() => undefined)\n }\n try {\n if (plan.ids && plan.ids.length > 0) {\n for (const id of plan.ids) await deleteOne(id)\n } else if (plan.filter) {\n // Resolve ids via a scan + JS evaluator, then delete by id.\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n const targets = hits\n .filter((hit) => evaluateFilter(plan.filter!, this.#parseMeta(hit.document.metadata)))\n .map((hit) => hit.document.id as string)\n for (const id of targets) await deleteOne(id)\n } else {\n // Delete-all: bulk delete by an always-true filter; fall back to per-id on error.\n try {\n await coll.delete({ filter_by: 'id:!= ' })\n } catch {\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n for (const hit of hits) await deleteOne(hit.document.id as string)\n }\n }\n } catch (err) {\n throw new E_VECTOR_STORE_DELETE_FAIL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AAK,MAAM,MAAM,KAAK,KAAK,MAAM,UAAU,EAAE;QACxC,IAAI,KAAK,QAAQ;IAItB,MAAM,YADQ,MADI,KAAK,OAAO;KAAE,GAAG;KAAK,UAAU;KAAY,UAAU;IAAI,CAAC,GAC3D,QAAQ,CAAC,GAExB,QAAQ,QAAQ,eAAe,KAAK,QAAS,KAAKG,WAAW,IAAI,SAAS,QAAQ,CAAC,CAAC,EACpF,KAAK,QAAQ,IAAI,SAAS,EAAY;IACzC,KAAK,MAAM,MAAM,SAAS,MAAM,UAAU,EAAE;GAC9C,OAEE,IAAI;IACF,MAAM,KAAK,OAAO,EAAE,WAAW,SAAS,CAAC;GAC3C,QAAQ;IAEN,MAAM,QAAQ,MADI,KAAK,OAAO;KAAE,GAAG;KAAK,UAAU;KAAY,UAAU;IAAI,CAAC,GAC3D,QAAQ,CAAC;IAC3B,KAAK,MAAM,OAAO,MAAM,MAAM,UAAU,IAAI,SAAS,EAAY;GACnE;EAEJ,SAAS,KAAK;GACZ,MAAM,IAAI,6BAA6B,CAAC,OAAO,GAAG,CAAC,CAAC;EACtD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"typesense.mjs","names":["#opts","#client","#ensure","#dims","#project","#parseMeta"],"sources":["../../../src/batteries/vector/typesense/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/typesense\n *\n * Typesense adapter. Each collection is a Typesense collection with a `float[]` vector field\n * (native `vector_query` KNN). Metadata is stored as a JSON string field and filtered with\n * the neutral filter tree's JS reference evaluator for exact cross-adapter parity (Typesense\n * filter_by requires per-field schema declaration, which the neutral metadata model doesn't\n * have). Document + id are plain fields.\n *\n * Driver: `typesense` (pure JS).\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { BaseVectorStore } from '../contract'\nimport { validateRecords } from '../validation'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport {\n E_VECTOR_STORE_DRIVER_UNAVAILABLE,\n E_VECTOR_STORE_CONNECTION_FAILED,\n E_VECTOR_STORE_COLLECTION_FAILED,\n E_VECTOR_STORE_UPSERT_FAILED,\n E_VECTOR_STORE_SEARCH_FAILED,\n E_VECTOR_STORE_DELETE_FAILED,\n E_VECTOR_STORE_DIMENSION_MISMATCH,\n E_VECTOR_STORE_UNSUPPORTED_OPERATION,\n} from '../exceptions'\nimport type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from '../plan'\nimport type {\n VectorMatch,\n VectorStoreCapabilities,\n BaseVectorStoreOptions,\n VectorMetadata,\n DistanceMetric,\n} from '../types'\n\nexport interface TypesenseVectorStoreOptions extends BaseVectorStoreOptions {\n /** Connection and authentication parameters for the backend. */\n connection?: {\n host?: string\n port?: number\n protocol?: string\n apiKey?: string\n url?: string\n }\n}\n\nconst getTypesense = async () => {\n try {\n const mod = await import('typesense')\n return (mod as any).default ?? mod\n } catch {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['typesense'])\n }\n}\n\nexport class TypesenseVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: false,\n namedVectors: false,\n rename: false,\n rawSql: false,\n builtInEncoding: false,\n // Typesense indexes writes synchronously (searchable on resolve). The option is a no-op.\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #client: any | null = null\n #dims: Map<string, number> = new Map()\n\n get #opts(): TypesenseVectorStoreOptions {\n return this.options as TypesenseVectorStoreOptions\n }\n\n /** Static availability probe: whether this adapter's runtime driver can load in the current environment. */\n static isAvailable(): boolean {\n return typeof process !== 'undefined'\n }\n isAvailable(): boolean {\n return typeof process !== 'undefined'\n }\n\n async connect(): Promise<void> {\n if (this.#client) return\n const Typesense = await getTypesense()\n const c = this.#opts.connection || {}\n let node: any\n if (c.url) {\n const u = new URL(c.url)\n node = {\n host: u.hostname,\n port: Number(u.port) || (u.protocol === 'https:' ? 443 : 8108),\n protocol: u.protocol.replace(':', ''),\n }\n } else {\n node = { host: c.host ?? 'localhost', port: c.port ?? 8108, protocol: c.protocol ?? 'http' }\n }\n try {\n this.#client = new Typesense.Client({\n nodes: [node],\n apiKey: c.apiKey ?? 'xyz',\n connectionTimeoutSeconds: 5,\n })\n } catch (err) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([String(err)])\n }\n }\n\n async close(): Promise<void> {\n this.#client = null\n }\n\n async #ensure(): Promise<any> {\n if (!this.#client) await this.connect()\n return this.#client!\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n const client = await this.#ensure()\n this.#dims.set(spec.collection, spec.vector.dimensions)\n if (ifNotExists && (await this.hasCollection(spec.collection))) return\n try {\n await client.collections().create({\n name: spec.collection,\n fields: [\n { name: 'id', type: 'string' },\n { name: 'vec', type: 'float[]', num_dim: spec.vector.dimensions },\n { name: 'document', type: 'string', optional: true },\n { name: 'metadata', type: 'string', optional: true },\n ],\n })\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['createCollection', String(err)])\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n const client = await this.#ensure()\n if (ifExists && !(await this.hasCollection(collection))) return\n try {\n await client.collections(collection).delete()\n this.#dims.delete(collection)\n } catch (err) {\n const msg = String(err)\n if (ifExists && msg.includes('Not Found')) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['dropCollection', msg])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n const client = await this.#ensure()\n try {\n await client.collections(collection).retrieve()\n return true\n } catch {\n return false\n }\n }\n\n async renameCollection(_from: string, _to: string): Promise<void> {\n throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(['renameCollection', 'typesense'])\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n if (plan.records.length === 0) return\n validateRecords(plan.records)\n const client = await this.#ensure()\n const expected = this.#opts.dimensions ?? this.#dims.get(plan.collection)\n try {\n const docs: any[] = []\n for (const r of plan.records) {\n let vector = r.vector\n if (!vector && r.document) {\n const [v] = await this.encode([r.document], 'document')\n vector = v\n }\n if (!vector) {\n throw new E_VECTOR_STORE_UPSERT_FAILED(['Record missing vector and document'])\n }\n if (expected !== undefined && vector.length !== expected) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([expected, vector.length])\n }\n docs.push({\n id: r.id,\n vec: vector,\n document: r.document ?? '',\n metadata: r.metadata ? JSON.stringify(r.metadata) : '{}',\n })\n }\n await client.collections(plan.collection).documents().import(docs, { action: 'upsert' })\n } catch (err) {\n if (\n isInstanceOf(err, 'E_VECTOR_STORE_DIMENSION_MISMATCH', E_VECTOR_STORE_DIMENSION_MISMATCH) ||\n isInstanceOf(err, 'E_VECTOR_STORE_UPSERT_FAILED', E_VECTOR_STORE_UPSERT_FAILED)\n ) {\n throw err\n }\n throw new E_VECTOR_STORE_UPSERT_FAILED([String(err)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n const client = await this.#ensure()\n const metric = this.#opts.metric ?? 'cosine'\n let queryVector: number[] | undefined\n if (plan.near) {\n if ('vector' in plan.near) {\n queryVector = plan.near.vector\n } else if ('serverText' in plan.near) {\n const [v] = await this.encode([plan.near.serverText], 'query')\n queryVector = v\n } else if ('id' in plan.near) {\n try {\n const doc = await client.collections(plan.collection).documents(plan.near.id).retrieve()\n queryVector = doc.vec as number[]\n } catch {\n queryVector = undefined\n }\n if (!queryVector) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n }\n }\n\n const offset = plan.offset ?? 0\n try {\n const coll = client.collections(plan.collection).documents()\n if (queryVector) {\n // Over-fetch then JS-filter for exact cross-adapter filter semantics.\n const k = Math.max(plan.topK + offset, plan.topK) + (plan.filter ? 250 : 0)\n const res = await coll.search({\n q: '*',\n vector_query: `vec:([${queryVector.join(',')}], k:${k})`,\n per_page: Math.min(250, k),\n })\n const hits = (res.hits ?? []) as any[]\n const mapped = hits.map((hit) => ({\n match: this.#project(hit.document, plan, metric, hit.vector_distance),\n meta: this.#parseMeta(hit.document.metadata),\n }))\n const filtered = plan.filter\n ? mapped.filter((m) => evaluateFilter(plan.filter!, m.meta))\n : mapped\n return filtered.slice(offset, offset + plan.topK).map((m) => m.match)\n } else {\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n const mapped = hits.map((hit) => ({\n match: this.#project(hit.document, plan, metric, undefined),\n meta: this.#parseMeta(hit.document.metadata),\n }))\n const filtered = plan.filter\n ? mapped.filter((m) => evaluateFilter(plan.filter!, m.meta))\n : mapped\n return filtered.slice(offset, offset + plan.topK).map((m) => m.match)\n }\n } catch (err) {\n throw new E_VECTOR_STORE_SEARCH_FAILED([String(err)])\n }\n }\n\n #parseMeta(val: unknown): VectorMetadata {\n if (typeof val === 'string') {\n try {\n return JSON.parse(val) as VectorMetadata\n } catch {\n return {}\n }\n }\n if (val && typeof val === 'object') return val as VectorMetadata\n return {}\n }\n\n #project(doc: any, plan: SearchPlan, metric: string, dist: number | undefined): VectorMatch {\n const proj = plan.projection\n const out: VectorMatch = {}\n if (proj.id) out.id = doc.id as string\n if (proj.vector && Array.isArray(doc.vec)) out.vector = doc.vec as number[]\n if (proj.document) out.document = (doc.document ?? undefined) as string | undefined\n if (proj.metadata) out.metadata = this.#parseMeta(doc.metadata)\n if (dist !== undefined && dist !== null) {\n out.score = normalizeScore(Number(dist), metric as DistanceMetric, 'distance')\n }\n return out\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n const client = await this.#ensure()\n const collection = client.collections(plan.collection)\n const coll = collection.documents()\n // Delete a single document by id: documents(id).delete() (NOT documents().delete(id),\n // which targets the bulk filter endpoint).\n const deleteOne = async (id: string): Promise<void> => {\n await collection\n .documents(id)\n .delete()\n .catch(() => undefined)\n }\n try {\n if (plan.ids && plan.ids.length > 0) {\n for (const id of plan.ids) await deleteOne(id)\n } else if (plan.filter) {\n // Resolve ids via a scan + JS evaluator, then delete by id.\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n const targets = hits\n .filter((hit) => evaluateFilter(plan.filter!, this.#parseMeta(hit.document.metadata)))\n .map((hit) => hit.document.id as string)\n for (const id of targets) await deleteOne(id)\n } else {\n // Delete-all: bulk delete by an always-true filter; fall back to per-id on error.\n try {\n await coll.delete({ filter_by: 'id:!= ' })\n } catch {\n const res = await coll.search({ q: '*', query_by: 'document', per_page: 250 })\n const hits = (res.hits ?? []) as any[]\n for (const hit of hits) await deleteOne(hit.document.id as string)\n }\n }\n } catch (err) {\n throw new E_VECTOR_STORE_DELETE_FAILED([String(err)])\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+CA,IAAM,eAAe,YAAY;CAC/B,IAAI;EACF,MAAM,MAAM,MAAM,OAAO;EACzB,OAAQ,IAAY,WAAW;CACjC,QAAQ;EACN,MAAM,IAAI,kCAAkC,CAAC,WAAW,CAAC;CAC3D;AACF;AAEA,IAAa,uBAAb,cAA0C,gBAAgB;CACxD,eAAiD;EAC/C,cAAc;EACd,cAAc;EACd,QAAQ;EACR,QAAQ;EACR,iBAAiB;EAEjB,aAAa;GAAE,cAAc;GAAO,SAAS;GAAU,OAAO,CAAC,QAAQ;EAAE;CAC3E;CAEA,UAAsB;CACtB,wBAA6B,IAAI,IAAI;CAErC,IAAIA,QAAqC;EACvC,OAAO,KAAK;CACd;;CAGA,OAAO,cAAuB;EAC5B,OAAO,OAAO,YAAY;CAC5B;CACA,cAAuB;EACrB,OAAO,OAAO,YAAY;CAC5B;CAEA,MAAM,UAAyB;EAC7B,IAAI,KAAKC,SAAS;EAClB,MAAM,YAAY,MAAM,aAAa;EACrC,MAAM,IAAI,KAAKD,MAAM,cAAc,CAAC;EACpC,IAAI;EACJ,IAAI,EAAE,KAAK;GACT,MAAM,IAAI,IAAI,IAAI,EAAE,GAAG;GACvB,OAAO;IACL,MAAM,EAAE;IACR,MAAM,OAAO,EAAE,IAAI,MAAM,EAAE,aAAa,WAAW,MAAM;IACzD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KAAa,SAAS,MACjC,IAAI,QAAQ,eAAe,OAAO,IAAI,GAAG,QAA0B,UAAU;EAE/E,OAAO;CACT;CAEA,MAAM,cAAc,MAAiC;EAEnD,MAAM,cAAa,MADE,KAAKH,QAAQ,GACR,YAAY,KAAK,UAAU;EACrD,MAAM,OAAO,WAAW,UAAU;EAGlC,MAAM,YAAY,OAAO,OAA8B;GACrD,MAAM,WACH,UAAU,EAAE,EACZ,OAAO,EACP,YAAY,KAAA,CAAS;EAC1B;EACA,IAAI;GACF,IAAI,KAAK,OAAO,KAAK,IAAI,SAAS,GAChC,KAAK,MAAM,MAAM,KAAK,KAAK,MAAM,UAAU,EAAE;QACxC,IAAI,KAAK,QAAQ;IAItB,MAAM,YADQ,MADI,KAAK,OAAO;KAAE,GAAG;KAAK,UAAU;KAAY,UAAU;IAAI,CAAC,GAC3D,QAAQ,CAAC,GAExB,QAAQ,QAAQ,eAAe,KAAK,QAAS,KAAKG,WAAW,IAAI,SAAS,QAAQ,CAAC,CAAC,EACpF,KAAK,QAAQ,IAAI,SAAS,EAAY;IACzC,KAAK,MAAM,MAAM,SAAS,MAAM,UAAU,EAAE;GAC9C,OAEE,IAAI;IACF,MAAM,KAAK,OAAO,EAAE,WAAW,SAAS,CAAC;GAC3C,QAAQ;IAEN,MAAM,QAAQ,MADI,KAAK,OAAO;KAAE,GAAG;KAAK,UAAU;KAAY,UAAU;IAAI,CAAC,GAC3D,QAAQ,CAAC;IAC3B,KAAK,MAAM,OAAO,MAAM,MAAM,UAAU,IAAI,SAAS,EAAY;GACnE;EAEJ,SAAS,KAAK;GACZ,MAAM,IAAI,6BAA6B,CAAC,OAAO,GAAG,CAAC,CAAC;EACtD;CACF;AACF"}
|
|
@@ -11,6 +11,7 @@ let _nhtio_validation = require("@nhtio/validation");
|
|
|
11
11
|
* @module @nhtio/adk/batteries/vector/validation
|
|
12
12
|
*/
|
|
13
13
|
var detail = (e) => e.details.map((d) => d.message).join("; ");
|
|
14
|
+
/** Validator schema for {@link @nhtio/adk/batteries/vector!BaseVectorStoreOptions}; allows adapter-specific extra keys. */
|
|
14
15
|
var baseVectorStoreOptionsSchema = _nhtio_validation.validator.object({
|
|
15
16
|
metric: _nhtio_validation.validator.string().valid("cosine", "dot", "euclidean").optional(),
|
|
16
17
|
encoder: _nhtio_validation.validator.custom((value, helpers) => {
|
|
@@ -22,6 +23,7 @@ var baseVectorStoreOptionsSchema = _nhtio_validation.validator.object({
|
|
|
22
23
|
defaultCollection: _nhtio_validation.validator.string().optional(),
|
|
23
24
|
consistency: _nhtio_validation.validator.string().valid("strong", "best-effort", "eventual").optional()
|
|
24
25
|
}).unknown(true);
|
|
26
|
+
/** Validator schema for a single {@link @nhtio/adk/batteries/vector!VectorRecord}; rejects unknown keys. */
|
|
25
27
|
var vectorRecordSchema = _nhtio_validation.validator.object({
|
|
26
28
|
id: _nhtio_validation.validator.string().min(1).required(),
|
|
27
29
|
vector: _nhtio_validation.validator.array().items(_nhtio_validation.validator.number()).optional(),
|
|
@@ -37,6 +39,12 @@ var vectorRecordSchema = _nhtio_validation.validator.object({
|
|
|
37
39
|
* them and re-validates the resolved value (see resolveClientCtor).
|
|
38
40
|
*/
|
|
39
41
|
var clientSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.custom((v, h) => require_batteries_vector_vector_store_constructor.implementsVectorStoreConstructor(v) ? v : h.error("any.invalid")), _nhtio_validation.validator.custom((v, h) => typeof v === "function" && !require_batteries_vector_vector_store_constructor.implementsVectorStoreConstructor(v) ? v : h.error("any.invalid")));
|
|
42
|
+
/**
|
|
43
|
+
* Validate a {@link @nhtio/adk/batteries/vector!CreateVectorStoreConfig} shape (client + options).
|
|
44
|
+
*
|
|
45
|
+
* @param input - The raw config to validate.
|
|
46
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_STORE_CONFIG} when the shape is invalid.
|
|
47
|
+
*/
|
|
40
48
|
var validateCreateConfig = (input) => {
|
|
41
49
|
const { error } = _nhtio_validation.validator.object({
|
|
42
50
|
client: clientSchema.required(),
|
|
@@ -68,6 +76,12 @@ var resolveClientCtor = async (client) => {
|
|
|
68
76
|
if (!require_batteries_vector_vector_store_constructor.implementsVectorStoreConstructor(resolved)) throw new require_batteries_vector_exceptions.E_INVALID_VECTOR_STORE_CONFIG(["client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)"]);
|
|
69
77
|
return resolved;
|
|
70
78
|
};
|
|
79
|
+
/**
|
|
80
|
+
* Validate a batch of {@link @nhtio/adk/batteries/vector!VectorRecord}s, including that vectors contain only finite numbers.
|
|
81
|
+
*
|
|
82
|
+
* @param records - The records to validate.
|
|
83
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_RECORD} (carrying the offending index) on the first invalid record.
|
|
84
|
+
*/
|
|
71
85
|
var validateRecords = (records) => {
|
|
72
86
|
for (const [i, record] of records.entries()) {
|
|
73
87
|
const { error } = vectorRecordSchema.validate(record, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.cjs","names":[],"sources":["../../../src/batteries/vector/validation.ts"],"sourcesContent":["/**\n * Runtime validation schemas and throwing wrappers for the vector battery.\n *\n * @module @nhtio/adk/batteries/vector/validation\n */\n\nimport { vectorFilterSchema } from './filters'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport { implementsVectorStoreConstructor } from './vector_store_constructor'\nimport { E_INVALID_VECTOR_STORE_CONFIG, E_INVALID_VECTOR_RECORD } from './exceptions'\nimport type { VectorRecord } from './types'\n\nconst detail = (e: ValidationError): string => e.details.map((d) => d.message).join('; ')\n\nexport const baseVectorStoreOptionsSchema = validator\n .object({\n metric: validator.string().valid('cosine', 'dot', 'euclidean').optional(),\n encoder: validator\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (typeof value === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n dimensions: validator.number().integer().min(1).optional(),\n defaultCollection: validator.string().optional(),\n consistency: validator.string().valid('strong', 'best-effort', 'eventual').optional(),\n })\n .unknown(true)\n\nexport const vectorRecordSchema = validator\n .object({\n id: validator.string().min(1).required(),\n vector: validator.array().items(validator.number()).optional(),\n document: validator.string().optional(),\n metadata: validator.object().unknown(true).optional(),\n })\n .unknown(false)\n\nexport { vectorFilterSchema }\n\n/**\n * `client` accepts three forms, validated as alternatives:\n * 1. the adapter class itself — a BaseVectorStore subclass constructor\n * 2. a sync resolver `() => Class` — returns the class\n * 3. an async resolver `() => import(…)` — resolves to the class (e.g. a dynamic import)\n * Forms 2 and 3 are both plain functions that are NOT store constructors; the factory awaits\n * them and re-validates the resolved value (see resolveClientCtor).\n */\nconst clientSchema = validator.alternatives(\n // form 1: an actual adapter class\n validator.custom((v, h) => (implementsVectorStoreConstructor(v) ? v : h.error('any.invalid'))),\n // forms 2 & 3: a (sync or async) resolver function that is not itself a store class\n validator.custom((v, h) =>\n typeof v === 'function' && !implementsVectorStoreConstructor(v) ? v : h.error('any.invalid')\n )\n)\n\nexport const validateCreateConfig = (input: unknown): void => {\n const schema = validator\n .object({\n client: clientSchema.required(),\n options: validator.object().unknown(true).required(),\n })\n .unknown(true)\n const { error } = schema.validate(input, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_STORE_CONFIG([detail(error)])\n}\n\n/**\n * Resolve the `client` (class | sync resolver | async resolver) down to the adapter constructor,\n * then validate the resolved value is a BaseVectorStore subclass — throwing the same\n * E_INVALID_VECTOR_STORE_CONFIG if a resolver hands back something that isn't one.\n */\nexport const resolveClientCtor = async (client: unknown): Promise<new (options: any) => any> => {\n let resolved: unknown = client\n // A resolver is a plain function that is not itself a store class; call it (it may be async).\n // A bare non-store class is also a function — invoking it throws \"cannot invoke without new\";\n // we catch that and fall through to the not-a-store rejection below rather than leaking it.\n if (typeof client === 'function' && !implementsVectorStoreConstructor(client)) {\n try {\n resolved = await (client as () => unknown)()\n } catch {\n resolved = undefined\n }\n // A resolver may return a module namespace; unwrap a `.default` export if present.\n if (resolved && typeof resolved === 'object' && 'default' in (resolved as object)) {\n const def = (resolved as { default?: unknown }).default\n if (implementsVectorStoreConstructor(def)) resolved = def\n }\n }\n if (!implementsVectorStoreConstructor(resolved)) {\n throw new E_INVALID_VECTOR_STORE_CONFIG([\n 'client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)',\n ])\n }\n return resolved as new (options: any) => any\n}\n\nexport const validateRecords = (records: VectorRecord[]): void => {\n for (const [i, record] of records.entries()) {\n const { error } = vectorRecordSchema.validate(record, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_RECORD([i, detail(error)])\n const vec = record.vector\n if (vec && !vec.every((n) => Number.isFinite(n))) {\n throw new E_INVALID_VECTOR_RECORD([i, 'vector contains a non-finite number'])\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAM,UAAU,MAA+B,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI
|
|
1
|
+
{"version":3,"file":"validation.cjs","names":[],"sources":["../../../src/batteries/vector/validation.ts"],"sourcesContent":["/**\n * Runtime validation schemas and throwing wrappers for the vector battery.\n *\n * @module @nhtio/adk/batteries/vector/validation\n */\n\nimport { vectorFilterSchema } from './filters'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport { implementsVectorStoreConstructor } from './vector_store_constructor'\nimport { E_INVALID_VECTOR_STORE_CONFIG, E_INVALID_VECTOR_RECORD } from './exceptions'\nimport type { VectorRecord } from './types'\n\nconst detail = (e: ValidationError): string => e.details.map((d) => d.message).join('; ')\n\n/** Validator schema for {@link @nhtio/adk/batteries/vector!BaseVectorStoreOptions}; allows adapter-specific extra keys. */\nexport const baseVectorStoreOptionsSchema = validator\n .object({\n metric: validator.string().valid('cosine', 'dot', 'euclidean').optional(),\n encoder: validator\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (typeof value === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n dimensions: validator.number().integer().min(1).optional(),\n defaultCollection: validator.string().optional(),\n consistency: validator.string().valid('strong', 'best-effort', 'eventual').optional(),\n })\n .unknown(true)\n\n/** Validator schema for a single {@link @nhtio/adk/batteries/vector!VectorRecord}; rejects unknown keys. */\nexport const vectorRecordSchema = validator\n .object({\n id: validator.string().min(1).required(),\n vector: validator.array().items(validator.number()).optional(),\n document: validator.string().optional(),\n metadata: validator.object().unknown(true).optional(),\n })\n .unknown(false)\n\nexport { vectorFilterSchema }\n\n/**\n * `client` accepts three forms, validated as alternatives:\n * 1. the adapter class itself — a BaseVectorStore subclass constructor\n * 2. a sync resolver `() => Class` — returns the class\n * 3. an async resolver `() => import(…)` — resolves to the class (e.g. a dynamic import)\n * Forms 2 and 3 are both plain functions that are NOT store constructors; the factory awaits\n * them and re-validates the resolved value (see resolveClientCtor).\n */\nconst clientSchema = validator.alternatives(\n // form 1: an actual adapter class\n validator.custom((v, h) => (implementsVectorStoreConstructor(v) ? v : h.error('any.invalid'))),\n // forms 2 & 3: a (sync or async) resolver function that is not itself a store class\n validator.custom((v, h) =>\n typeof v === 'function' && !implementsVectorStoreConstructor(v) ? v : h.error('any.invalid')\n )\n)\n\n/**\n * Validate a {@link @nhtio/adk/batteries/vector!CreateVectorStoreConfig} shape (client + options).\n *\n * @param input - The raw config to validate.\n * @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_STORE_CONFIG} when the shape is invalid.\n */\nexport const validateCreateConfig = (input: unknown): void => {\n const schema = validator\n .object({\n client: clientSchema.required(),\n options: validator.object().unknown(true).required(),\n })\n .unknown(true)\n const { error } = schema.validate(input, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_STORE_CONFIG([detail(error)])\n}\n\n/**\n * Resolve the `client` (class | sync resolver | async resolver) down to the adapter constructor,\n * then validate the resolved value is a BaseVectorStore subclass — throwing the same\n * E_INVALID_VECTOR_STORE_CONFIG if a resolver hands back something that isn't one.\n */\nexport const resolveClientCtor = async (client: unknown): Promise<new (options: any) => any> => {\n let resolved: unknown = client\n // A resolver is a plain function that is not itself a store class; call it (it may be async).\n // A bare non-store class is also a function — invoking it throws \"cannot invoke without new\";\n // we catch that and fall through to the not-a-store rejection below rather than leaking it.\n if (typeof client === 'function' && !implementsVectorStoreConstructor(client)) {\n try {\n resolved = await (client as () => unknown)()\n } catch {\n resolved = undefined\n }\n // A resolver may return a module namespace; unwrap a `.default` export if present.\n if (resolved && typeof resolved === 'object' && 'default' in (resolved as object)) {\n const def = (resolved as { default?: unknown }).default\n if (implementsVectorStoreConstructor(def)) resolved = def\n }\n }\n if (!implementsVectorStoreConstructor(resolved)) {\n throw new E_INVALID_VECTOR_STORE_CONFIG([\n 'client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)',\n ])\n }\n return resolved as new (options: any) => any\n}\n\n/**\n * Validate a batch of {@link @nhtio/adk/batteries/vector!VectorRecord}s, including that vectors contain only finite numbers.\n *\n * @param records - The records to validate.\n * @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_RECORD} (carrying the offending index) on the first invalid record.\n */\nexport const validateRecords = (records: VectorRecord[]): void => {\n for (const [i, record] of records.entries()) {\n const { error } = vectorRecordSchema.validate(record, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_RECORD([i, detail(error)])\n const vec = record.vector\n if (vec && !vec.every((n) => Number.isFinite(n))) {\n throw new E_INVALID_VECTOR_RECORD([i, 'vector contains a non-finite number'])\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAM,UAAU,MAA+B,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI;;AAGxF,IAAa,+BAA+B,kBAAA,UACzC,OAAO;CACN,QAAQ,kBAAA,UAAU,OAAO,EAAE,MAAM,UAAU,OAAO,WAAW,EAAE,SAAS;CACxE,SAAS,kBAAA,UACN,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,IAAI,OAAO,UAAU,YAAY,OAAO;EACxC,OAAO,QAAQ,MAAM,aAAa;CACpC,CAAC,EAC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,WAAW,cAAc,CAAC,kDAAA,iCAAiC,MAAM,GAAG;EAC7E,IAAI;GACF,WAAW,MAAO,OAAyB;EAC7C,QAAQ;GACN,WAAW,KAAA;EACb;EAEA,IAAI,YAAY,OAAO,aAAa,YAAY,aAAc,UAAqB;GACjF,MAAM,MAAO,SAAmC;GAChD,IAAI,kDAAA,iCAAiC,GAAG,GAAG,WAAW;EACxD;CACF;CACA,IAAI,CAAC,kDAAA,iCAAiC,QAAQ,GAC5C,MAAM,IAAI,oCAAA,8BAA8B,CACtC,wFACF,CAAC;CAEH,OAAO;AACT;;;;;;;AAQA,IAAa,mBAAmB,YAAkC;CAChE,KAAK,MAAM,CAAC,GAAG,WAAW,QAAQ,QAAQ,GAAG;EAC3C,MAAM,EAAE,UAAU,mBAAmB,SAAS,QAAQ;GAAE,YAAY;GAAO,SAAS;EAAM,CAAC;EAC3F,IAAI,OAAO,MAAM,IAAI,oCAAA,wBAAwB,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC;EAC/D,MAAM,MAAM,OAAO;EACnB,IAAI,OAAO,CAAC,IAAI,OAAO,MAAM,OAAO,SAAS,CAAC,CAAC,GAC7C,MAAM,IAAI,oCAAA,wBAAwB,CAAC,GAAG,qCAAqC,CAAC;CAEhF;AACF"}
|
|
@@ -5,9 +5,17 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { vectorFilterSchema } from "./filters";
|
|
7
7
|
import type { VectorRecord } from "./types";
|
|
8
|
+
/** Validator schema for {@link @nhtio/adk/batteries/vector!BaseVectorStoreOptions}; allows adapter-specific extra keys. */
|
|
8
9
|
export declare const baseVectorStoreOptionsSchema: import("@nhtio/validation").ObjectSchema<any>;
|
|
10
|
+
/** Validator schema for a single {@link @nhtio/adk/batteries/vector!VectorRecord}; rejects unknown keys. */
|
|
9
11
|
export declare const vectorRecordSchema: import("@nhtio/validation").ObjectSchema<any>;
|
|
10
12
|
export { vectorFilterSchema };
|
|
13
|
+
/**
|
|
14
|
+
* Validate a {@link @nhtio/adk/batteries/vector!CreateVectorStoreConfig} shape (client + options).
|
|
15
|
+
*
|
|
16
|
+
* @param input - The raw config to validate.
|
|
17
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_STORE_CONFIG} when the shape is invalid.
|
|
18
|
+
*/
|
|
11
19
|
export declare const validateCreateConfig: (input: unknown) => void;
|
|
12
20
|
/**
|
|
13
21
|
* Resolve the `client` (class | sync resolver | async resolver) down to the adapter constructor,
|
|
@@ -15,4 +23,10 @@ export declare const validateCreateConfig: (input: unknown) => void;
|
|
|
15
23
|
* E_INVALID_VECTOR_STORE_CONFIG if a resolver hands back something that isn't one.
|
|
16
24
|
*/
|
|
17
25
|
export declare const resolveClientCtor: (client: unknown) => Promise<new (options: any) => any>;
|
|
26
|
+
/**
|
|
27
|
+
* Validate a batch of {@link @nhtio/adk/batteries/vector!VectorRecord}s, including that vectors contain only finite numbers.
|
|
28
|
+
*
|
|
29
|
+
* @param records - The records to validate.
|
|
30
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_RECORD} (carrying the offending index) on the first invalid record.
|
|
31
|
+
*/
|
|
18
32
|
export declare const validateRecords: (records: VectorRecord[]) => void;
|
|
@@ -9,6 +9,7 @@ import { validator } from "@nhtio/validation";
|
|
|
9
9
|
* @module @nhtio/adk/batteries/vector/validation
|
|
10
10
|
*/
|
|
11
11
|
var detail = (e) => e.details.map((d) => d.message).join("; ");
|
|
12
|
+
/** Validator schema for {@link @nhtio/adk/batteries/vector!BaseVectorStoreOptions}; allows adapter-specific extra keys. */
|
|
12
13
|
var baseVectorStoreOptionsSchema = validator.object({
|
|
13
14
|
metric: validator.string().valid("cosine", "dot", "euclidean").optional(),
|
|
14
15
|
encoder: validator.custom((value, helpers) => {
|
|
@@ -20,6 +21,7 @@ var baseVectorStoreOptionsSchema = validator.object({
|
|
|
20
21
|
defaultCollection: validator.string().optional(),
|
|
21
22
|
consistency: validator.string().valid("strong", "best-effort", "eventual").optional()
|
|
22
23
|
}).unknown(true);
|
|
24
|
+
/** Validator schema for a single {@link @nhtio/adk/batteries/vector!VectorRecord}; rejects unknown keys. */
|
|
23
25
|
var vectorRecordSchema = validator.object({
|
|
24
26
|
id: validator.string().min(1).required(),
|
|
25
27
|
vector: validator.array().items(validator.number()).optional(),
|
|
@@ -35,6 +37,12 @@ var vectorRecordSchema = validator.object({
|
|
|
35
37
|
* them and re-validates the resolved value (see resolveClientCtor).
|
|
36
38
|
*/
|
|
37
39
|
var clientSchema = validator.alternatives(validator.custom((v, h) => implementsVectorStoreConstructor(v) ? v : h.error("any.invalid")), validator.custom((v, h) => typeof v === "function" && !implementsVectorStoreConstructor(v) ? v : h.error("any.invalid")));
|
|
40
|
+
/**
|
|
41
|
+
* Validate a {@link @nhtio/adk/batteries/vector!CreateVectorStoreConfig} shape (client + options).
|
|
42
|
+
*
|
|
43
|
+
* @param input - The raw config to validate.
|
|
44
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_STORE_CONFIG} when the shape is invalid.
|
|
45
|
+
*/
|
|
38
46
|
var validateCreateConfig = (input) => {
|
|
39
47
|
const { error } = validator.object({
|
|
40
48
|
client: clientSchema.required(),
|
|
@@ -66,6 +74,12 @@ var resolveClientCtor = async (client) => {
|
|
|
66
74
|
if (!implementsVectorStoreConstructor(resolved)) throw new E_INVALID_VECTOR_STORE_CONFIG(["client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)"]);
|
|
67
75
|
return resolved;
|
|
68
76
|
};
|
|
77
|
+
/**
|
|
78
|
+
* Validate a batch of {@link @nhtio/adk/batteries/vector!VectorRecord}s, including that vectors contain only finite numbers.
|
|
79
|
+
*
|
|
80
|
+
* @param records - The records to validate.
|
|
81
|
+
* @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_RECORD} (carrying the offending index) on the first invalid record.
|
|
82
|
+
*/
|
|
69
83
|
var validateRecords = (records) => {
|
|
70
84
|
for (const [i, record] of records.entries()) {
|
|
71
85
|
const { error } = vectorRecordSchema.validate(record, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/batteries/vector/validation.ts"],"sourcesContent":["/**\n * Runtime validation schemas and throwing wrappers for the vector battery.\n *\n * @module @nhtio/adk/batteries/vector/validation\n */\n\nimport { vectorFilterSchema } from './filters'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport { implementsVectorStoreConstructor } from './vector_store_constructor'\nimport { E_INVALID_VECTOR_STORE_CONFIG, E_INVALID_VECTOR_RECORD } from './exceptions'\nimport type { VectorRecord } from './types'\n\nconst detail = (e: ValidationError): string => e.details.map((d) => d.message).join('; ')\n\nexport const baseVectorStoreOptionsSchema = validator\n .object({\n metric: validator.string().valid('cosine', 'dot', 'euclidean').optional(),\n encoder: validator\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (typeof value === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n dimensions: validator.number().integer().min(1).optional(),\n defaultCollection: validator.string().optional(),\n consistency: validator.string().valid('strong', 'best-effort', 'eventual').optional(),\n })\n .unknown(true)\n\nexport const vectorRecordSchema = validator\n .object({\n id: validator.string().min(1).required(),\n vector: validator.array().items(validator.number()).optional(),\n document: validator.string().optional(),\n metadata: validator.object().unknown(true).optional(),\n })\n .unknown(false)\n\nexport { vectorFilterSchema }\n\n/**\n * `client` accepts three forms, validated as alternatives:\n * 1. the adapter class itself — a BaseVectorStore subclass constructor\n * 2. a sync resolver `() => Class` — returns the class\n * 3. an async resolver `() => import(…)` — resolves to the class (e.g. a dynamic import)\n * Forms 2 and 3 are both plain functions that are NOT store constructors; the factory awaits\n * them and re-validates the resolved value (see resolveClientCtor).\n */\nconst clientSchema = validator.alternatives(\n // form 1: an actual adapter class\n validator.custom((v, h) => (implementsVectorStoreConstructor(v) ? v : h.error('any.invalid'))),\n // forms 2 & 3: a (sync or async) resolver function that is not itself a store class\n validator.custom((v, h) =>\n typeof v === 'function' && !implementsVectorStoreConstructor(v) ? v : h.error('any.invalid')\n )\n)\n\nexport const validateCreateConfig = (input: unknown): void => {\n const schema = validator\n .object({\n client: clientSchema.required(),\n options: validator.object().unknown(true).required(),\n })\n .unknown(true)\n const { error } = schema.validate(input, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_STORE_CONFIG([detail(error)])\n}\n\n/**\n * Resolve the `client` (class | sync resolver | async resolver) down to the adapter constructor,\n * then validate the resolved value is a BaseVectorStore subclass — throwing the same\n * E_INVALID_VECTOR_STORE_CONFIG if a resolver hands back something that isn't one.\n */\nexport const resolveClientCtor = async (client: unknown): Promise<new (options: any) => any> => {\n let resolved: unknown = client\n // A resolver is a plain function that is not itself a store class; call it (it may be async).\n // A bare non-store class is also a function — invoking it throws \"cannot invoke without new\";\n // we catch that and fall through to the not-a-store rejection below rather than leaking it.\n if (typeof client === 'function' && !implementsVectorStoreConstructor(client)) {\n try {\n resolved = await (client as () => unknown)()\n } catch {\n resolved = undefined\n }\n // A resolver may return a module namespace; unwrap a `.default` export if present.\n if (resolved && typeof resolved === 'object' && 'default' in (resolved as object)) {\n const def = (resolved as { default?: unknown }).default\n if (implementsVectorStoreConstructor(def)) resolved = def\n }\n }\n if (!implementsVectorStoreConstructor(resolved)) {\n throw new E_INVALID_VECTOR_STORE_CONFIG([\n 'client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)',\n ])\n }\n return resolved as new (options: any) => any\n}\n\nexport const validateRecords = (records: VectorRecord[]): void => {\n for (const [i, record] of records.entries()) {\n const { error } = vectorRecordSchema.validate(record, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_RECORD([i, detail(error)])\n const vec = record.vector\n if (vec && !vec.every((n) => Number.isFinite(n))) {\n throw new E_INVALID_VECTOR_RECORD([i, 'vector contains a non-finite number'])\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAM,UAAU,MAA+B,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI
|
|
1
|
+
{"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/batteries/vector/validation.ts"],"sourcesContent":["/**\n * Runtime validation schemas and throwing wrappers for the vector battery.\n *\n * @module @nhtio/adk/batteries/vector/validation\n */\n\nimport { vectorFilterSchema } from './filters'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport { implementsVectorStoreConstructor } from './vector_store_constructor'\nimport { E_INVALID_VECTOR_STORE_CONFIG, E_INVALID_VECTOR_RECORD } from './exceptions'\nimport type { VectorRecord } from './types'\n\nconst detail = (e: ValidationError): string => e.details.map((d) => d.message).join('; ')\n\n/** Validator schema for {@link @nhtio/adk/batteries/vector!BaseVectorStoreOptions}; allows adapter-specific extra keys. */\nexport const baseVectorStoreOptionsSchema = validator\n .object({\n metric: validator.string().valid('cosine', 'dot', 'euclidean').optional(),\n encoder: validator\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (typeof value === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n dimensions: validator.number().integer().min(1).optional(),\n defaultCollection: validator.string().optional(),\n consistency: validator.string().valid('strong', 'best-effort', 'eventual').optional(),\n })\n .unknown(true)\n\n/** Validator schema for a single {@link @nhtio/adk/batteries/vector!VectorRecord}; rejects unknown keys. */\nexport const vectorRecordSchema = validator\n .object({\n id: validator.string().min(1).required(),\n vector: validator.array().items(validator.number()).optional(),\n document: validator.string().optional(),\n metadata: validator.object().unknown(true).optional(),\n })\n .unknown(false)\n\nexport { vectorFilterSchema }\n\n/**\n * `client` accepts three forms, validated as alternatives:\n * 1. the adapter class itself — a BaseVectorStore subclass constructor\n * 2. a sync resolver `() => Class` — returns the class\n * 3. an async resolver `() => import(…)` — resolves to the class (e.g. a dynamic import)\n * Forms 2 and 3 are both plain functions that are NOT store constructors; the factory awaits\n * them and re-validates the resolved value (see resolveClientCtor).\n */\nconst clientSchema = validator.alternatives(\n // form 1: an actual adapter class\n validator.custom((v, h) => (implementsVectorStoreConstructor(v) ? v : h.error('any.invalid'))),\n // forms 2 & 3: a (sync or async) resolver function that is not itself a store class\n validator.custom((v, h) =>\n typeof v === 'function' && !implementsVectorStoreConstructor(v) ? v : h.error('any.invalid')\n )\n)\n\n/**\n * Validate a {@link @nhtio/adk/batteries/vector!CreateVectorStoreConfig} shape (client + options).\n *\n * @param input - The raw config to validate.\n * @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_STORE_CONFIG} when the shape is invalid.\n */\nexport const validateCreateConfig = (input: unknown): void => {\n const schema = validator\n .object({\n client: clientSchema.required(),\n options: validator.object().unknown(true).required(),\n })\n .unknown(true)\n const { error } = schema.validate(input, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_STORE_CONFIG([detail(error)])\n}\n\n/**\n * Resolve the `client` (class | sync resolver | async resolver) down to the adapter constructor,\n * then validate the resolved value is a BaseVectorStore subclass — throwing the same\n * E_INVALID_VECTOR_STORE_CONFIG if a resolver hands back something that isn't one.\n */\nexport const resolveClientCtor = async (client: unknown): Promise<new (options: any) => any> => {\n let resolved: unknown = client\n // A resolver is a plain function that is not itself a store class; call it (it may be async).\n // A bare non-store class is also a function — invoking it throws \"cannot invoke without new\";\n // we catch that and fall through to the not-a-store rejection below rather than leaking it.\n if (typeof client === 'function' && !implementsVectorStoreConstructor(client)) {\n try {\n resolved = await (client as () => unknown)()\n } catch {\n resolved = undefined\n }\n // A resolver may return a module namespace; unwrap a `.default` export if present.\n if (resolved && typeof resolved === 'object' && 'default' in (resolved as object)) {\n const def = (resolved as { default?: unknown }).default\n if (implementsVectorStoreConstructor(def)) resolved = def\n }\n }\n if (!implementsVectorStoreConstructor(resolved)) {\n throw new E_INVALID_VECTOR_STORE_CONFIG([\n 'client must be, or resolve to, a vector store constructor (a BaseVectorStore subclass)',\n ])\n }\n return resolved as new (options: any) => any\n}\n\n/**\n * Validate a batch of {@link @nhtio/adk/batteries/vector!VectorRecord}s, including that vectors contain only finite numbers.\n *\n * @param records - The records to validate.\n * @throws {@link @nhtio/adk/batteries/vector!E_INVALID_VECTOR_RECORD} (carrying the offending index) on the first invalid record.\n */\nexport const validateRecords = (records: VectorRecord[]): void => {\n for (const [i, record] of records.entries()) {\n const { error } = vectorRecordSchema.validate(record, { abortEarly: false, convert: false })\n if (error) throw new E_INVALID_VECTOR_RECORD([i, detail(error)])\n const vec = record.vector\n if (vec && !vec.every((n) => Number.isFinite(n))) {\n throw new E_INVALID_VECTOR_RECORD([i, 'vector contains a non-finite number'])\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAM,UAAU,MAA+B,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI;;AAGxF,IAAa,+BAA+B,UACzC,OAAO;CACN,QAAQ,UAAU,OAAO,EAAE,MAAM,UAAU,OAAO,WAAW,EAAE,SAAS;CACxE,SAAS,UACN,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,IAAI,OAAO,UAAU,YAAY,OAAO;EACxC,OAAO,QAAQ,MAAM,aAAa;CACpC,CAAC,EACA,SAAS;CACZ,YAAY,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,SAAS;CACzD,mBAAmB,UAAU,OAAO,EAAE,SAAS;CAC/C,aAAa,UAAU,OAAO,EAAE,MAAM,UAAU,eAAe,UAAU,EAAE,SAAS;AACtF,CAAC,EACA,QAAQ,IAAI;;AAGf,IAAa,qBAAqB,UAC/B,OAAO;CACN,IAAI,UAAU,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;CACvC,QAAQ,UAAU,MAAM,EAAE,MAAM,UAAU,OAAO,CAAC,EAAE,SAAS;CAC7D,UAAU,UAAU,OAAO,EAAE,SAAS;CACtC,UAAU,UAAU,OAAO,EAAE,QAAQ,IAAI,EAAE,SAAS;AACtD,CAAC,EACA,QAAQ,KAAK;;;;;;;;;AAYhB,IAAM,eAAe,UAAU,aAE7B,UAAU,QAAQ,GAAG,MAAO,iCAAiC,CAAC,IAAI,IAAI,EAA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AG,qCAAqC,CAAC;CAEhF;AACF"}
|
|
@@ -30,7 +30,7 @@ var VECTOR_STORE_METHODS = [
|
|
|
30
30
|
* @remarks
|
|
31
31
|
* Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is
|
|
32
32
|
* duck-typed: the value must be a function whose `prototype` carries every canonical adapter
|
|
33
|
-
* instance method. This mirrors
|
|
33
|
+
* instance method. This mirrors `spooledArtifactConstructorSchema`'s cross-realm-safe
|
|
34
34
|
* pattern — `instanceof BaseVectorStore` would be tighter but would couple this contract to the
|
|
35
35
|
* class value and reject structurally-valid (e.g. cross-realm) adapters.
|
|
36
36
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector_store_constructor.cjs","names":[],"sources":["../../../src/batteries/vector/vector_store_constructor.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vector_store_constructor\n */\n\nimport { validator } from '@nhtio/validation'\nimport type { BaseVectorStore } from './contract'\nimport type { BaseVectorStoreOptions } from './types'\n\n/**\n * Constructor signature for any {@link BaseVectorStore} adapter (the class itself or a subclass).\n *\n * @remarks\n * Re-declared at the contract level so the factory's `client` resolver can recognise a valid\n * adapter constructor without value-importing {@link BaseVectorStore} into modules where that\n * would be awkward, mirroring `SpooledArtifactConstructorLike`.\n */\nexport type VectorStoreConstructorLike<O extends BaseVectorStoreOptions = BaseVectorStoreOptions> =\n new (options: O) => BaseVectorStore\n\n/**\n * The instance methods every {@link BaseVectorStore} subclass carries on its prototype — the\n * data plane (execute*), the schema plane, the connection lifecycle, and `asCallable` (which the\n * factory invokes to build the callable store). A duck-typed value is a valid adapter when its\n * prototype provides all of them.\n */\nconst VECTOR_STORE_METHODS = [\n 'isAvailable',\n 'connect',\n 'close',\n 'executeSearch',\n 'executeUpsert',\n 'executeDelete',\n 'createCollection',\n 'dropCollection',\n 'hasCollection',\n 'renameCollection',\n 'asCallable',\n] as const\n\n/**\n * Validator schema for a {@link VectorStoreConstructorLike} value.\n *\n * @remarks\n * Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is\n * duck-typed: the value must be a function whose `prototype` carries every canonical adapter\n * instance method. This mirrors
|
|
1
|
+
{"version":3,"file":"vector_store_constructor.cjs","names":[],"sources":["../../../src/batteries/vector/vector_store_constructor.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vector_store_constructor\n */\n\nimport { validator } from '@nhtio/validation'\nimport type { BaseVectorStore } from './contract'\nimport type { BaseVectorStoreOptions } from './types'\n\n/**\n * Constructor signature for any {@link BaseVectorStore} adapter (the class itself or a subclass).\n *\n * @remarks\n * Re-declared at the contract level so the factory's `client` resolver can recognise a valid\n * adapter constructor without value-importing {@link BaseVectorStore} into modules where that\n * would be awkward, mirroring `SpooledArtifactConstructorLike`.\n */\nexport type VectorStoreConstructorLike<O extends BaseVectorStoreOptions = BaseVectorStoreOptions> =\n new (options: O) => BaseVectorStore\n\n/**\n * The instance methods every {@link BaseVectorStore} subclass carries on its prototype — the\n * data plane (execute*), the schema plane, the connection lifecycle, and `asCallable` (which the\n * factory invokes to build the callable store). A duck-typed value is a valid adapter when its\n * prototype provides all of them.\n */\nconst VECTOR_STORE_METHODS = [\n 'isAvailable',\n 'connect',\n 'close',\n 'executeSearch',\n 'executeUpsert',\n 'executeDelete',\n 'createCollection',\n 'dropCollection',\n 'hasCollection',\n 'renameCollection',\n 'asCallable',\n] as const\n\n/**\n * Validator schema for a {@link VectorStoreConstructorLike} value.\n *\n * @remarks\n * Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is\n * duck-typed: the value must be a function whose `prototype` carries every canonical adapter\n * instance method. This mirrors `spooledArtifactConstructorSchema`'s cross-realm-safe\n * pattern — `instanceof BaseVectorStore` would be tighter but would couple this contract to the\n * class value and reject structurally-valid (e.g. cross-realm) adapters.\n */\nexport const vectorStoreConstructorSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (typeof value !== 'function') return helpers.error('any.invalid')\n const proto = (value as { prototype?: unknown }).prototype\n if (proto === undefined || proto === null) return helpers.error('any.invalid')\n if (\n VECTOR_STORE_METHODS.every((m) => typeof (proto as Record<string, unknown>)[m] === 'function')\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` is a constructor whose prototype carries every canonical\n * {@link BaseVectorStore} instance method. Duck-typed; does not use `instanceof`.\n */\nexport const implementsVectorStoreConstructor = (\n value: unknown\n): value is VectorStoreConstructorLike => {\n // `.required()` on the schema makes the validator reject undefined/null itself (without it,\n // `validator.any()` skips `.custom()` for an \"absent\" value and would wrongly pass).\n const { error } = vectorStoreConstructorSchema.validate(value, { abortEarly: true })\n return !error\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,IAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,IAAa,+BAA+B,kBAAA,UACzC,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,OAAO,UAAU,YAAY,OAAO,QAAQ,MAAM,aAAa;CACnE,MAAM,QAAS,MAAkC;CACjD,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,QAAQ,MAAM,aAAa;CAC7E,IACE,qBAAqB,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU,GAE7F,OAAO;CAET,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;;;;AAMH,IAAa,oCACX,UACwC;CAGxC,MAAM,EAAE,UAAU,6BAA6B,SAAS,OAAO,EAAE,YAAY,KAAK,CAAC;CACnF,OAAO,CAAC;AACV"}
|
|
@@ -18,7 +18,7 @@ export type VectorStoreConstructorLike<O extends BaseVectorStoreOptions = BaseVe
|
|
|
18
18
|
* @remarks
|
|
19
19
|
* Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is
|
|
20
20
|
* duck-typed: the value must be a function whose `prototype` carries every canonical adapter
|
|
21
|
-
* instance method. This mirrors
|
|
21
|
+
* instance method. This mirrors `spooledArtifactConstructorSchema`'s cross-realm-safe
|
|
22
22
|
* pattern — `instanceof BaseVectorStore` would be tighter but would couple this contract to the
|
|
23
23
|
* class value and reject structurally-valid (e.g. cross-realm) adapters.
|
|
24
24
|
*/
|
|
@@ -28,7 +28,7 @@ var VECTOR_STORE_METHODS = [
|
|
|
28
28
|
* @remarks
|
|
29
29
|
* Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is
|
|
30
30
|
* duck-typed: the value must be a function whose `prototype` carries every canonical adapter
|
|
31
|
-
* instance method. This mirrors
|
|
31
|
+
* instance method. This mirrors `spooledArtifactConstructorSchema`'s cross-realm-safe
|
|
32
32
|
* pattern — `instanceof BaseVectorStore` would be tighter but would couple this contract to the
|
|
33
33
|
* class value and reject structurally-valid (e.g. cross-realm) adapters.
|
|
34
34
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector_store_constructor.mjs","names":[],"sources":["../../../src/batteries/vector/vector_store_constructor.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vector_store_constructor\n */\n\nimport { validator } from '@nhtio/validation'\nimport type { BaseVectorStore } from './contract'\nimport type { BaseVectorStoreOptions } from './types'\n\n/**\n * Constructor signature for any {@link BaseVectorStore} adapter (the class itself or a subclass).\n *\n * @remarks\n * Re-declared at the contract level so the factory's `client` resolver can recognise a valid\n * adapter constructor without value-importing {@link BaseVectorStore} into modules where that\n * would be awkward, mirroring `SpooledArtifactConstructorLike`.\n */\nexport type VectorStoreConstructorLike<O extends BaseVectorStoreOptions = BaseVectorStoreOptions> =\n new (options: O) => BaseVectorStore\n\n/**\n * The instance methods every {@link BaseVectorStore} subclass carries on its prototype — the\n * data plane (execute*), the schema plane, the connection lifecycle, and `asCallable` (which the\n * factory invokes to build the callable store). A duck-typed value is a valid adapter when its\n * prototype provides all of them.\n */\nconst VECTOR_STORE_METHODS = [\n 'isAvailable',\n 'connect',\n 'close',\n 'executeSearch',\n 'executeUpsert',\n 'executeDelete',\n 'createCollection',\n 'dropCollection',\n 'hasCollection',\n 'renameCollection',\n 'asCallable',\n] as const\n\n/**\n * Validator schema for a {@link VectorStoreConstructorLike} value.\n *\n * @remarks\n * Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is\n * duck-typed: the value must be a function whose `prototype` carries every canonical adapter\n * instance method. This mirrors
|
|
1
|
+
{"version":3,"file":"vector_store_constructor.mjs","names":[],"sources":["../../../src/batteries/vector/vector_store_constructor.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vector_store_constructor\n */\n\nimport { validator } from '@nhtio/validation'\nimport type { BaseVectorStore } from './contract'\nimport type { BaseVectorStoreOptions } from './types'\n\n/**\n * Constructor signature for any {@link BaseVectorStore} adapter (the class itself or a subclass).\n *\n * @remarks\n * Re-declared at the contract level so the factory's `client` resolver can recognise a valid\n * adapter constructor without value-importing {@link BaseVectorStore} into modules where that\n * would be awkward, mirroring `SpooledArtifactConstructorLike`.\n */\nexport type VectorStoreConstructorLike<O extends BaseVectorStoreOptions = BaseVectorStoreOptions> =\n new (options: O) => BaseVectorStore\n\n/**\n * The instance methods every {@link BaseVectorStore} subclass carries on its prototype — the\n * data plane (execute*), the schema plane, the connection lifecycle, and `asCallable` (which the\n * factory invokes to build the callable store). A duck-typed value is a valid adapter when its\n * prototype provides all of them.\n */\nconst VECTOR_STORE_METHODS = [\n 'isAvailable',\n 'connect',\n 'close',\n 'executeSearch',\n 'executeUpsert',\n 'executeDelete',\n 'createCollection',\n 'dropCollection',\n 'hasCollection',\n 'renameCollection',\n 'asCallable',\n] as const\n\n/**\n * Validator schema for a {@link VectorStoreConstructorLike} value.\n *\n * @remarks\n * Invoked at validate-time, so inspecting the constructor's prototype is safe. The check is\n * duck-typed: the value must be a function whose `prototype` carries every canonical adapter\n * instance method. This mirrors `spooledArtifactConstructorSchema`'s cross-realm-safe\n * pattern — `instanceof BaseVectorStore` would be tighter but would couple this contract to the\n * class value and reject structurally-valid (e.g. cross-realm) adapters.\n */\nexport const vectorStoreConstructorSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (typeof value !== 'function') return helpers.error('any.invalid')\n const proto = (value as { prototype?: unknown }).prototype\n if (proto === undefined || proto === null) return helpers.error('any.invalid')\n if (\n VECTOR_STORE_METHODS.every((m) => typeof (proto as Record<string, unknown>)[m] === 'function')\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` is a constructor whose prototype carries every canonical\n * {@link BaseVectorStore} instance method. Duck-typed; does not use `instanceof`.\n */\nexport const implementsVectorStoreConstructor = (\n value: unknown\n): value is VectorStoreConstructorLike => {\n // `.required()` on the schema makes the validator reject undefined/null itself (without it,\n // `validator.any()` skips `.custom()` for an \"absent\" value and would wrongly pass).\n const { error } = vectorStoreConstructorSchema.validate(value, { abortEarly: true })\n return !error\n}\n"],"mappings":";;;;;;;;;;;AAyBA,IAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,IAAa,+BAA+B,UACzC,IAAI,EACJ,SAAS,EACT,QAAQ,OAAO,YAAY;CAC1B,IAAI,OAAO,UAAU,YAAY,OAAO,QAAQ,MAAM,aAAa;CACnE,MAAM,QAAS,MAAkC;CACjD,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,QAAQ,MAAM,aAAa;CAC7E,IACE,qBAAqB,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU,GAE7F,OAAO;CAET,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC;;;;;AAMH,IAAa,oCACX,UACwC;CAGxC,MAAM,EAAE,UAAU,6BAA6B,SAAS,OAAO,EAAE,YAAY,KAAK,CAAC;CACnF,OAAO,CAAC;AACV"}
|
|
@@ -17,6 +17,7 @@ import { BaseVectorStore } from "../contract";
|
|
|
17
17
|
import type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from "../plan";
|
|
18
18
|
import type { VectorMatch, VectorStoreCapabilities, BaseVectorStoreOptions } from "../types";
|
|
19
19
|
export interface VespaVectorStoreOptions extends BaseVectorStoreOptions {
|
|
20
|
+
/** Connection and authentication parameters for the backend. */
|
|
20
21
|
connection?: {
|
|
21
22
|
endpoint?: string;
|
|
22
23
|
configUrl?: string;
|
|
@@ -25,6 +26,7 @@ export interface VespaVectorStoreOptions extends BaseVectorStoreOptions {
|
|
|
25
26
|
export declare class VespaVectorStore extends BaseVectorStore {
|
|
26
27
|
#private;
|
|
27
28
|
readonly capabilities: VectorStoreCapabilities;
|
|
29
|
+
/** Static availability probe: whether this adapter's runtime driver can load in the current environment. */
|
|
28
30
|
static isAvailable(): boolean;
|
|
29
31
|
isAvailable(): boolean;
|
|
30
32
|
connect(): Promise<void>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
require("../../chunk-Ble4zEEl.js");
|
|
3
|
-
const require_tool_registry = require("../../tool_registry-
|
|
3
|
+
const require_tool_registry = require("../../tool_registry-CKJPze3j.js");
|
|
4
4
|
require("../../guards.cjs");
|
|
5
5
|
const require_batteries_vector_filters = require("./filters.cjs");
|
|
6
6
|
const require_batteries_vector_helpers = require("./helpers.cjs");
|
|
@@ -135,6 +135,7 @@ var VespaVectorStore = class extends require_batteries_vector_contract.BaseVecto
|
|
|
135
135
|
get #opts() {
|
|
136
136
|
return this.options;
|
|
137
137
|
}
|
|
138
|
+
/** Static availability probe: whether this adapter's runtime driver can load in the current environment. */
|
|
138
139
|
static isAvailable() {
|
|
139
140
|
return typeof process !== "undefined" && typeof fetch === "function";
|
|
140
141
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vespa.cjs","names":["#opts","#connected","#endpoint","#untilDate","#collections","#deploy","#configUrl","#buildPackage","#sleep","#clearCollection","#vecValues","#parseMeta","#project"],"sources":["../../../src/batteries/vector/vespa/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vespa\n *\n * Vespa vector-store adapter. A logical collection maps to a document-type in a deployed\n * application package; the adapter maintains the application-package STATE in memory (the set of\n * live collections + their dims/metric) and redeploys the whole package on each schema change\n * via the config server (dependency-free store-zip). Feed/get/delete/search are performed over\n * the document + search HTTP APIs; scores are recomputed locally (cosineSim/dotProd/euclideanDist)\n * to guarantee the [0,1] contract regardless of backend metric quirks. Metadata is a JSON string\n * field filtered with the neutral filter tree's JS reference evaluator for cross-adapter parity.\n *\n * Vespa has NO runtime \"create collection\". A collection = a document-type declared in a .sd schema\n * file inside a deployed application package. The adapter maintains the application-package STATE\n * in memory and redeploys the whole package on each schema change via the config server.\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { BaseVectorStore } from '../contract'\nimport { validateRecords } from '../validation'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport {\n E_VECTOR_STORE_CONNECTION_FAILED,\n E_VECTOR_STORE_COLLECTION_FAILED,\n E_VECTOR_STORE_UPSERT_FAILED,\n E_VECTOR_STORE_SEARCH_FAILED,\n E_VECTOR_STORE_DELETE_FAILED,\n E_VECTOR_STORE_DIMENSION_MISMATCH,\n E_VECTOR_STORE_UNSUPPORTED_OPERATION,\n} from '../exceptions'\nimport type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from '../plan'\nimport type {\n VectorMatch,\n VectorStoreCapabilities,\n BaseVectorStoreOptions,\n VectorMetadata,\n DistanceMetric,\n} from '../types'\n\n// ZIP writer (no compression)\nconst crc32Table: number[] = (() => {\n const t: number[] = []\n for (let n = 0; n < 256; n++) {\n let c = n\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n t[n] = c >>> 0\n }\n return t\n})()\n\nconst crc32 = (buf: Buffer): number => {\n let c = 0xffffffff\n for (let i = 0; i < buf.length; i++) c = crc32Table[(c ^ buf[i]) & 0xff] ^ (c >>> 8)\n return (c ^ 0xffffffff) >>> 0\n}\n\nconst storeZip = (files: Array<{ name: string; data: Buffer }>): Buffer => {\n const locals: Buffer[] = []\n const central: Buffer[] = []\n let offset = 0\n for (const f of files) {\n const name = Buffer.from(f.name, 'utf8')\n const data = f.data\n const crc = crc32(data)\n const lh = Buffer.alloc(30)\n lh.writeUInt32LE(0x04034b50, 0)\n lh.writeUInt16LE(20, 4)\n lh.writeUInt32LE(crc, 14)\n lh.writeUInt32LE(data.length, 18)\n lh.writeUInt32LE(data.length, 22)\n lh.writeUInt16LE(name.length, 26)\n const local = Buffer.concat([lh, name, data])\n locals.push(local)\n const ch = Buffer.alloc(46)\n ch.writeUInt32LE(0x02014b50, 0)\n ch.writeUInt16LE(20, 4)\n ch.writeUInt16LE(20, 6)\n ch.writeUInt32LE(crc, 16)\n ch.writeUInt32LE(data.length, 20)\n ch.writeUInt32LE(data.length, 24)\n ch.writeUInt16LE(name.length, 28)\n ch.writeUInt32LE(offset, 42)\n central.push(Buffer.concat([ch, name]))\n offset += local.length\n }\n const cd = Buffer.concat(central)\n const localAll = Buffer.concat(locals)\n const eocd = Buffer.alloc(22)\n eocd.writeUInt32LE(0x06054b50, 0)\n eocd.writeUInt16LE(files.length, 8)\n eocd.writeUInt16LE(files.length, 10)\n eocd.writeUInt32LE(cd.length, 12)\n eocd.writeUInt32LE(localAll.length, 16)\n return Buffer.concat([localAll, cd, eocd])\n}\n\nconst metricToVespa = (metric: DistanceMetric): string =>\n metric === 'cosine' ? 'angular' : metric === 'euclidean' ? 'euclidean' : 'dotproduct'\n\nconst cosineSim = (a: number[], b: number[]): number => {\n let dot = 0\n let normA = 0\n let normB = 0\n for (const [i, av] of a.entries()) {\n const bv = b[i]\n dot += av * bv\n normA += av * av\n normB += bv * bv\n }\n const denom = Math.sqrt(normA) * Math.sqrt(normB)\n return denom === 0 ? 0 : dot / denom\n}\n\nconst dotProd = (a: number[], b: number[]): number => {\n let s = 0\n for (const [i, av] of a.entries()) {\n s += av * b[i]\n }\n return s\n}\n\nconst euclideanDist = (a: number[], b: number[]): number => {\n let s = 0\n for (const [i, av] of a.entries()) {\n const d = av - b[i]\n s += d * d\n }\n return Math.sqrt(s)\n}\n\nconst computeScore = (vec: number[], query: number[], metric: DistanceMetric): number => {\n if (metric === 'cosine') {\n const raw = cosineSim(vec, query)\n return normalizeScore(raw, 'cosine', 'similarity')\n } else if (metric === 'dot') {\n const raw = dotProd(vec, query)\n return normalizeScore(raw, 'dot', 'similarity')\n } else if (metric === 'euclidean') {\n const raw = euclideanDist(vec, query)\n return normalizeScore(raw, 'euclidean', 'distance')\n } else {\n const raw = cosineSim(vec, query)\n return normalizeScore(raw, 'cosine', 'similarity')\n }\n}\n\nexport interface VespaVectorStoreOptions extends BaseVectorStoreOptions {\n connection?: {\n endpoint?: string\n configUrl?: string\n }\n}\n\nexport class VespaVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: false,\n namedVectors: false,\n rename: false,\n rawSql: false,\n builtInEncoding: false,\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #collections: Map<string, { dims: number; metric: DistanceMetric }> = new Map()\n #connected: boolean = false\n\n get #opts(): VespaVectorStoreOptions {\n return this.options as VespaVectorStoreOptions\n }\n\n static isAvailable(): boolean {\n return typeof process !== 'undefined' && typeof fetch === 'function'\n }\n\n isAvailable(): boolean {\n return typeof process !== 'undefined' && typeof fetch === 'function'\n }\n\n async connect(): Promise<void> {\n if (this.#connected) return\n const endpoint = this.#endpoint()\n try {\n const res = await fetch(endpoint + '/ApplicationStatus')\n if (!res.ok) {\n const body = (await res.json()) as any\n throw new E_VECTOR_STORE_CONNECTION_FAILED([\n `Vespa config server unreachable: ${body?.message ?? res.statusText}`,\n ])\n }\n } catch (err) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([String(err)])\n }\n this.#connected = true\n }\n\n async close(): Promise<void> {\n this.#connected = false\n }\n\n #endpoint(): string {\n return this.#opts.connection?.endpoint ?? 'http://localhost:8080'\n }\n\n #configUrl(): string {\n return this.#opts.connection?.configUrl ?? 'http://localhost:19071'\n }\n\n #untilDate(): string {\n return new Date(Date.now() + 25 * 86400 * 1000).toISOString().slice(0, 10)\n }\n\n #buildPackage(): Buffer {\n const files: Array<{ name: string; data: Buffer }> = []\n\n // hosts.xml (constant)\n files.push({\n name: 'hosts.xml',\n data: Buffer.from(\n '<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n<hosts><host name=\"localhost\"><alias>node1</alias></host></hosts>\\n',\n 'utf8'\n ),\n })\n\n // validation-overrides.xml\n const until = this.#untilDate()\n files.push({\n name: 'validation-overrides.xml',\n data: Buffer.from(\n `<validation-overrides>\\n <allow until=\"${until}\">schema-removal</allow>\\n <allow until=\"${until}\">field-type-change</allow>\\n <allow until=\"${until}\">indexing-change</allow>\\n</validation-overrides>\\n`,\n 'utf8'\n ),\n })\n\n // services.xml (one <document> line per live collection)\n let docLines = ''\n for (const [coll] of this.#collections) {\n docLines += ` <document type=\"${coll}\" mode=\"index\"/>\\n`\n }\n if (docLines === '') docLines = ' <document type=\"empty\" mode=\"index\"/>\\n'\n files.push({\n name: 'services.xml',\n data: Buffer.from(\n `<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n<services version=\"1.0\">\\n <container id=\"default\" version=\"1.0\"><document-api/><search/></container>\\n <content id=\"docs\" version=\"1.0\">\\n <redundancy>1</redundancy>\\n <documents>\\n${docLines} </documents>\\n <nodes><node distribution-key=\"0\" hostalias=\"node1\"/></nodes>\\n <tuning><resource-limits><disk>0.97</disk><memory>0.95</memory></resource-limits></tuning>\\n </content>\\n</services>\\n`,\n 'utf8'\n ),\n })\n\n // schemas/<coll>.sd\n for (const [coll, spec] of this.#collections) {\n const metric = metricToVespa(spec.metric)\n const sd = `schema ${coll} {\\n document ${coll} {\\n field id type string {\\n indexing: summary | attribute\\n attribute: fast-search\\n }\\n field vec type tensor<float>(x[${spec.dims}]) {\\n indexing: summary | attribute | index\\n attribute { distance-metric: ${metric} }\\n index { hnsw { max-links-per-node: 16 neighbors-to-explore-at-insert: 100 } }\\n }\\n field document type string { indexing: summary }\\n field metadata type string { indexing: summary }\\n }\\n rank-profile vector_nearest {\\n inputs { query(q) tensor<float>(x[${spec.dims}]) }\\n first-phase { expression: closeness(field, vec) }\\n }\\n}\\n`\n files.push({\n name: `schemas/${coll}.sd`,\n data: Buffer.from(sd, 'utf8'),\n })\n }\n\n return storeZip(files)\n }\n\n async #deploy(): Promise<void> {\n const url = this.#configUrl() + '/application/v2/tenant/default/prepareandactivate'\n const pkg = this.#buildPackage()\n // fetch's BodyInit doesn't accept a Node Buffer directly under the DOM lib types; a Uint8Array\n // view over the same bytes is an accepted BodyInit and avoids a copy.\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/zip' },\n // The installed DOM lib's BodyInit doesn't list Uint8Array, but the runtime (undici/Node)\n // accepts a typed-array body fine — cast through the accepted union.\n body: new Uint8Array(pkg.buffer, pkg.byteOffset, pkg.byteLength) as unknown as BodyInit,\n })\n if (!res.ok) {\n const data = (await res.json()) as any\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['deploy', data?.message ?? `HTTP ${res.status}`])\n }\n // Poll ApplicationStatus until 200\n const endpoint = this.#endpoint()\n for (let i = 0; i < 60; i++) {\n try {\n const sres = await fetch(endpoint + '/ApplicationStatus')\n if (sres.ok) return\n } catch {\n // continue polling\n }\n await this.#sleep(1000)\n }\n }\n\n async #sleep(ms: number): Promise<void> {\n await new Promise((r) => setTimeout(r, ms))\n }\n\n #vecValues(field: any): number[] {\n if (field?.values && Array.isArray(field.values)) return field.values\n if (field?.cells && Array.isArray(field.cells)) {\n return field.cells.map((c: any) => c.value)\n }\n return []\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n const coll = spec.collection\n if (this.#collections.has(coll)) {\n if (ifNotExists) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED([\n 'createCollection',\n `collection already exists: ${coll}`,\n ])\n }\n this.#collections.set(coll, { dims: spec.vector.dimensions, metric: spec.vector.metric })\n try {\n await this.#deploy()\n // Wait for schema to be query-ready\n const endpoint = this.#endpoint()\n for (let i = 0; i < 30; i++) {\n try {\n const q = encodeURIComponent(`select id from ${coll} where true`)\n const res = await fetch(`${endpoint}/search/?yql=${q}&hits=1`)\n if (res.ok) break\n } catch {\n // continue polling\n }\n await this.#sleep(500)\n }\n // Clear any residual documents (redeploy preserves data)\n await this.#clearCollection(coll)\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['createCollection', String(err)])\n }\n }\n\n async #clearCollection(coll: string): Promise<void> {\n try {\n const endpoint = this.#endpoint()\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid?selection=true&cluster=docs`,\n {\n method: 'DELETE',\n }\n )\n if (!res.ok) {\n const body = (await res.json()) as any\n // Ignore 404 for non-existing collection\n if (body?.message?.includes('No document type') || res.status === 404) {\n return\n }\n }\n } catch {\n // Ignore errors during clear\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n if (!this.#collections.has(collection)) {\n if (ifExists) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED([\n 'dropCollection',\n `collection not found: ${collection}`,\n ])\n }\n try {\n await this.#clearCollection(collection)\n this.#collections.delete(collection)\n if (this.#collections.size === 0) {\n // Do not redeploy an empty content cluster; just forget it locally\n return\n }\n await this.#deploy()\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['dropCollection', String(err)])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n return this.#collections.has(collection)\n }\n\n async renameCollection(_from: string, _to: string): Promise<void> {\n throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(['renameCollection', 'vespa'])\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n if (plan.records.length === 0) return\n validateRecords(plan.records)\n const coll = plan.collection\n const endpoint = this.#endpoint()\n const dims = this.#opts.dimensions ?? this.#collections.get(coll)?.dims\n try {\n const ids = []\n for (const r of plan.records) {\n let vector = r.vector\n if (!vector && r.document) {\n const [v] = await this.encode([r.document], 'document')\n vector = v\n }\n if (!vector) {\n throw new E_VECTOR_STORE_UPSERT_FAILED(['Record missing vector and document'])\n }\n if (dims !== undefined && vector.length !== dims) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([dims, vector.length])\n }\n const body = {\n fields: {\n id: r.id,\n vec: { values: vector },\n document: r.document ?? '',\n metadata: r.metadata ? JSON.stringify(r.metadata) : '{}',\n },\n }\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(r.id)}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }\n )\n if (!res.ok) {\n const errData = (await res.json()) as any\n throw new Error(errData?.message ?? `HTTP ${res.status}`)\n }\n ids.push(r.id)\n }\n // Brief settle for HNSW index\n await this.#sleep(500)\n } catch (err) {\n if (\n isInstanceOf(err, 'E_VECTOR_STORE_DIMENSION_MISMATCH', E_VECTOR_STORE_DIMENSION_MISMATCH) ||\n isInstanceOf(err, 'E_VECTOR_STORE_UPSERT_FAILED', E_VECTOR_STORE_UPSERT_FAILED)\n ) {\n throw err\n }\n throw new E_VECTOR_STORE_UPSERT_FAILED([String(err)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n const coll = plan.collection\n const endpoint = this.#endpoint()\n const metric = this.#collections.get(coll)?.metric ?? this.#opts.metric ?? 'cosine'\n let queryVector: number[] | undefined\n if (plan.near) {\n if ('vector' in plan.near) {\n queryVector = plan.near.vector\n } else if ('serverText' in plan.near) {\n const [v] = await this.encode([plan.near.serverText], 'query')\n queryVector = v\n } else if ('id' in plan.near) {\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(plan.near.id)}`\n )\n if (!res.ok) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n const data = (await res.json()) as any\n const vec = this.#vecValues(data.fields?.vec)\n if (!vec || vec.length === 0) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n queryVector = vec\n }\n }\n\n const offset = plan.offset ?? 0\n const topK = plan.topK ?? 10\n const k = plan.filter ? 400 : topK + offset\n const yql = queryVector\n ? `select id, document, metadata, vec from ${coll} where {targetHits:${k}}nearestNeighbor(vec, q)`\n : `select id, document, metadata, vec from ${coll} where true`\n\n try {\n const body: any = {\n yql,\n hits: k,\n }\n if (queryVector) {\n body['input.query(q)'] = queryVector\n body['ranking.profile'] = 'vector_nearest'\n }\n const res = await fetch(`${endpoint}/search/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`)\n }\n const data = (await res.json()) as any\n const root = data.root as any\n const children = root.children ?? []\n\n if (queryVector) {\n const filtered = children\n .filter((c: any) =>\n evaluateFilter(plan.filter ?? {}, this.#parseMeta(c.fields?.metadata))\n )\n .map((c: any) => {\n const vec = this.#vecValues(c.fields?.vec)\n const score = computeScore(vec, queryVector, metric)\n return { ...c.fields, score }\n })\n filtered.sort((a: any, b: any) => b.score - a.score)\n return filtered.slice(offset, offset + topK).map((d: any) => this.#project(d, plan, true))\n } else {\n const filtered = children.filter((c: any) =>\n evaluateFilter(plan.filter ?? {}, this.#parseMeta(c.fields?.metadata))\n )\n return filtered.slice(offset, offset + topK).map((d: any) => this.#project(d, plan, false))\n }\n } catch (err) {\n if ((err as any)?.message?.includes('Referenced id not found')) {\n throw err\n }\n throw new E_VECTOR_STORE_SEARCH_FAILED([String(err)])\n }\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n const coll = plan.collection\n const endpoint = this.#endpoint()\n try {\n if (plan.ids && plan.ids.length > 0) {\n for (const id of plan.ids) {\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(id)}`,\n { method: 'DELETE' }\n )\n if (!res.ok && res.status !== 404) {\n const body = (await res.json()) as any\n throw new Error(body?.message ?? `HTTP ${res.status}`)\n }\n }\n } else if (plan.filter) {\n const yql = `select id, metadata, vec from ${coll} where true`\n const res = await fetch(`${endpoint}/search/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ yql, hits: 400 }),\n })\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`)\n }\n const data = (await res.json()) as any\n const children = data.root.children ?? []\n const targets = children\n .filter((c: any) => evaluateFilter(plan.filter!, this.#parseMeta(c.fields?.metadata)))\n .map((c: any) => c.fields?.id)\n for (const id of targets) {\n await fetch(`${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n })\n }\n } else {\n await fetch(`${endpoint}/document/v1/default/${coll}/docid?selection=true&cluster=docs`, {\n method: 'DELETE',\n })\n }\n } catch (err) {\n throw new E_VECTOR_STORE_DELETE_FAILED([String(err)])\n }\n }\n\n #parseMeta(val: unknown): VectorMetadata {\n if (typeof val === 'string') {\n try {\n return JSON.parse(val) as VectorMetadata\n } catch {\n return {}\n }\n }\n if (val && typeof val === 'object') return val as VectorMetadata\n return {}\n }\n\n #project(doc: any, plan: SearchPlan, hasScore: boolean): VectorMatch {\n const proj = plan.projection\n const out: VectorMatch = {}\n if (proj.id) out.id = doc.id as string\n if (proj.vector) {\n const vec = this.#vecValues(doc.vec)\n if (vec && vec.length > 0) out.vector = vec.map(Number)\n }\n if (proj.document) out.document = (doc.document ?? undefined) as string | undefined\n if (proj.metadata) out.metadata = this.#parseMeta(doc.metadata)\n if (hasScore && typeof doc.score === 'number') {\n out.score = doc.score\n }\n return out\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAM,oBAA8B;CAClC,MAAM,IAAc,CAAC;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,KAAK;EAC5B,IAAI,IAAI;EACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,a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","#untilDate","#collections","#deploy","#configUrl","#buildPackage","#sleep","#clearCollection","#vecValues","#parseMeta","#project"],"sources":["../../../src/batteries/vector/vespa/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/vespa\n *\n * Vespa vector-store adapter. A logical collection maps to a document-type in a deployed\n * application package; the adapter maintains the application-package STATE in memory (the set of\n * live collections + their dims/metric) and redeploys the whole package on each schema change\n * via the config server (dependency-free store-zip). Feed/get/delete/search are performed over\n * the document + search HTTP APIs; scores are recomputed locally (cosineSim/dotProd/euclideanDist)\n * to guarantee the [0,1] contract regardless of backend metric quirks. Metadata is a JSON string\n * field filtered with the neutral filter tree's JS reference evaluator for cross-adapter parity.\n *\n * Vespa has NO runtime \"create collection\". A collection = a document-type declared in a .sd schema\n * file inside a deployed application package. The adapter maintains the application-package STATE\n * in memory and redeploys the whole package on each schema change via the config server.\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { BaseVectorStore } from '../contract'\nimport { validateRecords } from '../validation'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport {\n E_VECTOR_STORE_CONNECTION_FAILED,\n E_VECTOR_STORE_COLLECTION_FAILED,\n E_VECTOR_STORE_UPSERT_FAILED,\n E_VECTOR_STORE_SEARCH_FAILED,\n E_VECTOR_STORE_DELETE_FAILED,\n E_VECTOR_STORE_DIMENSION_MISMATCH,\n E_VECTOR_STORE_UNSUPPORTED_OPERATION,\n} from '../exceptions'\nimport type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from '../plan'\nimport type {\n VectorMatch,\n VectorStoreCapabilities,\n BaseVectorStoreOptions,\n VectorMetadata,\n DistanceMetric,\n} from '../types'\n\n// ZIP writer (no compression)\nconst crc32Table: number[] = (() => {\n const t: number[] = []\n for (let n = 0; n < 256; n++) {\n let c = n\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n t[n] = c >>> 0\n }\n return t\n})()\n\nconst crc32 = (buf: Buffer): number => {\n let c = 0xffffffff\n for (let i = 0; i < buf.length; i++) c = crc32Table[(c ^ buf[i]) & 0xff] ^ (c >>> 8)\n return (c ^ 0xffffffff) >>> 0\n}\n\nconst storeZip = (files: Array<{ name: string; data: Buffer }>): Buffer => {\n const locals: Buffer[] = []\n const central: Buffer[] = []\n let offset = 0\n for (const f of files) {\n const name = Buffer.from(f.name, 'utf8')\n const data = f.data\n const crc = crc32(data)\n const lh = Buffer.alloc(30)\n lh.writeUInt32LE(0x04034b50, 0)\n lh.writeUInt16LE(20, 4)\n lh.writeUInt32LE(crc, 14)\n lh.writeUInt32LE(data.length, 18)\n lh.writeUInt32LE(data.length, 22)\n lh.writeUInt16LE(name.length, 26)\n const local = Buffer.concat([lh, name, data])\n locals.push(local)\n const ch = Buffer.alloc(46)\n ch.writeUInt32LE(0x02014b50, 0)\n ch.writeUInt16LE(20, 4)\n ch.writeUInt16LE(20, 6)\n ch.writeUInt32LE(crc, 16)\n ch.writeUInt32LE(data.length, 20)\n ch.writeUInt32LE(data.length, 24)\n ch.writeUInt16LE(name.length, 28)\n ch.writeUInt32LE(offset, 42)\n central.push(Buffer.concat([ch, name]))\n offset += local.length\n }\n const cd = Buffer.concat(central)\n const localAll = Buffer.concat(locals)\n const eocd = Buffer.alloc(22)\n eocd.writeUInt32LE(0x06054b50, 0)\n eocd.writeUInt16LE(files.length, 8)\n eocd.writeUInt16LE(files.length, 10)\n eocd.writeUInt32LE(cd.length, 12)\n eocd.writeUInt32LE(localAll.length, 16)\n return Buffer.concat([localAll, cd, eocd])\n}\n\nconst metricToVespa = (metric: DistanceMetric): string =>\n metric === 'cosine' ? 'angular' : metric === 'euclidean' ? 'euclidean' : 'dotproduct'\n\nconst cosineSim = (a: number[], b: number[]): number => {\n let dot = 0\n let normA = 0\n let normB = 0\n for (const [i, av] of a.entries()) {\n const bv = b[i]\n dot += av * bv\n normA += av * av\n normB += bv * bv\n }\n const denom = Math.sqrt(normA) * Math.sqrt(normB)\n return denom === 0 ? 0 : dot / denom\n}\n\nconst dotProd = (a: number[], b: number[]): number => {\n let s = 0\n for (const [i, av] of a.entries()) {\n s += av * b[i]\n }\n return s\n}\n\nconst euclideanDist = (a: number[], b: number[]): number => {\n let s = 0\n for (const [i, av] of a.entries()) {\n const d = av - b[i]\n s += d * d\n }\n return Math.sqrt(s)\n}\n\nconst computeScore = (vec: number[], query: number[], metric: DistanceMetric): number => {\n if (metric === 'cosine') {\n const raw = cosineSim(vec, query)\n return normalizeScore(raw, 'cosine', 'similarity')\n } else if (metric === 'dot') {\n const raw = dotProd(vec, query)\n return normalizeScore(raw, 'dot', 'similarity')\n } else if (metric === 'euclidean') {\n const raw = euclideanDist(vec, query)\n return normalizeScore(raw, 'euclidean', 'distance')\n } else {\n const raw = cosineSim(vec, query)\n return normalizeScore(raw, 'cosine', 'similarity')\n }\n}\n\nexport interface VespaVectorStoreOptions extends BaseVectorStoreOptions {\n /** Connection and authentication parameters for the backend. */\n connection?: {\n endpoint?: string\n configUrl?: string\n }\n}\n\nexport class VespaVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: false,\n namedVectors: false,\n rename: false,\n rawSql: false,\n builtInEncoding: false,\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #collections: Map<string, { dims: number; metric: DistanceMetric }> = new Map()\n #connected: boolean = false\n\n get #opts(): VespaVectorStoreOptions {\n return this.options as VespaVectorStoreOptions\n }\n\n /** Static availability probe: whether this adapter's runtime driver can load in the current environment. */\n static isAvailable(): boolean {\n return typeof process !== 'undefined' && typeof fetch === 'function'\n }\n\n isAvailable(): boolean {\n return typeof process !== 'undefined' && typeof fetch === 'function'\n }\n\n async connect(): Promise<void> {\n if (this.#connected) return\n const endpoint = this.#endpoint()\n try {\n const res = await fetch(endpoint + '/ApplicationStatus')\n if (!res.ok) {\n const body = (await res.json()) as any\n throw new E_VECTOR_STORE_CONNECTION_FAILED([\n `Vespa config server unreachable: ${body?.message ?? res.statusText}`,\n ])\n }\n } catch (err) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([String(err)])\n }\n this.#connected = true\n }\n\n async close(): Promise<void> {\n this.#connected = false\n }\n\n #endpoint(): string {\n return this.#opts.connection?.endpoint ?? 'http://localhost:8080'\n }\n\n #configUrl(): string {\n return this.#opts.connection?.configUrl ?? 'http://localhost:19071'\n }\n\n #untilDate(): string {\n return new Date(Date.now() + 25 * 86400 * 1000).toISOString().slice(0, 10)\n }\n\n #buildPackage(): Buffer {\n const files: Array<{ name: string; data: Buffer }> = []\n\n // hosts.xml (constant)\n files.push({\n name: 'hosts.xml',\n data: Buffer.from(\n '<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n<hosts><host name=\"localhost\"><alias>node1</alias></host></hosts>\\n',\n 'utf8'\n ),\n })\n\n // validation-overrides.xml\n const until = this.#untilDate()\n files.push({\n name: 'validation-overrides.xml',\n data: Buffer.from(\n `<validation-overrides>\\n <allow until=\"${until}\">schema-removal</allow>\\n <allow until=\"${until}\">field-type-change</allow>\\n <allow until=\"${until}\">indexing-change</allow>\\n</validation-overrides>\\n`,\n 'utf8'\n ),\n })\n\n // services.xml (one <document> line per live collection)\n let docLines = ''\n for (const [coll] of this.#collections) {\n docLines += ` <document type=\"${coll}\" mode=\"index\"/>\\n`\n }\n if (docLines === '') docLines = ' <document type=\"empty\" mode=\"index\"/>\\n'\n files.push({\n name: 'services.xml',\n data: Buffer.from(\n `<?xml version=\"1.0\" encoding=\"utf-8\" ?>\\n<services version=\"1.0\">\\n <container id=\"default\" version=\"1.0\"><document-api/><search/></container>\\n <content id=\"docs\" version=\"1.0\">\\n <redundancy>1</redundancy>\\n <documents>\\n${docLines} </documents>\\n <nodes><node distribution-key=\"0\" hostalias=\"node1\"/></nodes>\\n <tuning><resource-limits><disk>0.97</disk><memory>0.95</memory></resource-limits></tuning>\\n </content>\\n</services>\\n`,\n 'utf8'\n ),\n })\n\n // schemas/<coll>.sd\n for (const [coll, spec] of this.#collections) {\n const metric = metricToVespa(spec.metric)\n const sd = `schema ${coll} {\\n document ${coll} {\\n field id type string {\\n indexing: summary | attribute\\n attribute: fast-search\\n }\\n field vec type tensor<float>(x[${spec.dims}]) {\\n indexing: summary | attribute | index\\n attribute { distance-metric: ${metric} }\\n index { hnsw { max-links-per-node: 16 neighbors-to-explore-at-insert: 100 } }\\n }\\n field document type string { indexing: summary }\\n field metadata type string { indexing: summary }\\n }\\n rank-profile vector_nearest {\\n inputs { query(q) tensor<float>(x[${spec.dims}]) }\\n first-phase { expression: closeness(field, vec) }\\n }\\n}\\n`\n files.push({\n name: `schemas/${coll}.sd`,\n data: Buffer.from(sd, 'utf8'),\n })\n }\n\n return storeZip(files)\n }\n\n async #deploy(): Promise<void> {\n const url = this.#configUrl() + '/application/v2/tenant/default/prepareandactivate'\n const pkg = this.#buildPackage()\n // fetch's BodyInit doesn't accept a Node Buffer directly under the DOM lib types; a Uint8Array\n // view over the same bytes is an accepted BodyInit and avoids a copy.\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/zip' },\n // The installed DOM lib's BodyInit doesn't list Uint8Array, but the runtime (undici/Node)\n // accepts a typed-array body fine — cast through the accepted union.\n body: new Uint8Array(pkg.buffer, pkg.byteOffset, pkg.byteLength) as unknown as BodyInit,\n })\n if (!res.ok) {\n const data = (await res.json()) as any\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['deploy', data?.message ?? `HTTP ${res.status}`])\n }\n // Poll ApplicationStatus until 200\n const endpoint = this.#endpoint()\n for (let i = 0; i < 60; i++) {\n try {\n const sres = await fetch(endpoint + '/ApplicationStatus')\n if (sres.ok) return\n } catch {\n // continue polling\n }\n await this.#sleep(1000)\n }\n }\n\n async #sleep(ms: number): Promise<void> {\n await new Promise((r) => setTimeout(r, ms))\n }\n\n #vecValues(field: any): number[] {\n if (field?.values && Array.isArray(field.values)) return field.values\n if (field?.cells && Array.isArray(field.cells)) {\n return field.cells.map((c: any) => c.value)\n }\n return []\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n const coll = spec.collection\n if (this.#collections.has(coll)) {\n if (ifNotExists) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED([\n 'createCollection',\n `collection already exists: ${coll}`,\n ])\n }\n this.#collections.set(coll, { dims: spec.vector.dimensions, metric: spec.vector.metric })\n try {\n await this.#deploy()\n // Wait for schema to be query-ready\n const endpoint = this.#endpoint()\n for (let i = 0; i < 30; i++) {\n try {\n const q = encodeURIComponent(`select id from ${coll} where true`)\n const res = await fetch(`${endpoint}/search/?yql=${q}&hits=1`)\n if (res.ok) break\n } catch {\n // continue polling\n }\n await this.#sleep(500)\n }\n // Clear any residual documents (redeploy preserves data)\n await this.#clearCollection(coll)\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['createCollection', String(err)])\n }\n }\n\n async #clearCollection(coll: string): Promise<void> {\n try {\n const endpoint = this.#endpoint()\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid?selection=true&cluster=docs`,\n {\n method: 'DELETE',\n }\n )\n if (!res.ok) {\n const body = (await res.json()) as any\n // Ignore 404 for non-existing collection\n if (body?.message?.includes('No document type') || res.status === 404) {\n return\n }\n }\n } catch {\n // Ignore errors during clear\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n if (!this.#collections.has(collection)) {\n if (ifExists) return\n throw new E_VECTOR_STORE_COLLECTION_FAILED([\n 'dropCollection',\n `collection not found: ${collection}`,\n ])\n }\n try {\n await this.#clearCollection(collection)\n this.#collections.delete(collection)\n if (this.#collections.size === 0) {\n // Do not redeploy an empty content cluster; just forget it locally\n return\n }\n await this.#deploy()\n } catch (err) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['dropCollection', String(err)])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n return this.#collections.has(collection)\n }\n\n async renameCollection(_from: string, _to: string): Promise<void> {\n throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(['renameCollection', 'vespa'])\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n if (plan.records.length === 0) return\n validateRecords(plan.records)\n const coll = plan.collection\n const endpoint = this.#endpoint()\n const dims = this.#opts.dimensions ?? this.#collections.get(coll)?.dims\n try {\n const ids = []\n for (const r of plan.records) {\n let vector = r.vector\n if (!vector && r.document) {\n const [v] = await this.encode([r.document], 'document')\n vector = v\n }\n if (!vector) {\n throw new E_VECTOR_STORE_UPSERT_FAILED(['Record missing vector and document'])\n }\n if (dims !== undefined && vector.length !== dims) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([dims, vector.length])\n }\n const body = {\n fields: {\n id: r.id,\n vec: { values: vector },\n document: r.document ?? '',\n metadata: r.metadata ? JSON.stringify(r.metadata) : '{}',\n },\n }\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(r.id)}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }\n )\n if (!res.ok) {\n const errData = (await res.json()) as any\n throw new Error(errData?.message ?? `HTTP ${res.status}`)\n }\n ids.push(r.id)\n }\n // Brief settle for HNSW index\n await this.#sleep(500)\n } catch (err) {\n if (\n isInstanceOf(err, 'E_VECTOR_STORE_DIMENSION_MISMATCH', E_VECTOR_STORE_DIMENSION_MISMATCH) ||\n isInstanceOf(err, 'E_VECTOR_STORE_UPSERT_FAILED', E_VECTOR_STORE_UPSERT_FAILED)\n ) {\n throw err\n }\n throw new E_VECTOR_STORE_UPSERT_FAILED([String(err)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n const coll = plan.collection\n const endpoint = this.#endpoint()\n const metric = this.#collections.get(coll)?.metric ?? this.#opts.metric ?? 'cosine'\n let queryVector: number[] | undefined\n if (plan.near) {\n if ('vector' in plan.near) {\n queryVector = plan.near.vector\n } else if ('serverText' in plan.near) {\n const [v] = await this.encode([plan.near.serverText], 'query')\n queryVector = v\n } else if ('id' in plan.near) {\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(plan.near.id)}`\n )\n if (!res.ok) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n const data = (await res.json()) as any\n const vec = this.#vecValues(data.fields?.vec)\n if (!vec || vec.length === 0) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['Referenced id not found: ' + plan.near.id])\n }\n queryVector = vec\n }\n }\n\n const offset = plan.offset ?? 0\n const topK = plan.topK ?? 10\n const k = plan.filter ? 400 : topK + offset\n const yql = queryVector\n ? `select id, document, metadata, vec from ${coll} where {targetHits:${k}}nearestNeighbor(vec, q)`\n : `select id, document, metadata, vec from ${coll} where true`\n\n try {\n const body: any = {\n yql,\n hits: k,\n }\n if (queryVector) {\n body['input.query(q)'] = queryVector\n body['ranking.profile'] = 'vector_nearest'\n }\n const res = await fetch(`${endpoint}/search/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`)\n }\n const data = (await res.json()) as any\n const root = data.root as any\n const children = root.children ?? []\n\n if (queryVector) {\n const filtered = children\n .filter((c: any) =>\n evaluateFilter(plan.filter ?? {}, this.#parseMeta(c.fields?.metadata))\n )\n .map((c: any) => {\n const vec = this.#vecValues(c.fields?.vec)\n const score = computeScore(vec, queryVector, metric)\n return { ...c.fields, score }\n })\n filtered.sort((a: any, b: any) => b.score - a.score)\n return filtered.slice(offset, offset + topK).map((d: any) => this.#project(d, plan, true))\n } else {\n const filtered = children.filter((c: any) =>\n evaluateFilter(plan.filter ?? {}, this.#parseMeta(c.fields?.metadata))\n )\n return filtered.slice(offset, offset + topK).map((d: any) => this.#project(d, plan, false))\n }\n } catch (err) {\n if ((err as any)?.message?.includes('Referenced id not found')) {\n throw err\n }\n throw new E_VECTOR_STORE_SEARCH_FAILED([String(err)])\n }\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n const coll = plan.collection\n const endpoint = this.#endpoint()\n try {\n if (plan.ids && plan.ids.length > 0) {\n for (const id of plan.ids) {\n const res = await fetch(\n `${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(id)}`,\n { method: 'DELETE' }\n )\n if (!res.ok && res.status !== 404) {\n const body = (await res.json()) as any\n throw new Error(body?.message ?? `HTTP ${res.status}`)\n }\n }\n } else if (plan.filter) {\n const yql = `select id, metadata, vec from ${coll} where true`\n const res = await fetch(`${endpoint}/search/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ yql, hits: 400 }),\n })\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`)\n }\n const data = (await res.json()) as any\n const children = data.root.children ?? []\n const targets = children\n .filter((c: any) => evaluateFilter(plan.filter!, this.#parseMeta(c.fields?.metadata)))\n .map((c: any) => c.fields?.id)\n for (const id of targets) {\n await fetch(`${endpoint}/document/v1/default/${coll}/docid/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n })\n }\n } else {\n await fetch(`${endpoint}/document/v1/default/${coll}/docid?selection=true&cluster=docs`, {\n method: 'DELETE',\n })\n }\n } catch (err) {\n throw new E_VECTOR_STORE_DELETE_FAILED([String(err)])\n }\n }\n\n #parseMeta(val: unknown): VectorMetadata {\n if (typeof val === 'string') {\n try {\n return JSON.parse(val) as VectorMetadata\n } catch {\n return {}\n }\n }\n if (val && typeof val === 'object') return val as VectorMetadata\n return {}\n }\n\n #project(doc: any, plan: SearchPlan, hasScore: boolean): VectorMatch {\n const proj = plan.projection\n const out: VectorMatch = {}\n if (proj.id) out.id = doc.id as string\n if (proj.vector) {\n const vec = this.#vecValues(doc.vec)\n if (vec && vec.length > 0) out.vector = vec.map(Number)\n }\n if (proj.document) out.document = (doc.document ?? undefined) as string | undefined\n if (proj.metadata) out.metadata = this.#parseMeta(doc.metadata)\n if (hasScore && typeof doc.score === 'number') {\n out.score = doc.score\n }\n return out\n }\n}\n"],"mappings":";;;;;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AA;EACnD,IAAI,KAAK,UAAU,IAAI,WAAW,KAAKC,WAAW,IAAI,QAAQ;EAC9D,IAAI,YAAY,OAAO,IAAI,UAAU,UACnC,IAAI,QAAQ,IAAI;EAElB,OAAO;CACT;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as isInstanceOf } from "../../tool_registry-
|
|
1
|
+
import { s as isInstanceOf } from "../../tool_registry-791Vrjtf.mjs";
|
|
2
2
|
import "../../guards.mjs";
|
|
3
3
|
import { evaluateFilter } from "./filters.mjs";
|
|
4
4
|
import { normalizeScore } from "./helpers.mjs";
|
|
@@ -133,6 +133,7 @@ var VespaVectorStore = class extends BaseVectorStore {
|
|
|
133
133
|
get #opts() {
|
|
134
134
|
return this.options;
|
|
135
135
|
}
|
|
136
|
+
/** Static availability probe: whether this adapter's runtime driver can load in the current environment. */
|
|
136
137
|
static isAvailable() {
|
|
137
138
|
return typeof process !== "undefined" && typeof fetch === "function";
|
|
138
139
|
}
|