@nhtio/adk 1.20260924.0 → 1.20260928.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 +87 -0
- package/artifact_methods-Cg0go7Q4.mjs +1 -0
- package/artifact_methods-CxeKTocm.cjs +1 -0
- package/batteries/artifacts/ecmascript.cjs +1 -1
- package/batteries/artifacts/ecmascript.mjs +1 -1
- package/batteries/artifacts/toon.cjs +1 -1
- package/batteries/artifacts/toon.mjs +1 -1
- package/batteries/artifacts/xml.cjs +1 -1
- package/batteries/artifacts/xml.mjs +1 -1
- package/batteries/artifacts/yaml.cjs +1 -1
- package/batteries/artifacts/yaml.mjs +1 -1
- package/batteries/artifacts.cjs +4 -4
- package/batteries/artifacts.mjs +4 -4
- package/batteries/dev-tools/forge.cjs +3 -3
- package/batteries/dev-tools/forge.mjs +3 -3
- package/batteries/dev-tools.cjs +3 -3
- package/batteries/dev-tools.mjs +3 -3
- package/batteries/encoding.cjs +7 -7
- package/batteries/encoding.mjs +7 -7
- package/batteries/generation/gemini/adapter.cjs +1 -1
- package/batteries/generation/gemini/adapter.mjs +1 -1
- package/batteries/generation/local_diffusion/adapter.cjs +1 -1
- package/batteries/generation/local_diffusion/adapter.mjs +1 -1
- package/batteries/generation/openai/adapter.cjs +1 -1
- package/batteries/generation/openai/adapter.mjs +1 -1
- package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
- package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
- package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
- package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
- package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
- package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
- package/batteries/llm/anthropic_messages/validation.cjs +2 -2
- package/batteries/llm/anthropic_messages/validation.mjs +2 -2
- package/batteries/llm/anthropic_messages.cjs +2 -2
- package/batteries/llm/anthropic_messages.mjs +2 -2
- package/batteries/llm/bedrock_converse/adapter.cjs +162 -21
- package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
- package/batteries/llm/bedrock_converse/adapter.mjs +162 -21
- package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
- package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
- package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
- package/batteries/llm/bedrock_converse/validation.cjs +2 -2
- package/batteries/llm/bedrock_converse/validation.mjs +2 -2
- package/batteries/llm/bedrock_converse.cjs +2 -2
- package/batteries/llm/bedrock_converse.mjs +2 -2
- package/batteries/llm/claude_code_cli/adapter.cjs +66 -25
- package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/adapter.mjs +66 -25
- package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
- package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
- package/batteries/llm/claude_code_cli/line_queue.d.ts +39 -0
- package/batteries/llm/claude_code_cli/message_id_state.d.ts +48 -0
- package/batteries/llm/claude_code_cli/types.d.ts +76 -0
- package/batteries/llm/claude_code_cli/validation.cjs +5 -2
- package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/validation.mjs +5 -2
- package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/wire.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/wire.d.ts +45 -1
- package/batteries/llm/claude_code_cli/wire.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/wrapper.d.ts +5 -4
- package/batteries/llm/claude_code_cli.cjs +2 -2
- package/batteries/llm/claude_code_cli.mjs +2 -2
- package/batteries/llm/gemini_generate_content/adapter.cjs +160 -19
- package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
- package/batteries/llm/gemini_generate_content/adapter.mjs +160 -19
- package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
- package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
- package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
- package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
- package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
- package/batteries/llm/gemini_generate_content.cjs +1 -1
- package/batteries/llm/gemini_generate_content.mjs +1 -1
- package/batteries/llm/litert_lm/adapter.cjs +6 -6
- package/batteries/llm/litert_lm/adapter.mjs +6 -6
- package/batteries/llm/litert_lm/helpers.cjs +3 -3
- package/batteries/llm/litert_lm/helpers.mjs +3 -3
- package/batteries/llm/litert_lm/validation.cjs +2 -2
- package/batteries/llm/litert_lm/validation.mjs +2 -2
- package/batteries/llm/litert_lm.cjs +1 -1
- package/batteries/llm/litert_lm.mjs +1 -1
- package/batteries/llm/ollama/adapter.cjs +6 -6
- package/batteries/llm/ollama/adapter.mjs +6 -6
- package/batteries/llm/ollama/helpers.cjs +4 -4
- package/batteries/llm/ollama/helpers.mjs +4 -4
- package/batteries/llm/ollama/validation.cjs +2 -2
- package/batteries/llm/ollama/validation.mjs +2 -2
- package/batteries/llm/ollama.cjs +2 -2
- package/batteries/llm/ollama.mjs +2 -2
- package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
- package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
- package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
- package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
- package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
- package/batteries/llm/openai_chat_completions.cjs +2 -2
- package/batteries/llm/openai_chat_completions.mjs +2 -2
- package/batteries/llm/openai_responses/adapter.cjs +6 -6
- package/batteries/llm/openai_responses/adapter.mjs +6 -6
- package/batteries/llm/openai_responses/helpers.cjs +3 -3
- package/batteries/llm/openai_responses/helpers.mjs +3 -3
- package/batteries/llm/openai_responses/validation.cjs +2 -2
- package/batteries/llm/openai_responses/validation.mjs +2 -2
- package/batteries/llm/openai_responses.cjs +2 -2
- package/batteries/llm/openai_responses.mjs +2 -2
- package/batteries/llm/transformers_js/adapter.cjs +6 -6
- package/batteries/llm/transformers_js/adapter.mjs +6 -6
- package/batteries/llm/transformers_js/helpers.cjs +3 -3
- package/batteries/llm/transformers_js/helpers.mjs +3 -3
- package/batteries/llm/transformers_js/validation.cjs +2 -2
- package/batteries/llm/transformers_js/validation.mjs +2 -2
- package/batteries/llm/transformers_js.cjs +1 -1
- package/batteries/llm/transformers_js.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
- package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
- package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
- package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
- package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
- package/batteries/llm/webllm_chat_completions.cjs +2 -2
- package/batteries/llm/webllm_chat_completions.mjs +2 -2
- package/batteries/llm.cjs +2 -2
- package/batteries/llm.mjs +2 -2
- package/batteries/media/forge.cjs +4 -4
- package/batteries/media/forge.mjs +4 -4
- package/batteries/media/lint.cjs +1 -1
- package/batteries/media/lint.mjs +1 -1
- package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
- package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
- package/batteries/orchestration/executor.cjs +2 -2
- package/batteries/orchestration/executor.mjs +2 -2
- package/batteries/orchestration/forge.cjs +4 -4
- package/batteries/orchestration/forge.mjs +4 -4
- package/batteries/orchestration/validation.cjs +2 -2
- package/batteries/orchestration/validation.mjs +2 -2
- package/batteries/orchestration.cjs +4 -4
- package/batteries/orchestration.mjs +4 -4
- package/batteries/sandbox/js.cjs +1 -1
- package/batteries/sandbox/js.mjs +1 -1
- package/batteries/sandbox/tools.cjs +1 -1
- package/batteries/sandbox/tools.mjs +1 -1
- package/batteries/sandbox.cjs +3 -3
- package/batteries/sandbox.mjs +3 -3
- package/batteries/skills.cjs +9 -9
- package/batteries/skills.mjs +9 -9
- package/batteries/tools/_shared.cjs +1 -1
- package/batteries/tools/_shared.mjs +1 -1
- package/batteries/tools/color.cjs +2 -2
- package/batteries/tools/color.mjs +2 -2
- package/batteries/tools/comparison.cjs +2 -2
- package/batteries/tools/comparison.mjs +2 -2
- package/batteries/tools/data_structure.cjs +2 -2
- package/batteries/tools/data_structure.mjs +2 -2
- package/batteries/tools/datetime_extended.cjs +3 -3
- package/batteries/tools/datetime_extended.mjs +3 -3
- package/batteries/tools/datetime_math.cjs +3 -3
- package/batteries/tools/datetime_math.mjs +3 -3
- package/batteries/tools/encoding.cjs +2 -2
- package/batteries/tools/encoding.mjs +2 -2
- package/batteries/tools/formatting.cjs +2 -2
- package/batteries/tools/formatting.mjs +2 -2
- package/batteries/tools/geo_basics.cjs +2 -2
- package/batteries/tools/geo_basics.mjs +2 -2
- package/batteries/tools/math.cjs +2 -2
- package/batteries/tools/math.mjs +2 -2
- package/batteries/tools/memory.cjs +5 -5
- package/batteries/tools/memory.mjs +5 -5
- package/batteries/tools/parsing.cjs +3 -3
- package/batteries/tools/parsing.mjs +3 -3
- package/batteries/tools/retrievables.cjs +5 -5
- package/batteries/tools/retrievables.mjs +5 -5
- package/batteries/tools/scrapper.cjs +1 -1
- package/batteries/tools/scrapper.mjs +1 -1
- package/batteries/tools/searxng.cjs +1 -1
- package/batteries/tools/searxng.mjs +1 -1
- package/batteries/tools/standing_instructions.cjs +3 -3
- package/batteries/tools/standing_instructions.mjs +3 -3
- package/batteries/tools/statistics.cjs +3 -3
- package/batteries/tools/statistics.mjs +3 -3
- package/batteries/tools/string_processing.cjs +2 -2
- package/batteries/tools/string_processing.mjs +2 -2
- package/batteries/tools/structured_data.cjs +2 -2
- package/batteries/tools/structured_data.mjs +2 -2
- 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 +3 -3
- package/batteries/tools/time.mjs +3 -3
- package/batteries/tools/unit_conversion.cjs +2 -2
- package/batteries/tools/unit_conversion.mjs +2 -2
- package/batteries/tools.cjs +2 -2
- package/batteries/tools.mjs +2 -2
- package/batteries/validation.cjs +4 -4
- package/batteries/validation.mjs +4 -4
- package/batteries/vector/conformance.cjs +59 -0
- package/batteries/vector/conformance.cjs.map +1 -1
- package/batteries/vector/conformance.mjs +59 -0
- package/batteries/vector/conformance.mjs.map +1 -1
- package/batteries/vector/lancedb.cjs +1 -1
- package/batteries/vector/lancedb.cjs.map +1 -1
- package/batteries/vector/lancedb.mjs +1 -1
- package/batteries/vector/lancedb.mjs.map +1 -1
- package/batteries/vector/retrievable.cjs +1 -1
- package/batteries/vector/retrievable.mjs +1 -1
- package/batteries/vector/sqlite_vec/index.d.ts +1 -1
- package/batteries/vector/sqlite_vec.cjs +19 -30
- package/batteries/vector/sqlite_vec.cjs.map +1 -1
- package/batteries/vector/sqlite_vec.mjs +20 -31
- package/batteries/vector/sqlite_vec.mjs.map +1 -1
- package/batteries.cjs +4 -4
- package/batteries.mjs +4 -4
- package/{chat_common-B7fvGTKv.cjs → chat_common-CNayzS1V.cjs} +2 -2
- package/{chat_common-B7fvGTKv.cjs.map → chat_common-CNayzS1V.cjs.map} +1 -1
- package/{chat_common-CeoHwSsz.mjs → chat_common-DKw8FDol.mjs} +2 -2
- package/{chat_common-CeoHwSsz.mjs.map → chat_common-DKw8FDol.mjs.map} +1 -1
- package/claude-code-cli-wrapper.cjs +104 -22
- package/claude-code-cli-wrapper.cjs.map +1 -1
- package/claude-code-cli-wrapper.mjs +104 -22
- package/claude-code-cli-wrapper.mjs.map +1 -1
- package/{common-7gCR3zQu.cjs → common-CqetsItm.cjs} +7 -7
- package/{common-7gCR3zQu.cjs.map → common-CqetsItm.cjs.map} +1 -1
- package/{common-B5maOoF_.mjs → common-oI1niK9Z.mjs} +7 -7
- package/{common-B5maOoF_.mjs.map → common-oI1niK9Z.mjs.map} +1 -1
- package/common.cjs +7 -7
- package/common.mjs +7 -7
- package/{dispatch_runner-DO7jo_gl.mjs → dispatch_runner-BZDXUe0G.mjs} +5 -5
- package/{dispatch_runner-DO7jo_gl.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
- package/{dispatch_runner-FlriTyoq.cjs → dispatch_runner-DDUxXJC3.cjs} +5 -5
- package/{dispatch_runner-FlriTyoq.cjs.map → dispatch_runner-DDUxXJC3.cjs.map} +1 -1
- package/dispatch_runner.cjs +1 -1
- package/dispatch_runner.mjs +1 -1
- package/{ecmascript-bgwVyZG1.mjs → ecmascript-B9Z2C24U.mjs} +3 -3
- package/{ecmascript-bgwVyZG1.mjs.map → ecmascript-B9Z2C24U.mjs.map} +1 -1
- package/{ecmascript-BydSB03Y.cjs → ecmascript-BYfmjg7y.cjs} +3 -3
- package/{ecmascript-BydSB03Y.cjs.map → ecmascript-BYfmjg7y.cjs.map} +1 -1
- package/eslint/rules.cjs +1 -1
- package/eslint/rules.mjs +1 -1
- package/eslint.cjs +2 -2
- package/eslint.mjs +2 -2
- package/exceptions.cjs +1 -1
- package/exceptions.mjs +1 -1
- package/forge.cjs +2 -2
- package/forge.mjs +2 -2
- package/guards.cjs +7 -7
- package/guards.mjs +7 -7
- package/{helpers-Dcp4CrOz.cjs → helpers-DPlh_7Bn.cjs} +3 -3
- package/{helpers-Dcp4CrOz.cjs.map → helpers-DPlh_7Bn.cjs.map} +1 -1
- package/{helpers-C1T0DV8Q.mjs → helpers-mbn_EsDV.mjs} +3 -3
- package/{helpers-C1T0DV8Q.mjs.map → helpers-mbn_EsDV.mjs.map} +1 -1
- package/index.cjs +11 -11
- package/index.mjs +11 -11
- package/mcp/adk-docs-corpus.json +2 -2
- package/package.json +425 -425
- package/{retrievable-BBwiACtw.cjs → retrievable-Bq-O3k6r.cjs} +3 -3
- package/{retrievable-BBwiACtw.cjs.map → retrievable-Bq-O3k6r.cjs.map} +1 -1
- package/{retrievable-CrGKx4sc.mjs → retrievable-CXTAUuuv.mjs} +3 -3
- package/{retrievable-CrGKx4sc.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
- package/{scrapper-BibKj8qE.cjs → scrapper-B8xG9lTD.cjs} +4 -4
- package/{scrapper-BibKj8qE.cjs.map → scrapper-B8xG9lTD.cjs.map} +1 -1
- package/{scrapper-_JzgbLG5.mjs → scrapper-DiQ5FfDL.mjs} +4 -4
- package/{scrapper-_JzgbLG5.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
- package/{searxng-D-nA2gEI.mjs → searxng-BFTJ6rTE.mjs} +4 -4
- package/{searxng-D-nA2gEI.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
- package/{searxng-C6xrLW-v.cjs → searxng-EJhWRnIE.cjs} +4 -4
- package/{searxng-C6xrLW-v.cjs.map → searxng-EJhWRnIE.cjs.map} +1 -1
- package/server.json +2 -2
- package/skills/adk-assembly/SKILL.md +2 -2
- package/{spooled_artifact-BLgbGT8b.cjs → spooled_artifact---DmicFW.cjs} +384 -384
- package/spooled_artifact---DmicFW.cjs.map +1 -0
- package/{spooled_artifact-BkOe4-j-.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
- package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
- package/spooled_artifact.cjs +2 -2
- package/spooled_artifact.mjs +2 -2
- package/{spooled_markdown_artifact-8zdejfcJ.cjs → spooled_markdown_artifact-Rjzj-kyh.cjs} +3 -3
- package/{spooled_markdown_artifact-8zdejfcJ.cjs.map → spooled_markdown_artifact-Rjzj-kyh.cjs.map} +1 -1
- package/{spooled_markdown_artifact-Dnl-lCGv.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
- package/{spooled_markdown_artifact-Dnl-lCGv.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
- package/{thought-BrQt6HAb.mjs → thought-CxSaF6Xf.mjs} +3 -3
- package/{thought-BrQt6HAb.mjs.map → thought-CxSaF6Xf.mjs.map} +1 -1
- package/{thought-COeZTQ-B.cjs → thought-Dp3sMWW6.cjs} +3 -3
- package/{thought-COeZTQ-B.cjs.map → thought-Dp3sMWW6.cjs.map} +1 -1
- package/{tokenizable-DDIdXbJN.cjs → tokenizable-BcodRtoW.cjs} +29 -29
- package/{tokenizable-DDIdXbJN.cjs.map → tokenizable-BcodRtoW.cjs.map} +1 -1
- package/{tokenizable-xPXj1AQX.mjs → tokenizable-VB4Av8GF.mjs} +30 -30
- package/{tokenizable-xPXj1AQX.mjs.map → tokenizable-VB4Av8GF.mjs.map} +1 -1
- package/{tool_call-JbjeUpRK.cjs → tool_call-B9px4W9k.cjs} +4 -4
- package/{tool_call-JbjeUpRK.cjs.map → tool_call-B9px4W9k.cjs.map} +1 -1
- package/{tool_call-8crmZsO8.mjs → tool_call-Cfaj-6zK.mjs} +4 -4
- package/{tool_call-8crmZsO8.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
- package/{tools-BC4NJqZD.mjs → tools-D0MBDh2R.mjs} +6 -6
- package/{tools-BC4NJqZD.mjs.map → tools-D0MBDh2R.mjs.map} +1 -1
- package/{tools-D4mdzi0a.cjs → tools-aNbi6JyA.cjs} +6 -6
- package/{tools-D4mdzi0a.cjs.map → tools-aNbi6JyA.cjs.map} +1 -1
- package/{toon-BA9Q7NHG.mjs → toon-BSTQnHed.mjs} +5 -5
- package/{toon-BA9Q7NHG.mjs.map → toon-BSTQnHed.mjs.map} +1 -1
- package/{toon-b-0pFKZ8.cjs → toon-DmLwZ6H1.cjs} +5 -5
- package/{toon-b-0pFKZ8.cjs.map → toon-DmLwZ6H1.cjs.map} +1 -1
- package/{turn_runner-BmVXcBZ2.mjs → turn_runner-BHHD6h77.mjs} +5 -5
- package/{turn_runner-BmVXcBZ2.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
- package/{turn_runner-DX-3s3ih.cjs → turn_runner-Dj7JsUTQ.cjs} +5 -5
- package/{turn_runner-DX-3s3ih.cjs.map → turn_runner-Dj7JsUTQ.cjs.map} +1 -1
- package/turn_runner.cjs +1 -1
- package/turn_runner.mjs +1 -1
- package/{xml-B1JIGLpU.mjs → xml-CYseDztH.mjs} +5 -5
- package/{xml-B1JIGLpU.mjs.map → xml-CYseDztH.mjs.map} +1 -1
- package/{xml-fvwTsoRv.cjs → xml-zJul8jMQ.cjs} +5 -5
- package/{xml-fvwTsoRv.cjs.map → xml-zJul8jMQ.cjs.map} +1 -1
- package/{yaml-1mP4uxdf.mjs → yaml-BPBoiOjx.mjs} +5 -5
- package/{yaml-1mP4uxdf.mjs.map → yaml-BPBoiOjx.mjs.map} +1 -1
- package/{yaml-DPUTumla.cjs → yaml-D0PzoRAr.cjs} +5 -5
- package/{yaml-DPUTumla.cjs.map → yaml-D0PzoRAr.cjs.map} +1 -1
- package/artifact_methods-7KatxCSd.cjs +0 -1
- package/artifact_methods-q52ETLwI.mjs +0 -1
- package/spooled_artifact-BLgbGT8b.cjs.map +0 -1
- package/spooled_artifact-BkOe4-j-.mjs.map +0 -1
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { evaluateFilter } from "./filters.mjs";
|
|
2
2
|
import { normalizeScore } from "./helpers.mjs";
|
|
3
|
-
import { E_VECTOR_STORE_COLLECTION_FAILED, E_VECTOR_STORE_CONNECTION_FAILED, E_VECTOR_STORE_DELETE_FAILED, E_VECTOR_STORE_DIMENSION_MISMATCH, E_VECTOR_STORE_DRIVER_UNAVAILABLE, E_VECTOR_STORE_SEARCH_FAILED, E_VECTOR_STORE_UPSERT_FAILED } from "./exceptions.mjs";
|
|
3
|
+
import { E_VECTOR_STORE_COLLECTION_FAILED, E_VECTOR_STORE_CONNECTION_FAILED, E_VECTOR_STORE_DELETE_FAILED, E_VECTOR_STORE_DIMENSION_MISMATCH, E_VECTOR_STORE_DRIVER_UNAVAILABLE, E_VECTOR_STORE_SEARCH_FAILED, E_VECTOR_STORE_UNSUPPORTED_OPERATION, E_VECTOR_STORE_UPSERT_FAILED } from "./exceptions.mjs";
|
|
4
4
|
import { BaseVectorStore } from "./contract.mjs";
|
|
5
5
|
import { validateRecords } from "./validation.mjs";
|
|
6
6
|
//#region src/batteries/vector/sqlite_vec/index.ts
|
|
7
7
|
/**
|
|
8
8
|
* @module @nhtio/adk/batteries/vector/sqlite_vec
|
|
9
9
|
*/
|
|
10
|
+
var ident = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
10
11
|
var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
11
12
|
capabilities = {
|
|
12
13
|
transactions: true,
|
|
13
14
|
namedVectors: false,
|
|
14
|
-
rename:
|
|
15
|
+
rename: false,
|
|
15
16
|
rawSql: true,
|
|
16
17
|
builtInEncoding: false,
|
|
17
18
|
consistency: {
|
|
@@ -80,8 +81,8 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
80
81
|
await this.connect();
|
|
81
82
|
const { collection, vector } = spec;
|
|
82
83
|
const dims = vector.dimensions;
|
|
83
|
-
const tbl =
|
|
84
|
-
const metaTbl =
|
|
84
|
+
const tbl = ident(collection);
|
|
85
|
+
const metaTbl = ident(collection + "__meta");
|
|
85
86
|
const { db } = this;
|
|
86
87
|
const exists = await this.hasCollection(collection);
|
|
87
88
|
if (!ifNotExists && exists) throw new E_VECTOR_STORE_COLLECTION_FAILED(["create", "collection exists"]);
|
|
@@ -95,8 +96,8 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
95
96
|
}
|
|
96
97
|
async dropCollection(collection, ifExists) {
|
|
97
98
|
await this.connect();
|
|
98
|
-
const tbl =
|
|
99
|
-
const metaTbl =
|
|
99
|
+
const tbl = ident(collection);
|
|
100
|
+
const metaTbl = ident(collection + "__meta");
|
|
100
101
|
if (!await this.hasCollection(collection)) {
|
|
101
102
|
if (!ifExists) throw new E_VECTOR_STORE_COLLECTION_FAILED(["drop", "collection does not exist"]);
|
|
102
103
|
return;
|
|
@@ -119,22 +120,8 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
119
120
|
return false;
|
|
120
121
|
}
|
|
121
122
|
}
|
|
122
|
-
async renameCollection(
|
|
123
|
-
|
|
124
|
-
if (!await this.hasCollection(from)) throw new E_VECTOR_STORE_COLLECTION_FAILED(["rename", "source collection does not exist"]);
|
|
125
|
-
if (await this.hasCollection(to)) throw new E_VECTOR_STORE_COLLECTION_FAILED(["rename", "target collection already exists"]);
|
|
126
|
-
const { db } = this;
|
|
127
|
-
try {
|
|
128
|
-
db.exec(`ALTER TABLE "${from}" RENAME TO "${to}"`);
|
|
129
|
-
db.exec(`ALTER TABLE "${from}__meta" RENAME TO "${to}__meta"`);
|
|
130
|
-
const dims = this.#_dims.get(from);
|
|
131
|
-
if (dims !== void 0) {
|
|
132
|
-
this.#_dims.set(to, dims);
|
|
133
|
-
this.#_dims.delete(from);
|
|
134
|
-
}
|
|
135
|
-
} catch (e) {
|
|
136
|
-
throw new E_VECTOR_STORE_COLLECTION_FAILED(["rename", e?.message ?? String(e)]);
|
|
137
|
-
}
|
|
123
|
+
async renameCollection(_from, _to) {
|
|
124
|
+
throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(["renameCollection", "sqlite_vec"]);
|
|
138
125
|
}
|
|
139
126
|
async executeUpsert(plan) {
|
|
140
127
|
await this.connect();
|
|
@@ -157,11 +144,13 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
157
144
|
metadata: r.metadata
|
|
158
145
|
});
|
|
159
146
|
}
|
|
160
|
-
const
|
|
161
|
-
const
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
const
|
|
147
|
+
const metaTbl = ident(collection + "__meta");
|
|
148
|
+
const tbl = ident(collection);
|
|
149
|
+
const stmtMetaInsert = db.prepare(`INSERT INTO ${metaTbl} (id, document, metadata) VALUES (?, ?, ?)`);
|
|
150
|
+
const stmtMetaUpdate = db.prepare(`UPDATE ${metaTbl} SET document = ?, metadata = ? WHERE id = ?`);
|
|
151
|
+
const stmtRowid = db.prepare(`SELECT rowid FROM ${metaTbl} WHERE id = ?`);
|
|
152
|
+
const stmtVecDelete = db.prepare(`DELETE FROM ${tbl} WHERE rowid = ?`);
|
|
153
|
+
const stmtVecInsert = db.prepare(`INSERT INTO ${tbl} (rowid, embedding) VALUES (?, ?)`);
|
|
165
154
|
const txn = db.transaction(() => {
|
|
166
155
|
for (const r of resolvedRows) {
|
|
167
156
|
const buf = new Float32Array(r.vector);
|
|
@@ -189,8 +178,8 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
189
178
|
await this.connect();
|
|
190
179
|
const { db } = this;
|
|
191
180
|
const collection = plan.collection;
|
|
192
|
-
const tbl =
|
|
193
|
-
const metaTbl =
|
|
181
|
+
const tbl = ident(collection);
|
|
182
|
+
const metaTbl = ident(collection + "__meta");
|
|
194
183
|
const near = plan.near;
|
|
195
184
|
const limit = (plan.offset ?? 0) + plan.topK;
|
|
196
185
|
try {
|
|
@@ -268,8 +257,8 @@ var SqliteVecVectorStore = class extends BaseVectorStore {
|
|
|
268
257
|
async executeDelete(plan) {
|
|
269
258
|
await this.connect();
|
|
270
259
|
const collection = plan.collection;
|
|
271
|
-
const metaTbl =
|
|
272
|
-
const tbl =
|
|
260
|
+
const metaTbl = ident(collection + "__meta");
|
|
261
|
+
const tbl = ident(collection);
|
|
273
262
|
const { db } = this;
|
|
274
263
|
try {
|
|
275
264
|
if (plan.ids && plan.ids.length > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite_vec.mjs","names":["#opts","#_cache","#_dims"],"sources":["../../../src/batteries/vector/sqlite_vec/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/sqlite_vec\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { validateRecords } from '../validation'\nimport { BaseVectorStore, CallableVectorStore } from '../contract'\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} from '../exceptions'\nimport type { SearchPlan, UpsertPlan, DeletePlan, CollectionSpec } from '../plan'\nimport type { VectorMatch, VectorStoreCapabilities, BaseVectorStoreOptions } from '../types'\n\n/** Construction options for {@link SqliteVecVectorStore}. */\nexport interface SqliteVecVectorStoreOptions extends BaseVectorStoreOptions {\n /** Database location: a filesystem path, or `':memory:'` for an in-memory database. */\n connection: {\n path: string\n }\n}\n\ninterface VecRow {\n rowid: bigint\n distance: number\n}\n\ninterface CachedStore {\n db: any\n drivers?: { Database: any; sqliteVec: any }\n}\n\nexport class SqliteVecVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: true,\n namedVectors: false,\n rename: true,\n rawSql: true,\n builtInEncoding: false,\n // Strongly consistent (local file/in-memory): visible on resolve, so the option is a no-op.\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #_cache: CachedStore | null = null\n #_dims: Map<string, number> = new Map()\n\n constructor(options: SqliteVecVectorStoreOptions) {\n super(options)\n }\n\n get #opts(): SqliteVecVectorStoreOptions {\n return this.options as SqliteVecVectorStoreOptions\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.#_cache) {\n return\n }\n\n let Database: any\n let sqliteVec: any\n\n try {\n const mod1 = await import('better-sqlite3')\n Database = mod1.default\n } catch (e) {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['better-sqlite3 / sqlite-vec'])\n }\n\n try {\n sqliteVec = await import('sqlite-vec')\n } catch (e) {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['better-sqlite3 / sqlite-vec'])\n }\n\n const path = this.#opts.connection?.path ?? ':memory:'\n let db: any\n\n try {\n db = new Database(path)\n } catch (e: any) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([e?.message ?? String(e)])\n }\n\n sqliteVec.load(db)\n\n this.#_cache = { db, drivers: { Database, sqliteVec } }\n }\n\n async close(): Promise<void> {\n if (this.#_cache?.db) {\n this.#_cache.db.close()\n this.#_cache = null\n }\n }\n\n /** The underlying SQLite database handle; throws if the store is not connected. */\n get db(): any {\n if (!this.#_cache?.db) {\n throw new Error('Not connected')\n }\n return this.#_cache.db\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n await this.connect()\n const { collection, vector } = spec\n const dims = vector.dimensions\n const tbl = `\"${collection}\"`\n const metaTbl = `\"${collection}__meta\"`\n\n const { db } = this\n\n const exists = await this.hasCollection(collection)\n if (!ifNotExists && exists) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['create', 'collection exists'])\n }\n\n try {\n db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${tbl} USING vec0(embedding float[${dims}])`)\n db.exec(\n `CREATE TABLE IF NOT EXISTS ${metaTbl} (rowid INTEGER PRIMARY KEY, id TEXT UNIQUE, document TEXT, metadata TEXT)`\n )\n this.#_dims.set(collection, dims)\n } catch (e: any) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['create', e?.message ?? String(e)])\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n await this.connect()\n const tbl = `\"${collection}\"`\n const metaTbl = `\"${collection}__meta\"`\n\n const has = await this.hasCollection(collection)\n if (!has) {\n if (!ifExists) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['drop', 'collection does not exist'])\n }\n return\n }\n\n const { db } = this\n try {\n db.exec(`DROP TABLE IF EXISTS ${tbl}`)\n db.exec(`DROP TABLE IF EXISTS ${metaTbl}`)\n this.#_dims.delete(collection)\n } catch (e: any) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['drop', e?.message ?? String(e)])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n await this.connect()\n const { db } = this\n try {\n const res: any = db\n .prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`)\n .get(collection)\n return !!res?.name\n } catch {\n return false\n }\n }\n\n async renameCollection(from: string, to: string): Promise<void> {\n await this.connect()\n const hasFrom = await this.hasCollection(from)\n if (!hasFrom) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['rename', 'source collection does not exist'])\n }\n\n const hasTo = await this.hasCollection(to)\n if (hasTo) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['rename', 'target collection already exists'])\n }\n\n const { db } = this\n try {\n db.exec(`ALTER TABLE \"${from}\" RENAME TO \"${to}\"`)\n db.exec(`ALTER TABLE \"${from}__meta\" RENAME TO \"${to}__meta\"`)\n const dims = this.#_dims.get(from)\n if (dims !== undefined) {\n this.#_dims.set(to, dims)\n this.#_dims.delete(from)\n }\n } catch (e: any) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['rename', e?.message ?? String(e)])\n }\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n await this.connect()\n validateRecords(plan.records)\n\n const collection = plan.collection\n const dims = this.#_dims.get(collection)\n const { db } = this\n\n const resolvedRows: {\n id: string\n vector: number[]\n document?: string\n metadata?: Record<string, unknown>\n }[] = []\n\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\n if (vector && dims !== undefined && vector.length !== dims) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([dims, vector.length])\n }\n\n resolvedRows.push({\n id: r.id,\n vector: vector ?? [],\n document: r.document,\n metadata: r.metadata as Record<string, unknown> | undefined,\n })\n }\n\n const stmtMetaInsert = db.prepare(\n `INSERT INTO \"${collection}__meta\" (id, document, metadata) VALUES (?, ?, ?)`\n )\n const stmtMetaUpdate = db.prepare(\n `UPDATE \"${collection}__meta\" SET document = ?, metadata = ? WHERE id = ?`\n )\n const stmtRowid = db.prepare(`SELECT rowid FROM \"${collection}__meta\" WHERE id = ?`)\n const stmtVecDelete = db.prepare(`DELETE FROM \"${collection}\" WHERE rowid = ?`)\n const stmtVecInsert = db.prepare(`INSERT INTO \"${collection}\" (rowid, embedding) VALUES (?, ?)`)\n\n const txn = db.transaction(() => {\n for (const r of resolvedRows) {\n const buf = new Float32Array(r.vector)\n let rowid: bigint | undefined\n\n const rowidRes: any = stmtRowid.get(r.id)\n if (rowidRes?.rowid) {\n rowid = BigInt(rowidRes.rowid)\n stmtMetaUpdate.run(r.document ?? null, JSON.stringify(r.metadata ?? {}), r.id)\n stmtVecDelete.run(rowid)\n stmtVecInsert.run(rowid, buf)\n } else {\n const insertMeta = stmtMetaInsert.run(\n r.id,\n r.document ?? null,\n JSON.stringify(r.metadata ?? {})\n )\n rowid = BigInt(insertMeta.lastInsertRowid)\n stmtVecInsert.run(rowid, buf)\n }\n }\n })\n\n try {\n txn()\n } catch (e: any) {\n throw new E_VECTOR_STORE_UPSERT_FAILED([e?.message ?? String(e)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n await this.connect()\n const { db } = this\n const collection = plan.collection\n const tbl = `\"${collection}\"`\n const metaTbl = `\"${collection}__meta\"`\n\n const near = plan.near\n const limit = (plan.offset ?? 0) + plan.topK\n\n try {\n if (near) {\n let qvec: number[] | undefined\n\n if ('vector' in near) {\n qvec = near.vector\n } else if ('serverText' in near) {\n const [v] = await this.encode([near.serverText], 'query')\n qvec = v\n } else if ('id' in near) {\n const refRow: any = db.prepare(`SELECT rowid FROM ${metaTbl} WHERE id = ?`).get(near.id)\n if (refRow?.rowid) {\n const refVecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(BigInt(refRow.rowid))\n if (refVecRes?.embedding) {\n qvec = Array.from(new Float32Array(refVecRes.embedding.buffer || refVecRes.embedding))\n }\n }\n }\n\n if (!qvec) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['no query vector provided'])\n }\n\n const matchClause = `embedding MATCH ? ORDER BY distance LIMIT ${limit}`\n const matchBuf = new Float32Array(qvec)\n\n const matches: VecRow[] = []\n const stmtMatch = db.prepare(`SELECT rowid, distance FROM ${tbl} WHERE ${matchClause}`)\n for (const row of stmtMatch.iterate(matchBuf)) {\n matches.push({ rowid: BigInt(row.rowid), distance: row.distance })\n }\n\n let results: VectorMatch[] = []\n for (const m of matches) {\n const meta: any = db\n .prepare(`SELECT rowid, id, document, metadata FROM ${metaTbl} WHERE rowid = ?`)\n .get(m.rowid)\n if (!meta) {\n continue\n }\n\n const parsedMeta =\n typeof meta.metadata === 'string' ? JSON.parse(meta.metadata) : meta.metadata\n\n if (plan.filter && !evaluateFilter(plan.filter, parsedMeta as any)) {\n continue\n }\n\n let score = normalizeScore(\n Number(m.distance),\n this.options.metric ?? 'euclidean',\n 'distance'\n )\n\n const proj: VectorMatch = {}\n if (plan.projection.id) proj.id = meta.id\n if (plan.projection.vector) {\n const vecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(m.rowid)\n if (vecRes?.embedding) {\n proj.vector = Array.from(\n new Float32Array(vecRes.embedding.buffer || vecRes.embedding)\n )\n }\n }\n if (plan.projection.document && meta.document !== undefined) proj.document = meta.document\n if (plan.projection.metadata && parsedMeta !== undefined)\n proj.metadata = parsedMeta as any\n if (score !== undefined) proj.score = score\n results.push(proj)\n }\n\n const offset = plan.offset ?? 0\n return results.slice(offset, offset + plan.topK)\n } else {\n const rows: any[] = db.prepare(`SELECT rowid, id, document, metadata FROM ${metaTbl}`).all()\n let scored: { row: any; score?: number }[] = []\n\n for (const row of rows) {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n\n if (plan.filter && !evaluateFilter(plan.filter, parsedMeta as any)) {\n continue\n }\n\n scored.push({ row, score: undefined })\n }\n\n const offset = plan.offset ?? 0\n const limited = scored.slice(offset, offset + plan.topK)\n\n return limited.map(({ row }) => {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n const out: VectorMatch = {}\n\n if (plan.projection.id) out.id = row.id\n\n if (plan.projection.vector) {\n const vecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(BigInt(row.rowid))\n if (vecRes?.embedding) {\n out.vector = Array.from(new Float32Array(vecRes.embedding.buffer || vecRes.embedding))\n }\n }\n\n if (plan.projection.document && row.document !== undefined) out.document = row.document\n if (plan.projection.metadata && parsedMeta !== undefined) out.metadata = parsedMeta as any\n\n return out\n })\n }\n } catch (e: any) {\n throw new E_VECTOR_STORE_SEARCH_FAILED([e?.message ?? String(e)])\n }\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n await this.connect()\n const collection = plan.collection\n const metaTbl = `\"${collection}__meta\"`\n const tbl = `\"${collection}\"`\n\n const { db } = this\n\n try {\n if (plan.ids && plan.ids.length > 0) {\n const stmtIds = db.prepare(\n `SELECT rowid, metadata FROM ${metaTbl} WHERE id IN (${plan.ids.map(() => '?').join(', ')})`\n )\n const rowids: bigint[] = stmtIds.all(...plan.ids).map((r: any) => BigInt(r.rowid))\n if (rowids.length > 0) {\n const rowidPlaceholders = rowids.map(() => '?').join(', ')\n db.prepare(`DELETE FROM ${metaTbl} WHERE rowid IN (${rowidPlaceholders})`).run(...rowids)\n db.prepare(`DELETE FROM ${tbl} WHERE rowid IN (${rowidPlaceholders})`).run(...rowids)\n }\n } else if (plan.filter) {\n const rows: any[] = db.prepare(`SELECT rowid, metadata FROM ${metaTbl}`).all()\n const toDeleteRowids: bigint[] = []\n\n for (const row of rows) {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n if (evaluateFilter(plan.filter, parsedMeta as any)) {\n toDeleteRowids.push(BigInt(row.rowid))\n }\n }\n\n if (toDeleteRowids.length > 0) {\n const rowidPlaceholders = toDeleteRowids.map(() => '?').join(', ')\n db.prepare(`DELETE FROM ${metaTbl} WHERE rowid IN (${rowidPlaceholders})`).run(\n ...toDeleteRowids\n )\n db.prepare(`DELETE FROM ${tbl} WHERE rowid IN (${rowidPlaceholders})`).run(\n ...toDeleteRowids\n )\n }\n } else {\n db.exec(`DELETE FROM ${metaTbl}`)\n db.exec(`DELETE FROM ${tbl}`)\n }\n } catch (e: any) {\n throw new E_VECTOR_STORE_DELETE_FAILED([e?.message ?? String(e)])\n }\n }\n\n async transaction(fn: (tx: CallableVectorStore) => Promise<void>): Promise<void> {\n await this.connect()\n const { db } = this\n\n db.exec('BEGIN')\n try {\n await fn(this.asCallable())\n db.exec('COMMIT')\n } catch (e) {\n db.exec('ROLLBACK')\n throw e\n }\n }\n}\n"],"mappings":";;;;;;;;;AAsCA,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,UAA8B;CAC9B,yBAA8B,IAAI,IAAI;CAEtC,YAAY,SAAsC;EAChD,MAAM,OAAO;CACf;CAEA,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,SACP;EAGF,IAAI;EACJ,IAAI;EAEJ,IAAI;GAEF,YAAW,MADQ,OAAO,mBACV;EAClB,SAAS,GAAG;GACV,MAAM,IAAI,kCAAkC,CAAC,6BAA6B,CAAC;EAC7E;EAEA,IAAI;GACF,YAAY,MAAM,OAAO;EAC3B,SAAS,GAAG;GACV,MAAM,IAAI,kCAAkC,CAAC,6BAA6B,CAAC;EAC7E;EAEA,MAAM,OAAO,KAAK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KAAK,UAAU;GAClB,MAAM;EACR;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"sqlite_vec.mjs","names":["#opts","#_cache","#_dims"],"sources":["../../../src/batteries/vector/sqlite_vec/index.ts"],"sourcesContent":["/**\n * @module @nhtio/adk/batteries/vector/sqlite_vec\n */\n\nimport { evaluateFilter } from '../filters'\nimport { normalizeScore } from '../helpers'\nimport { validateRecords } from '../validation'\nimport { BaseVectorStore, CallableVectorStore } from '../contract'\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 { VectorMatch, VectorStoreCapabilities, BaseVectorStoreOptions } from '../types'\n\n// A double-quoted SQL identifier (table/column), escaping embedded quotes.\nconst ident = (name: string): string => `\"${name.replace(/\"/g, '\"\"')}\"`\n\n/** Construction options for {@link SqliteVecVectorStore}. */\nexport interface SqliteVecVectorStoreOptions extends BaseVectorStoreOptions {\n /** Database location: a filesystem path, or `':memory:'` for an in-memory database. */\n connection: {\n path: string\n }\n}\n\ninterface VecRow {\n rowid: bigint\n distance: number\n}\n\ninterface CachedStore {\n db: any\n drivers?: { Database: any; sqliteVec: any }\n}\n\nexport class SqliteVecVectorStore extends BaseVectorStore {\n readonly capabilities: VectorStoreCapabilities = {\n transactions: true,\n namedVectors: false,\n // sqlite-vec 0.1.9 implements no `xRename` hook, so `ALTER TABLE … RENAME TO` on the vec0 table\n // succeeds but renames only the virtual table's own entry, never its shadow tables\n // (`_chunks`/`_info`/`_rowids`/`_vector_chunks00`), so a\n // \"renamed\" collection is left unsearchable (`no such table: main.<new>_chunks`) with no error\n // at rename time. Finishing the job by hand isn't possible either — the core shadow tables\n // (`_chunks`/`_info`/`_rowids`) reject a direct rename outright (`table <name>_chunks may not be\n // altered`). sqlite-vec 0.1.9 has no supported rename, so renameCollection throws instead of\n // leaving a broken collection.\n rename: false,\n rawSql: true,\n builtInEncoding: false,\n // Strongly consistent (local file/in-memory): visible on resolve, so the option is a no-op.\n consistency: { configurable: false, default: 'strong', modes: ['strong'] },\n }\n\n #_cache: CachedStore | null = null\n #_dims: Map<string, number> = new Map()\n\n constructor(options: SqliteVecVectorStoreOptions) {\n super(options)\n }\n\n get #opts(): SqliteVecVectorStoreOptions {\n return this.options as SqliteVecVectorStoreOptions\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.#_cache) {\n return\n }\n\n let Database: any\n let sqliteVec: any\n\n try {\n const mod1 = await import('better-sqlite3')\n Database = mod1.default\n } catch (e) {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['better-sqlite3 / sqlite-vec'])\n }\n\n try {\n sqliteVec = await import('sqlite-vec')\n } catch (e) {\n throw new E_VECTOR_STORE_DRIVER_UNAVAILABLE(['better-sqlite3 / sqlite-vec'])\n }\n\n const path = this.#opts.connection?.path ?? ':memory:'\n let db: any\n\n try {\n db = new Database(path)\n } catch (e: any) {\n throw new E_VECTOR_STORE_CONNECTION_FAILED([e?.message ?? String(e)])\n }\n\n sqliteVec.load(db)\n\n this.#_cache = { db, drivers: { Database, sqliteVec } }\n }\n\n async close(): Promise<void> {\n if (this.#_cache?.db) {\n this.#_cache.db.close()\n this.#_cache = null\n }\n }\n\n /** The underlying SQLite database handle; throws if the store is not connected. */\n get db(): any {\n if (!this.#_cache?.db) {\n throw new Error('Not connected')\n }\n return this.#_cache.db\n }\n\n async createCollection(spec: CollectionSpec, ifNotExists: boolean): Promise<void> {\n await this.connect()\n const { collection, vector } = spec\n const dims = vector.dimensions\n const tbl = ident(collection)\n const metaTbl = ident(collection + '__meta')\n\n const { db } = this\n\n const exists = await this.hasCollection(collection)\n if (!ifNotExists && exists) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['create', 'collection exists'])\n }\n\n try {\n db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${tbl} USING vec0(embedding float[${dims}])`)\n db.exec(\n `CREATE TABLE IF NOT EXISTS ${metaTbl} (rowid INTEGER PRIMARY KEY, id TEXT UNIQUE, document TEXT, metadata TEXT)`\n )\n this.#_dims.set(collection, dims)\n } catch (e: any) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['create', e?.message ?? String(e)])\n }\n }\n\n async dropCollection(collection: string, ifExists: boolean): Promise<void> {\n await this.connect()\n const tbl = ident(collection)\n const metaTbl = ident(collection + '__meta')\n\n const has = await this.hasCollection(collection)\n if (!has) {\n if (!ifExists) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['drop', 'collection does not exist'])\n }\n return\n }\n\n const { db } = this\n try {\n db.exec(`DROP TABLE IF EXISTS ${tbl}`)\n db.exec(`DROP TABLE IF EXISTS ${metaTbl}`)\n this.#_dims.delete(collection)\n } catch (e: any) {\n throw new E_VECTOR_STORE_COLLECTION_FAILED(['drop', e?.message ?? String(e)])\n }\n }\n\n async hasCollection(collection: string): Promise<boolean> {\n await this.connect()\n const { db } = this\n try {\n const res: any = db\n .prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`)\n .get(collection)\n return !!res?.name\n } catch {\n return false\n }\n }\n\n async renameCollection(_from: string, _to: string): Promise<void> {\n // With no `xRename` hook in sqlite-vec 0.1.9, `ALTER TABLE … RENAME TO` on the vec0 table would\n // succeed but leave its shadow tables behind under the old name, and the core shadow tables\n // (`_chunks`/`_info`/`_rowids`) reject a direct rename outright (`table <name>_chunks may not be\n // altered`). There is no way to finish the job, so there is no supported rename.\n throw new E_VECTOR_STORE_UNSUPPORTED_OPERATION(['renameCollection', 'sqlite_vec'])\n }\n\n async executeUpsert(plan: UpsertPlan): Promise<void> {\n await this.connect()\n validateRecords(plan.records)\n\n const collection = plan.collection\n const dims = this.#_dims.get(collection)\n const { db } = this\n\n const resolvedRows: {\n id: string\n vector: number[]\n document?: string\n metadata?: Record<string, unknown>\n }[] = []\n\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\n if (vector && dims !== undefined && vector.length !== dims) {\n throw new E_VECTOR_STORE_DIMENSION_MISMATCH([dims, vector.length])\n }\n\n resolvedRows.push({\n id: r.id,\n vector: vector ?? [],\n document: r.document,\n metadata: r.metadata as Record<string, unknown> | undefined,\n })\n }\n\n const metaTbl = ident(collection + '__meta')\n const tbl = ident(collection)\n\n const stmtMetaInsert = db.prepare(\n `INSERT INTO ${metaTbl} (id, document, metadata) VALUES (?, ?, ?)`\n )\n const stmtMetaUpdate = db.prepare(\n `UPDATE ${metaTbl} SET document = ?, metadata = ? WHERE id = ?`\n )\n const stmtRowid = db.prepare(`SELECT rowid FROM ${metaTbl} WHERE id = ?`)\n const stmtVecDelete = db.prepare(`DELETE FROM ${tbl} WHERE rowid = ?`)\n const stmtVecInsert = db.prepare(`INSERT INTO ${tbl} (rowid, embedding) VALUES (?, ?)`)\n\n const txn = db.transaction(() => {\n for (const r of resolvedRows) {\n const buf = new Float32Array(r.vector)\n let rowid: bigint | undefined\n\n const rowidRes: any = stmtRowid.get(r.id)\n if (rowidRes?.rowid) {\n rowid = BigInt(rowidRes.rowid)\n stmtMetaUpdate.run(r.document ?? null, JSON.stringify(r.metadata ?? {}), r.id)\n stmtVecDelete.run(rowid)\n stmtVecInsert.run(rowid, buf)\n } else {\n const insertMeta = stmtMetaInsert.run(\n r.id,\n r.document ?? null,\n JSON.stringify(r.metadata ?? {})\n )\n rowid = BigInt(insertMeta.lastInsertRowid)\n stmtVecInsert.run(rowid, buf)\n }\n }\n })\n\n try {\n txn()\n } catch (e: any) {\n throw new E_VECTOR_STORE_UPSERT_FAILED([e?.message ?? String(e)])\n }\n }\n\n async executeSearch(plan: SearchPlan): Promise<VectorMatch[]> {\n await this.connect()\n const { db } = this\n const collection = plan.collection\n const tbl = ident(collection)\n const metaTbl = ident(collection + '__meta')\n\n const near = plan.near\n const limit = (plan.offset ?? 0) + plan.topK\n\n try {\n if (near) {\n let qvec: number[] | undefined\n\n if ('vector' in near) {\n qvec = near.vector\n } else if ('serverText' in near) {\n const [v] = await this.encode([near.serverText], 'query')\n qvec = v\n } else if ('id' in near) {\n const refRow: any = db.prepare(`SELECT rowid FROM ${metaTbl} WHERE id = ?`).get(near.id)\n if (refRow?.rowid) {\n const refVecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(BigInt(refRow.rowid))\n if (refVecRes?.embedding) {\n qvec = Array.from(new Float32Array(refVecRes.embedding.buffer || refVecRes.embedding))\n }\n }\n }\n\n if (!qvec) {\n throw new E_VECTOR_STORE_SEARCH_FAILED(['no query vector provided'])\n }\n\n const matchClause = `embedding MATCH ? ORDER BY distance LIMIT ${limit}`\n const matchBuf = new Float32Array(qvec)\n\n const matches: VecRow[] = []\n const stmtMatch = db.prepare(`SELECT rowid, distance FROM ${tbl} WHERE ${matchClause}`)\n for (const row of stmtMatch.iterate(matchBuf)) {\n matches.push({ rowid: BigInt(row.rowid), distance: row.distance })\n }\n\n let results: VectorMatch[] = []\n for (const m of matches) {\n const meta: any = db\n .prepare(`SELECT rowid, id, document, metadata FROM ${metaTbl} WHERE rowid = ?`)\n .get(m.rowid)\n if (!meta) {\n continue\n }\n\n const parsedMeta =\n typeof meta.metadata === 'string' ? JSON.parse(meta.metadata) : meta.metadata\n\n if (plan.filter && !evaluateFilter(plan.filter, parsedMeta as any)) {\n continue\n }\n\n let score = normalizeScore(\n Number(m.distance),\n this.options.metric ?? 'euclidean',\n 'distance'\n )\n\n const proj: VectorMatch = {}\n if (plan.projection.id) proj.id = meta.id\n if (plan.projection.vector) {\n const vecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(m.rowid)\n if (vecRes?.embedding) {\n proj.vector = Array.from(\n new Float32Array(vecRes.embedding.buffer || vecRes.embedding)\n )\n }\n }\n if (plan.projection.document && meta.document !== undefined) proj.document = meta.document\n if (plan.projection.metadata && parsedMeta !== undefined)\n proj.metadata = parsedMeta as any\n if (score !== undefined) proj.score = score\n results.push(proj)\n }\n\n const offset = plan.offset ?? 0\n return results.slice(offset, offset + plan.topK)\n } else {\n const rows: any[] = db.prepare(`SELECT rowid, id, document, metadata FROM ${metaTbl}`).all()\n let scored: { row: any; score?: number }[] = []\n\n for (const row of rows) {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n\n if (plan.filter && !evaluateFilter(plan.filter, parsedMeta as any)) {\n continue\n }\n\n scored.push({ row, score: undefined })\n }\n\n const offset = plan.offset ?? 0\n const limited = scored.slice(offset, offset + plan.topK)\n\n return limited.map(({ row }) => {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n const out: VectorMatch = {}\n\n if (plan.projection.id) out.id = row.id\n\n if (plan.projection.vector) {\n const vecRes: any = db\n .prepare(`SELECT embedding FROM ${tbl} WHERE rowid = ?`)\n .get(BigInt(row.rowid))\n if (vecRes?.embedding) {\n out.vector = Array.from(new Float32Array(vecRes.embedding.buffer || vecRes.embedding))\n }\n }\n\n if (plan.projection.document && row.document !== undefined) out.document = row.document\n if (plan.projection.metadata && parsedMeta !== undefined) out.metadata = parsedMeta as any\n\n return out\n })\n }\n } catch (e: any) {\n throw new E_VECTOR_STORE_SEARCH_FAILED([e?.message ?? String(e)])\n }\n }\n\n async executeDelete(plan: DeletePlan): Promise<void> {\n await this.connect()\n const collection = plan.collection\n const metaTbl = ident(collection + '__meta')\n const tbl = ident(collection)\n\n const { db } = this\n\n try {\n if (plan.ids && plan.ids.length > 0) {\n const stmtIds = db.prepare(\n `SELECT rowid, metadata FROM ${metaTbl} WHERE id IN (${plan.ids.map(() => '?').join(', ')})`\n )\n const rowids: bigint[] = stmtIds.all(...plan.ids).map((r: any) => BigInt(r.rowid))\n if (rowids.length > 0) {\n const rowidPlaceholders = rowids.map(() => '?').join(', ')\n db.prepare(`DELETE FROM ${metaTbl} WHERE rowid IN (${rowidPlaceholders})`).run(...rowids)\n db.prepare(`DELETE FROM ${tbl} WHERE rowid IN (${rowidPlaceholders})`).run(...rowids)\n }\n } else if (plan.filter) {\n const rows: any[] = db.prepare(`SELECT rowid, metadata FROM ${metaTbl}`).all()\n const toDeleteRowids: bigint[] = []\n\n for (const row of rows) {\n const parsedMeta =\n typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata\n if (evaluateFilter(plan.filter, parsedMeta as any)) {\n toDeleteRowids.push(BigInt(row.rowid))\n }\n }\n\n if (toDeleteRowids.length > 0) {\n const rowidPlaceholders = toDeleteRowids.map(() => '?').join(', ')\n db.prepare(`DELETE FROM ${metaTbl} WHERE rowid IN (${rowidPlaceholders})`).run(\n ...toDeleteRowids\n )\n db.prepare(`DELETE FROM ${tbl} WHERE rowid IN (${rowidPlaceholders})`).run(\n ...toDeleteRowids\n )\n }\n } else {\n db.exec(`DELETE FROM ${metaTbl}`)\n db.exec(`DELETE FROM ${tbl}`)\n }\n } catch (e: any) {\n throw new E_VECTOR_STORE_DELETE_FAILED([e?.message ?? String(e)])\n }\n }\n\n async transaction(fn: (tx: CallableVectorStore) => Promise<void>): Promise<void> {\n await this.connect()\n const { db } = this\n\n db.exec('BEGIN')\n try {\n await fn(this.asCallable())\n db.exec('COMMIT')\n } catch (e) {\n db.exec('ROLLBACK')\n throw e\n }\n }\n}\n"],"mappings":";;;;;;;;;AAsBA,IAAM,SAAS,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAI,EAAE;AAoBrE,IAAa,uBAAb,cAA0C,gBAAgB;CACxD,eAAiD;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CAAC;EAClE;CACF;CAEA,MAAM,YAAY,IAA+D;EAC/E,MAAM,KAAK,QAAQ;EACnB,MAAM,EAAE,OAAO;EAEf,GAAG,KAAK,OAAO;EACf,IAAI;GACF,MAAM,GAAG,KAAK,WAAW,CAAC;GAC1B,GAAG,KAAK,QAAQ;EAClB,SAAS,GAAG;GACV,GAAG,KAAK,UAAU;GAClB,MAAM;EACR;CACF;AACF"}
|
package/batteries.cjs
CHANGED
|
@@ -3,10 +3,10 @@ require("./chunk-Cek0wNdY.cjs");
|
|
|
3
3
|
const require_batteries_context_exceptions = require("./batteries/context/exceptions.cjs");
|
|
4
4
|
const require_batteries_llm_openai_chat_completions_exceptions = require("./batteries/llm/openai_chat_completions/exceptions.cjs");
|
|
5
5
|
const require_batteries_llm_openai_chat_completions_validation = require("./batteries/llm/openai_chat_completions/validation.cjs");
|
|
6
|
-
const require_helpers = require("./helpers-
|
|
6
|
+
const require_helpers = require("./helpers-DPlh_7Bn.cjs");
|
|
7
7
|
const require_batteries_llm_openai_chat_completions_helpers = require("./batteries/llm/openai_chat_completions/helpers.cjs");
|
|
8
8
|
const require_batteries_llm_openai_chat_completions_adapter = require("./batteries/llm/openai_chat_completions/adapter.cjs");
|
|
9
|
-
const require_chat_common = require("./chat_common-
|
|
9
|
+
const require_chat_common = require("./chat_common-CNayzS1V.cjs");
|
|
10
10
|
const require_batteries_llm_webllm_chat_completions_exceptions = require("./batteries/llm/webllm_chat_completions/exceptions.cjs");
|
|
11
11
|
const require_batteries_llm_webllm_chat_completions_validation = require("./batteries/llm/webllm_chat_completions/validation.cjs");
|
|
12
12
|
const require_batteries_llm_webllm_chat_completions_adapter = require("./batteries/llm/webllm_chat_completions/adapter.cjs");
|
|
@@ -41,8 +41,8 @@ const require_batteries_tools_math = require("./batteries/tools/math.cjs");
|
|
|
41
41
|
const require_batteries_tools_memory = require("./batteries/tools/memory.cjs");
|
|
42
42
|
const require_batteries_tools_parsing = require("./batteries/tools/parsing.cjs");
|
|
43
43
|
const require_batteries_tools_retrievables = require("./batteries/tools/retrievables.cjs");
|
|
44
|
-
const require_scrapper = require("./scrapper-
|
|
45
|
-
const require_searxng = require("./searxng-
|
|
44
|
+
const require_scrapper = require("./scrapper-B8xG9lTD.cjs");
|
|
45
|
+
const require_searxng = require("./searxng-EJhWRnIE.cjs");
|
|
46
46
|
const require_batteries_tools_standing_instructions = require("./batteries/tools/standing_instructions.cjs");
|
|
47
47
|
const require_batteries_tools_statistics = require("./batteries/tools/statistics.cjs");
|
|
48
48
|
const require_batteries_tools_string_processing = require("./batteries/tools/string_processing.cjs");
|
package/batteries.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { E_CONTEXT_RESOLVER_MISSING } from "./batteries/context/exceptions.mjs";
|
|
2
2
|
import { E_INVALID_OPENAI_CHAT_COMPLETIONS_OPTIONS, E_OPENAI_CHAT_COMPLETIONS_CONTEXT_OVERFLOW, E_OPENAI_CHAT_COMPLETIONS_HTTP_ERROR, E_OPENAI_CHAT_COMPLETIONS_INVALID_TOOL_CALL_ARGS, E_OPENAI_CHAT_COMPLETIONS_REQUEST_TIMEOUT, E_OPENAI_CHAT_COMPLETIONS_STREAM_ERROR, E_OPENAI_CHAT_COMPLETIONS_STREAM_STALLED } from "./batteries/llm/openai_chat_completions/exceptions.mjs";
|
|
3
3
|
import { openAIChatCompletionsOptionsSchema, validateOptions as validateOptions$9 } from "./batteries/llm/openai_chat_completions/validation.mjs";
|
|
4
|
-
import { A as renderMemories, F as renderThirdPartyPrivateRetrievables, G as toolsToChatCompletionsTools, H as sanitizeFilenameForDescription, I as renderThirdPartyPublicRetrievables, L as renderThought, M as renderRetrievableSafetyDirective, N as renderRetrievables, O as renderChatCompletionsSystemPrompt, P as renderStandingInstructions, R as renderTrustedContent, S as floorTrustTier, T as neutraliseDeveloperRulesTag, U as sanitizeMimeType, W as stripEnvelopeSpecialTokens, _ as defaultRenderUntrustedContent, c as defaultRenderMemories, d as defaultRenderRetrievables, f as defaultRenderStandingInstructions, g as defaultRenderTrustedContent, h as defaultRenderThought, i as defaultFilterThoughts, k as renderFirstPartyRetrievables, m as defaultRenderThirdPartyPublicRetrievables, o as defaultRenderChatCompletionsSystemPrompt, p as defaultRenderThirdPartyPrivateRetrievables, r as defaultDescriptionToChatCompletionsJsonSchema, s as defaultRenderFirstPartyRetrievables, u as defaultRenderRetrievableSafetyDirective, v as defaultToolsToChatCompletionsTools, x as filterThoughts, y as descriptionToChatCompletionsJsonSchema, z as renderUntrustedContent } from "./helpers-
|
|
4
|
+
import { A as renderMemories, F as renderThirdPartyPrivateRetrievables, G as toolsToChatCompletionsTools, H as sanitizeFilenameForDescription, I as renderThirdPartyPublicRetrievables, L as renderThought, M as renderRetrievableSafetyDirective, N as renderRetrievables, O as renderChatCompletionsSystemPrompt, P as renderStandingInstructions, R as renderTrustedContent, S as floorTrustTier, T as neutraliseDeveloperRulesTag, U as sanitizeMimeType, W as stripEnvelopeSpecialTokens, _ as defaultRenderUntrustedContent, c as defaultRenderMemories, d as defaultRenderRetrievables, f as defaultRenderStandingInstructions, g as defaultRenderTrustedContent, h as defaultRenderThought, i as defaultFilterThoughts, k as renderFirstPartyRetrievables, m as defaultRenderThirdPartyPublicRetrievables, o as defaultRenderChatCompletionsSystemPrompt, p as defaultRenderThirdPartyPrivateRetrievables, r as defaultDescriptionToChatCompletionsJsonSchema, s as defaultRenderFirstPartyRetrievables, u as defaultRenderRetrievableSafetyDirective, v as defaultToolsToChatCompletionsTools, x as filterThoughts, y as descriptionToChatCompletionsJsonSchema, z as renderUntrustedContent } from "./helpers-mbn_EsDV.mjs";
|
|
5
5
|
import { buildChatCompletionsHistory, createChatCompletionsToolCallDeltaAccumulator, defaultBuildChatCompletionsHistory, defaultCreateChatCompletionsToolCallDeltaAccumulator, defaultRenderChatCompletionsToolCallResult, defaultRenderTimelineMessage, extractReasoningFields, renderChatCompletionsToolCallResult, renderTimelineMessage } from "./batteries/llm/openai_chat_completions/helpers.mjs";
|
|
6
6
|
import { OpenAIChatCompletionsAdapter } from "./batteries/llm/openai_chat_completions/adapter.mjs";
|
|
7
|
-
import { t as deCollideToolCallIds } from "./chat_common-
|
|
7
|
+
import { t as deCollideToolCallIds } from "./chat_common-DKw8FDol.mjs";
|
|
8
8
|
import { E_INVALID_WEBLLM_CHAT_COMPLETIONS_OPTIONS, E_WEBLLM_CHAT_COMPLETIONS_CONTEXT_OVERFLOW, E_WEBLLM_CHAT_COMPLETIONS_INVALID_TOOL_CALL_ARGS, E_WEBLLM_CHAT_COMPLETIONS_STREAM_ERROR } from "./batteries/llm/webllm_chat_completions/exceptions.mjs";
|
|
9
9
|
import { validateOptions as validateOptions$17, webLLMChatCompletionsOptionsSchema } from "./batteries/llm/webllm_chat_completions/validation.mjs";
|
|
10
10
|
import { WebLLMChatCompletionsAdapter } from "./batteries/llm/webllm_chat_completions/adapter.mjs";
|
|
@@ -39,8 +39,8 @@ import { calculateTool, evaluateKatexTool } from "./batteries/tools/math.mjs";
|
|
|
39
39
|
import { deleteMemoryTool, listMemoriesTool, memoryTools, storeMemoryTool, updateMemoryTool } from "./batteries/tools/memory.mjs";
|
|
40
40
|
import { detectDelimiterTool, parseCsvTool, parseKvTool, parseYamlTool } from "./batteries/tools/parsing.mjs";
|
|
41
41
|
import { deleteRetrievableTool, listRetrievablesTool, retrievableTools, storeRetrievableTool, updateRetrievableTool } from "./batteries/tools/retrievables.mjs";
|
|
42
|
-
import { a as E_INVALID_SCRAPPER_CONFIG, i as createScrapperLinksToolSync, n as createScrapperArticleToolSync, r as createScrapperLinksTool, t as createScrapperArticleTool } from "./scrapper-
|
|
43
|
-
import { n as createSearxngSearchToolSync, r as E_INVALID_SEARXNG_CONFIG, t as createSearxngSearchTool } from "./searxng-
|
|
42
|
+
import { a as E_INVALID_SCRAPPER_CONFIG, i as createScrapperLinksToolSync, n as createScrapperArticleToolSync, r as createScrapperLinksTool, t as createScrapperArticleTool } from "./scrapper-DiQ5FfDL.mjs";
|
|
43
|
+
import { n as createSearxngSearchToolSync, r as E_INVALID_SEARXNG_CONFIG, t as createSearxngSearchTool } from "./searxng-BFTJ6rTE.mjs";
|
|
44
44
|
import { addStandingInstructionTool, listStandingInstructionsTool, removeStandingInstructionTool, standingInstructionTools } from "./batteries/tools/standing_instructions.mjs";
|
|
45
45
|
import { statsCorrelateTool, statsDescribeTool, statsHistogramTool, statsTransformTool } from "./batteries/tools/statistics.mjs";
|
|
46
46
|
import { stringExtractTool, stringTransformTool } from "./batteries/tools/string_processing.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
require("./tool_parsers-8_qO0a_F.cjs");
|
|
2
|
-
require("./helpers-
|
|
2
|
+
require("./helpers-DPlh_7Bn.cjs");
|
|
3
3
|
require("./gpu_budget-BBIUyLoj.cjs");
|
|
4
4
|
require("./lifecycle-vYQJ2rmf.cjs");
|
|
5
5
|
require("./batteries/llm/chat_common/exceptions.cjs");
|
|
@@ -42,4 +42,4 @@ Object.defineProperty(exports, "deCollideToolCallIds", {
|
|
|
42
42
|
}
|
|
43
43
|
});
|
|
44
44
|
|
|
45
|
-
//# sourceMappingURL=chat_common-
|
|
45
|
+
//# sourceMappingURL=chat_common-CNayzS1V.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_common-B7fvGTKv.cjs","names":[],"sources":["../src/batteries/llm/chat_common/types.ts"],"sourcesContent":["/**\n * Wire-shape-agnostic TypeScript types shared across the Chat-family LLM batteries.\n *\n * @remarks\n * This module is INTERNAL to the bundled LLM batteries and is intentionally **not** tagged with\n * an `@module` JSDoc directive — `bin/utils/index.ts` `getEntries` only mints a public package\n * subpath for files that carry such a tag, so a tagless file stays private and is inlined into\n * each consumer by the bundler (the same way `src/lib/utils/retry.ts` is shared, minus the public\n * subpath). It holds the type aliases that the OpenAI Chat Completions battery and the native\n * Ollama battery both need: the validator-description envelope, the JSON Schema subset, the\n * trust-/memory-/retrievable-/thought-attribute envelopes, the system-prompt bucket ordering, the\n * function-tool wire shape, the unsupported-media policy, the retry config, and the\n * {@link ChatHelpersCommon} contract for the wire-shape-agnostic translation helpers.\n *\n * Battery-specific wire shapes (OpenAI Chat Completions message/chunk/response objects, the Ollama\n * native message/chunk objects) live in each battery's own `types.ts`, not here.\n */\n\nimport { v6 as uuidv6 } from 'uuid'\nimport type { ParsedToolCall } from './tool_parsers'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type {\n Tokenizable,\n Memory,\n Thought,\n Retrievable,\n Tool,\n ArtifactTool,\n MediaKind,\n} from '@nhtio/adk/common'\n\n// ─── DescriptionLike (validator description envelope) ─────────────────────────\n\n/**\n * Structural shape of a validator/Joi `describe()` output, as consumed by the JSON-Schema\n * renderer. A loose superset — only the fields the renderer reads are typed; the index signature\n * carries everything else through untouched.\n */\nexport interface DescriptionLike {\n /** Validator type name (e.g. `'string'`, `'object'`, `'array'`). */\n type?: string\n /** Human-readable description of the field. */\n description?: string\n /** Presence flag (`'optional'`, `'required'`, or `'forbidden'`) at the top level. */\n presence?: string\n /** Default value supplied when the field is absent. */\n default?: unknown\n /** Permitted values declared via an enum/valid set. */\n enum?: unknown[]\n /** Permitted values declared via the validator's `valid()` rule. */\n valids?: unknown[]\n /** Example values for the field. */\n examples?: unknown[]\n /** Nested property descriptions, keyed by property name (for object types). */\n properties?: Record<string, DescriptionLike>\n /** Element description(s) for array types. */\n items?: DescriptionLike | DescriptionLike[]\n /** Names of required properties (for object types). */\n required?: string[]\n /** Validator flags bag carrying presence, description, and default. */\n flags?: { presence?: string; description?: string; default?: unknown }\n /** Pass-through for any other validator metadata the renderer does not read. */\n [key: string]: unknown\n}\n\n// ─── JSON Schema (Chat-Completions-compatible subset) ─────────────────────────\n\n/**\n * The subset of JSON Schema that Chat-family tool/function `parameters` accept, as emitted by\n * {@link ChatHelpersCommon.descriptionToChatCompletionsJsonSchema}. The index signature allows\n * extra keywords to pass through to the wire.\n */\nexport interface JsonSchema {\n /** JSON Schema primitive/compound type. */\n type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'\n /** Human-readable description of the schema node. */\n description?: string\n /** Permitted values for the node. */\n enum?: unknown[]\n /** Default value for the node. */\n default?: unknown\n /** Example values for the node. */\n examples?: unknown[]\n /** Property schemas keyed by property name (for `object` types). */\n properties?: Record<string, JsonSchema>\n /** Names of required properties (for `object` types). */\n required?: string[]\n /** Element schema(s) for `array` types. */\n items?: JsonSchema | JsonSchema[]\n /** Whether (or what schema) additional, undeclared properties are permitted. */\n additionalProperties?: boolean | JsonSchema\n /** Pass-through for any other JSON Schema keyword. */\n [key: string]: unknown\n}\n\n// ─── Helper-attribute envelopes ───────────────────────────────────────────────\n\n/**\n * Attribute bag rendered onto the trust envelope that wraps untrusted (third-party) content.\n */\nexport interface UntrustedContentAttrs {\n /**\n * Nonce binding the envelope's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the fence cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Content classifier rendered on the envelope. */\n kind: string\n /** Name of the tool that produced the content, when applicable. */\n tool?: string\n /**\n * When wrapping a {@link @nhtio/adk!Media}-derived text marker, the modality hazard axis derived from\n * `media.modalityHazard`: `'inert'`, `'extractable'` (from `'extractable-instructions'`), or\n * `'opaque'` (from `'opaque-perceptual'`). Omitted for non-media envelopes.\n */\n modality?: 'inert' | 'extractable' | 'opaque'\n}\n\n/**\n * Attribute bag rendered onto the trust envelope that wraps trusted (first-party) content.\n */\nexport interface TrustedContentAttrs {\n /**\n * Nonce binding the envelope's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the fence cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Content classifier rendered on the envelope. */\n kind: string\n /** Name of the tool that produced the content, when applicable. */\n tool?: string\n /**\n * Same semantics as {@link UntrustedContentAttrs.modality}.\n */\n modality?: 'inert' | 'extractable' | 'opaque'\n}\n\n/**\n * Attribute bag rendered onto a standing-instruction block.\n */\nexport interface StandingInstructionAttrs {\n /** Optional version label for the standing instruction. */\n version?: string\n}\n\n/**\n * Attribute bag rendered onto a memory block.\n */\nexport interface MemoryAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Origin of the memory (e.g. the producing subsystem). */\n source?: string\n /** ISO-8601 creation timestamp of the memory. */\n createdAt?: string\n /** Memory classifier. */\n kind?: string\n /** Relevance/recall score, when the memory was retrieved by similarity. */\n score?: number\n}\n\n/**\n * Attribute bag rendered onto a retrievable block.\n */\nexport interface RetrievableAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Origin of the retrievable (e.g. the source document or system). */\n source?: string\n /** ISO-8601 creation timestamp of the retrievable. */\n createdAt?: string\n /** Retrievable classifier. */\n kind?: string\n /** Relevance score from the retrieval query. */\n score?: number\n}\n\n/**\n * Attribute bag rendered onto a thought block.\n */\nexport interface ThoughtAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Whether the thought is the model's own, a peer's, or opaque vendor reasoning. */\n kind: 'self-reasoning' | 'peer-reasoning' | 'opaque-reasoning'\n /** Identity of the agent the thought originated from. */\n from: string\n /** ISO-8601 creation timestamp of the thought. */\n createdAt?: string\n /** Replay-compatibility label gating whether the thought is surfaced on replay. */\n replayCompatibility?: string\n}\n\n// ─── Bucket order ─────────────────────────────────────────────────────────────\n\n/**\n * Name of a system-prompt content bucket whose render order is configurable.\n */\nexport type ChatCompletionsBucketLabel =\n | 'standingInstructions'\n | 'memories'\n | 'retrievables'\n | 'timeline'\n\n/**\n * Ordered list of {@link ChatCompletionsBucketLabel}s controlling the sequence in which content\n * buckets are assembled into the prompt.\n */\nexport type ChatCompletionsBucketOrder = ReadonlyArray<ChatCompletionsBucketLabel>\n\n// ─── Function-tool wire shape (identical for OpenAI Chat Completions and Ollama) ──\n\n/**\n * Wire shape of a single function tool advertised to the model — identical for OpenAI Chat\n * Completions and Ollama.\n */\nexport interface ChatCompletionsTool {\n /** Tool kind; always `'function'` for the bundled batteries. */\n type: 'function'\n /** The function declaration: its name, description, and JSON-Schema parameters. */\n function: {\n name: string\n description?: string\n parameters?: JsonSchema\n }\n}\n\n// ─── Unsupported-media policy ─────────────────────────────────────────────────\n\n/**\n * Policy for how a Chat-family battery handles a {@link @nhtio/adk!Media} instance whose modality the\n * wire protocol cannot natively represent.\n *\n * @remarks\n * The option SHAPE is shared; each battery decides which modalities count as \"unsupported\"\n * (OpenAI Chat Completions: video; Ollama native `/api/chat`: everything except image). Three\n * modes:\n *\n * - `'throw'` — raise the battery's unsupported-media exception and fail the dispatch. Loud\n * failure; the default, so a misconfigured pipeline surfaces immediately.\n * - `'fallback-stash'` — look for a model-readable text entry in `media.stash`. If present, render\n * that text inside the appropriate trust envelope in lieu of a media block. If no entry is found,\n * fall through to `'synthetic-description'` behaviour. The shorthand string form uses the\n * battery's default key list (`['text:transcript', 'text:caption', 'text:description']`, walked\n * in order). The object form `{ mode: 'fallback-stash'; stashKeys }` overrides the key list.\n * - `'synthetic-description'` — always render a synthetic text description constructed from\n * `filename`, `byteLength`, and `mimeType` regardless of `stash` presence.\n */\nexport type UnsupportedMediaPolicy =\n | 'throw'\n | 'fallback-stash'\n | 'synthetic-description'\n | { mode: 'fallback-stash'; stashKeys: ReadonlyArray<string> }\n\n// ─── Media OUTPUT (generated media surfaced as assistant attachments) ─────────\n\n/**\n * One piece of media a model GENERATED as turn output — the descriptor a\n * {@link MediaOutputExtractorFn} returns for the adapter to persist + attach to the assistant\n * {@link @nhtio/adk!Message}.\n *\n * @remarks\n * The LLM batteries are multimodal-IN, text-OUT by default: the tested open-weight chat checkpoints\n * emit only text, so no media output is produced unless a consumer wraps a media-emitting model AND\n * supplies an extractor. The framework contract already supports the output direction —\n * `Message.attachments` is symmetric across roles and `ctx.storeMediaBytes` persists generated bytes —\n * so this descriptor is all the adapter needs: it calls `storeMediaBytes` with `bytes`, builds a\n * `Media.toolGenerated({ kind, mimeType, filename, reader })` from the returned reader, and attaches it.\n */\nexport interface GeneratedMediaOutput {\n /** Media modality (`'image'`/`'audio'`/`'video'`/`'document'`). */\n kind: MediaKind\n /** Concrete MIME type of the generated bytes (e.g. `'audio/wav'`, `'image/png'`). */\n mimeType: string\n /** The generated media bytes. */\n bytes: Uint8Array\n /** Optional filename for the attachment; the adapter supplies a default when omitted. */\n filename?: string\n}\n\n/**\n * Extracts generated media from a battery's raw generation result so the adapter can surface it as\n * assistant `Message.attachments`. Injectable + defaulted to absent (no media output) on every LLM\n * battery, mirroring the `toolCallParser` / `reasoningParser` / `decodeMedia` injection seams.\n *\n * @remarks\n * `result` is the battery-native generation object (transformers.js `model.generate` / pipeline output;\n * the LiteRT-LM final `Message` + raw content items) — deliberately typed `unknown` because its shape is\n * battery-specific and the extractor is supplied by whoever wraps a media-emitting model. Returning an\n * empty array (or not supplying the hook) yields today's text-only behavior, byte-for-byte unchanged.\n */\nexport type MediaOutputExtractorFn = (\n result: unknown\n) => GeneratedMediaOutput[] | Promise<GeneratedMediaOutput[]>\n\n// ─── Raw generation observability (the model's text BEFORE parsing) ───────────\n\n/**\n * One observation of a battery's raw model output for a single completed generation, fired the instant\n * the full text is in hand — AFTER envelope-token stripping + reasoning/tool-call parsing, but BEFORE\n * the parsed result is persisted. The whole point is to expose the gap between what the model literally\n * emitted (`rawText`) and what the battery managed to extract (`cleanedText` / `toolCalls` /\n * `reasoning`): when a small on-device model emits a tool call in a shape no parser matches, the call\n * silently leaks into `cleanedText` as prose, and this is the ONLY seam where that is visible.\n *\n * @remarks\n * This is a pure observability tap — it returns `void`, never mutates the result, and never throws into\n * the generation path (the adapter swallows callback errors). It fires once per terminal generation\n * (one per non-streamed turn; one per stream at stream end), for BOTH the transformers.js and LiteRT-LM\n * on-device batteries, at the identical point in each. Use it for parser bring-up against a new model,\n * live debugging (\"why did the agent abstain?\"), or capturing ground-truth fixtures — exactly the job\n * that previously required patching a temporary hook into the adapter.\n */\nexport interface RawGenerationObservation {\n /**\n * The model's complete decoded output for this generation, with non-semantic envelope/turn-boundary\n * special tokens already stripped (the same text handed to the parsers) — i.e. what the parsers\n * actually saw. This is the field to inspect when a tool call did not parse.\n */\n rawText: string\n /**\n * The residual prose after reasoning + tool-call extraction — what becomes the assistant message\n * `content`. If a tool call failed to parse, its source text is still here (the leak).\n */\n cleanedText: string\n /** The reasoning/thinking traces the reasoning parser extracted (empty when none / not applicable). */\n reasoning: ReadonlyArray<string>\n /** The tool calls the tool-call parser extracted (empty when the model emitted none, or none parsed). */\n toolCalls: ReadonlyArray<ParsedToolCall>\n /** Whether this generation streamed its prose to the consumer (vs. a single batch decode). */\n streamed: boolean\n /** The adapter's stream/message id for this generation, for correlating with other telemetry. */\n streamId: string\n}\n\n/**\n * Observe a battery's raw model output for one completed generation. Injectable + defaulted to absent\n * on the on-device LLM batteries (transformers.js, LiteRT-LM), mirroring the `toolCallParser` /\n * `reasoningParser` / `extractMediaOutputs` injection seams. Fired once per terminal generation, after\n * parsing and before persistence; purely observational (return value ignored, errors swallowed).\n */\nexport type RawGenerationObserverFn = (observation: RawGenerationObservation) => void\n\n// ─── Prompt observability (the exact request BEFORE it is dispatched) ──────────\n\n/**\n * One observation of the fully-assembled request a battery is about to send TO the model, fired the\n * instant assembly completes and BEFORE the engine/HTTP dispatch. It is the mirror of\n * {@link RawGenerationObservation}: that seam exposes the raw text coming back FROM the model; this one\n * exposes the raw request going TO it. Together they let you read ground truth at both ends of the wire —\n * e.g. to settle whether a \"smart quote\" in a rendered answer came from the model itself or from a\n * downstream markdown renderer, you inspect the bytes here, not the DOM.\n *\n * @remarks\n * This is a pure observability tap — it returns `void`, never mutates the request, and never throws into\n * the generation path (the adapter swallows callback errors). It fires once per terminal generation\n * (one per non-streamed turn; one per stream, at dispatch), across ALL five LLM batteries.\n *\n * **Handed back AS-IS — no redaction.** The observation carries the request exactly as assembled. The ADK\n * does not scrub credentials, headers, or any other field for you: what you put on the request is what you\n * see here, and if you route this to a persistent sink (a log, `localStorage`, a file) you may persist\n * secrets that rode the request (an `apiKey`, `Authorization` header, etc.). That is your responsibility to\n * handle, not the battery's — the ADK surfaces the truth and lets you decide what to do with it. (In\n * practice the API batteries strip ADK-control keys like `apiKey` out of the wire body before this fires,\n * but that is incidental to how the body is built, not a guarantee.)\n */\nexport interface PromptAssembledObservation {\n /** Which battery assembled this request (e.g. `'litert_lm'`, `'openai_chat_completions'`). */\n battery: string\n /**\n * The shape of the assembled request. `'rendered-prompt'` for the on-device batteries (transformers.js,\n * LiteRT-LM), which render a preface string + a messages array for the engine; `'request-body'` for the\n * API batteries (OpenAI-compatible, Ollama, WebLLM), which POST a JSON body.\n */\n kind: 'rendered-prompt' | 'request-body'\n /**\n * On-device leading/system content rendered ahead of the timeline (e.g. the LiteRT `preface` object,\n * which carries the assembled system message text and — for native tool delivery — the tool list), when\n * applicable. Its concrete shape is battery-specific; captured verbatim. Absent for the API batteries.\n */\n preface?: unknown\n /**\n * The per-turn messages exactly as handed to the engine (on-device) or placed on the wire (API): the\n * engine's message array, or the request body's `messages`.\n */\n messages: unknown\n /**\n * The tool declarations exactly as dispatched: the rendered `<tool_definitions>` prompt text (on-device\n * prompt-delivery) or the wire `tools` array (API / native tool delivery). Absent when no tools are sent.\n */\n tools?: unknown\n /**\n * API batteries only: the complete assembled request body, exactly as it will be sent (see the AS-IS /\n * no-redaction note above). Absent for the on-device batteries.\n */\n requestBody?: unknown\n /** Whether this generation streams its response (vs. a single batch call). */\n streamed: boolean\n /** The adapter's stream/message id for this generation, for correlating with other telemetry. */\n streamId: string\n}\n\n/**\n * Observe the fully-assembled request a battery is about to dispatch. Injectable + defaulted to absent on\n * every LLM battery, mirroring {@link RawGenerationObserverFn}. Fired once per terminal generation, after\n * assembly and before dispatch; purely observational (return value ignored, errors swallowed). The request\n * is handed back AS-IS — see {@link PromptAssembledObservation} for the no-redaction contract.\n */\nexport type PromptAssembledObserverFn = (observation: PromptAssembledObservation) => void\n\n// ─── Tool-call id ingress ─────────────────────────────────────────────────────\n\n/**\n * Shapes a provider-supplied tool-call id at adapter ingress, before the call is stored or used for\n * spool/result correlation. This hook exists to prevent the concrete failure seen with grok-4.3 on\n * Bedrock Mantle, which repeats `call_0` across tool-calling turns. Default absent = identity, so\n * adapters retain today's behaviour unless a consumer opts in.\n *\n * @remarks\n * `#doStoreToolCall` adds to `turnToolCalls` synchronously before its await, and adoption is a\n * sequential loop, so each call sees every prior call — including same-response siblings. A correctly\n * numbered parallel batch (`call_0`..`call_3`) is therefore safe because those ids are already\n * DISTINCT, not because the siblings are unstored. A genuine same-response duplicate IS de-collided,\n * which is intentional.\n */\nexport type ToolCallIdFilterFn = (id: string, ctx: DispatchContext) => string\n\n/**\n * De-collides a provider-supplied tool-call id against calls already adopted in this dispatch. It\n * prevents the concrete `call_0`-repeated-across-turns failure seen with grok-4.3 on Bedrock Mantle.\n * Default absent = identity; this implementation returns the original id when no collision exists.\n *\n * @remarks\n * `#doStoreToolCall` adds to `turnToolCalls` synchronously before its await, and adoption is a\n * sequential loop, so each call sees every prior call — including same-response siblings. A correctly\n * numbered parallel batch (`call_0`..`call_3`) passes through because those ids are already DISTINCT,\n * not because the siblings are unstored. A genuine same-response duplicate is de-collided, as intended.\n */\nexport const deCollideToolCallIds: ToolCallIdFilterFn = (id, ctx) =>\n [...ctx.turnToolCalls].some((tc) => tc.id === id) ? uuidv6() : id\n\n// ─── Retry config ─────────────────────────────────────────────────────────────\n\n/**\n * Retry/backoff configuration for a Chat-family battery's HTTP requests.\n */\nexport interface ChatCompletionsRetryConfig {\n /** Maximum number of attempts (including the first) before giving up. */\n maxAttempts?: number\n /** Base delay in milliseconds for the first retry; doubles each attempt. */\n baseDelayMs?: number\n /** Upper bound in milliseconds on any single backoff delay. */\n maxDelayMs?: number\n /** HTTP status codes that trigger a retry. */\n retriableStatuses?: number[]\n /** Whether to honour a server `Retry-After` header in place of computed backoff. */\n honorRetryAfter?: boolean\n}\n\n// ─── Shared helper contract (wire-shape-agnostic members) ─────────────────────\n\n/**\n * The wire-shape-agnostic subset of a Chat-family battery's translation helpers — every helper\n * that produces a plain `string` (or JSON Schema / tool-definition wire, which is identical across\n * the family) rather than a battery-specific message object.\n *\n * @remarks\n * Both `ChatCompletionsHelpers` (OpenAI battery) and `OllamaHelpers` (Ollama battery) extend this\n * contract and add their own wire-specific members (timeline-message rendering, tool-call-result\n * rendering, history assembly, and — for OpenAI — streaming tool-call delta accumulation). Helpers\n * that compose other helpers receive their dependents via explicit `deps` arguments typed against\n * THIS contract (never against a battery-specific bag), so the shared implementations carry no\n * import edge back to any individual battery.\n */\nexport interface ChatHelpersCommon {\n /** Converts a validator `describe()` envelope into the Chat-Completions JSON-Schema subset. */\n descriptionToChatCompletionsJsonSchema: (d: DescriptionLike) => JsonSchema\n /** Wraps untrusted (third-party) text in the untrusted-content trust envelope. */\n renderUntrustedContent: (content: string, attrs: UntrustedContentAttrs) => string\n /** Wraps trusted (first-party) text in the trusted-content trust envelope. */\n renderTrustedContent: (content: string, attrs: TrustedContentAttrs) => string\n /** Renders standing instructions into a single prompt block. */\n renderStandingInstructions: (\n items: Iterable<Tokenizable>,\n attrs?: StandingInstructionAttrs\n ) => string\n /** Renders memories (each with its attribute bag) into a single prompt block. */\n renderMemories: (items: Iterable<{ memory: Memory; attrs: MemoryAttrs }>) => string\n /** Renders the safety directive that precedes any retrievable content. */\n renderRetrievableSafetyDirective: () => string\n /** Renders first-party (trusted) retrievables into a single prompt block. */\n renderFirstPartyRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n ) => Promise<string>\n /** Renders third-party public retrievables, wrapping each in the untrusted-content envelope. */\n renderThirdPartyPublicRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /** Renders third-party private retrievables, wrapping each in the untrusted-content envelope. */\n renderThirdPartyPrivateRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /** Assembles the full retrievables block: safety directive plus the trust-tiered sub-renderers. */\n renderRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /**\n * Renders the directions-bearing \"handle\" body for a non-inlined {@link @nhtio/adk!SpooledArtifact}\n * tool result: metadata (callId/kind/byteLength/lineCount) plus the forged `artifact_*` tools the\n * model should call to read it incrementally.\n *\n * @remarks\n * Optional override seam. When omitted the battery uses the shared\n * {@link defaultRenderArtifactHandleBody}. A consumer overrides it to change WHICH reader the model\n * is steered toward first — e.g. promoting the JSON content-readers (`artifact_json_get` /\n * `artifact_json_keys`) ahead of the metadata-only `artifact_json_type` for a small model that grabs\n * the first listed tool. The tool list itself comes from the artifact's `constructor.toolMethods`;\n * an override typically reorders or re-annotates that list before delegating to the default renderer.\n */\n renderArtifactHandleBody?: (input: {\n callId: string\n artifact: unknown\n byteLength: number\n lineCount: number\n estimatedTokens?: number\n encoding?: string\n }) => string\n /**\n * Renders the directions-bearing \"handle\" body for a non-inlined {@link @nhtio/adk!Retrievable}\n * whose content is a {@link @nhtio/adk!SpooledArtifact}: metadata (callId/kind/byteLength/lineCount)\n * plus the forged `artifact_*` tools the model should call to read it incrementally.\n *\n * @remarks\n * Optional override seam, the retrievable-side counterpart to {@link renderArtifactHandleBody}.\n * When omitted the battery uses the shared {@link defaultRenderRetrievableHandleBody}.\n */\n renderRetrievableHandleBody?: (input: {\n callId: string\n artifact: unknown\n byteLength: number\n lineCount: number\n estimatedTokens?: number\n encoding?: string\n }) => string\n /** Renders a single thought into its prompt block, optionally carrying an opaque replay payload. */\n renderThought: (content: string, attrs: ThoughtAttrs, payload?: unknown) => string\n /** Selects which thoughts to surface, by surfacing mode, self identity, and replay compatibility. */\n filterThoughts: (\n thoughts: Iterable<Thought>,\n mode: 'all-self' | 'latest-self' | 'all',\n selfIdentity: string,\n replayCompatibility: ReadonlyArray<string>\n ) => Thought[]\n /** Translates the tool registry into the function-tool wire array advertised to the model. */\n toolsToChatCompletionsTools: (\n tools: ReadonlyArray<Tool | ArtifactTool>,\n deps: { descriptionToChatCompletionsJsonSchema: (d: DescriptionLike) => JsonSchema }\n ) => ChatCompletionsTool[]\n /** Assembles the system-prompt message from its constituent buckets in {@link ChatCompletionsBucketOrder}. */\n renderChatCompletionsSystemPrompt: (input: {\n systemPrompt: Tokenizable\n /**\n * Live dispatch context for resolving a DYNAMIC {@link Tokenizable} `systemPrompt` via\n * `.render(ctx)`. Optional; a static `systemPrompt` ignores it. The real implementation\n * (`chat_common/helpers.ts`) already accepts and forwards this — declared here so the type\n * matches what the function actually does.\n */\n renderCtx?: unknown\n standingInstructions: Iterable<Tokenizable>\n memories: Iterable<Memory>\n retrievables: Iterable<Retrievable>\n bucketOrder: ChatCompletionsBucketOrder\n renderStandingInstructions: ChatHelpersCommon['renderStandingInstructions']\n renderMemories: ChatHelpersCommon['renderMemories']\n renderRetrievables: ChatHelpersCommon['renderRetrievables']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n }) => Promise<string>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwdA,IAAa,wBAA4C,IAAI,QAC3D,CAAC,GAAG,IAAI,aAAa,EAAE,MAAM,OAAO,GAAG,OAAO,EAAE,KAAA,GAAA,KAAA,IAAW,IAAI"}
|
|
1
|
+
{"version":3,"file":"chat_common-CNayzS1V.cjs","names":[],"sources":["../src/batteries/llm/chat_common/types.ts"],"sourcesContent":["/**\n * Wire-shape-agnostic TypeScript types shared across the Chat-family LLM batteries.\n *\n * @remarks\n * This module is INTERNAL to the bundled LLM batteries and is intentionally **not** tagged with\n * an `@module` JSDoc directive — `bin/utils/index.ts` `getEntries` only mints a public package\n * subpath for files that carry such a tag, so a tagless file stays private and is inlined into\n * each consumer by the bundler (the same way `src/lib/utils/retry.ts` is shared, minus the public\n * subpath). It holds the type aliases that the OpenAI Chat Completions battery and the native\n * Ollama battery both need: the validator-description envelope, the JSON Schema subset, the\n * trust-/memory-/retrievable-/thought-attribute envelopes, the system-prompt bucket ordering, the\n * function-tool wire shape, the unsupported-media policy, the retry config, and the\n * {@link ChatHelpersCommon} contract for the wire-shape-agnostic translation helpers.\n *\n * Battery-specific wire shapes (OpenAI Chat Completions message/chunk/response objects, the Ollama\n * native message/chunk objects) live in each battery's own `types.ts`, not here.\n */\n\nimport { v6 as uuidv6 } from 'uuid'\nimport type { ParsedToolCall } from './tool_parsers'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type {\n Tokenizable,\n Memory,\n Thought,\n Retrievable,\n Tool,\n ArtifactTool,\n MediaKind,\n} from '@nhtio/adk/common'\n\n// ─── DescriptionLike (validator description envelope) ─────────────────────────\n\n/**\n * Structural shape of a validator/Joi `describe()` output, as consumed by the JSON-Schema\n * renderer. A loose superset — only the fields the renderer reads are typed; the index signature\n * carries everything else through untouched.\n */\nexport interface DescriptionLike {\n /** Validator type name (e.g. `'string'`, `'object'`, `'array'`). */\n type?: string\n /** Human-readable description of the field. */\n description?: string\n /** Presence flag (`'optional'`, `'required'`, or `'forbidden'`) at the top level. */\n presence?: string\n /** Default value supplied when the field is absent. */\n default?: unknown\n /** Permitted values declared via an enum/valid set. */\n enum?: unknown[]\n /** Permitted values declared via the validator's `valid()` rule. */\n valids?: unknown[]\n /** Example values for the field. */\n examples?: unknown[]\n /** Nested property descriptions, keyed by property name (for object types). */\n properties?: Record<string, DescriptionLike>\n /** Element description(s) for array types. */\n items?: DescriptionLike | DescriptionLike[]\n /** Names of required properties (for object types). */\n required?: string[]\n /** Validator flags bag carrying presence, description, and default. */\n flags?: { presence?: string; description?: string; default?: unknown }\n /** Pass-through for any other validator metadata the renderer does not read. */\n [key: string]: unknown\n}\n\n// ─── JSON Schema (Chat-Completions-compatible subset) ─────────────────────────\n\n/**\n * The subset of JSON Schema that Chat-family tool/function `parameters` accept, as emitted by\n * {@link ChatHelpersCommon.descriptionToChatCompletionsJsonSchema}. The index signature allows\n * extra keywords to pass through to the wire.\n */\nexport interface JsonSchema {\n /** JSON Schema primitive/compound type. */\n type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'\n /** Human-readable description of the schema node. */\n description?: string\n /** Permitted values for the node. */\n enum?: unknown[]\n /** Default value for the node. */\n default?: unknown\n /** Example values for the node. */\n examples?: unknown[]\n /** Property schemas keyed by property name (for `object` types). */\n properties?: Record<string, JsonSchema>\n /** Names of required properties (for `object` types). */\n required?: string[]\n /** Element schema(s) for `array` types. */\n items?: JsonSchema | JsonSchema[]\n /** Whether (or what schema) additional, undeclared properties are permitted. */\n additionalProperties?: boolean | JsonSchema\n /** Pass-through for any other JSON Schema keyword. */\n [key: string]: unknown\n}\n\n// ─── Helper-attribute envelopes ───────────────────────────────────────────────\n\n/**\n * Attribute bag rendered onto the trust envelope that wraps untrusted (third-party) content.\n */\nexport interface UntrustedContentAttrs {\n /**\n * Nonce binding the envelope's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the fence cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Content classifier rendered on the envelope. */\n kind: string\n /** Name of the tool that produced the content, when applicable. */\n tool?: string\n /**\n * When wrapping a {@link @nhtio/adk!Media}-derived text marker, the modality hazard axis derived from\n * `media.modalityHazard`: `'inert'`, `'extractable'` (from `'extractable-instructions'`), or\n * `'opaque'` (from `'opaque-perceptual'`). Omitted for non-media envelopes.\n */\n modality?: 'inert' | 'extractable' | 'opaque'\n}\n\n/**\n * Attribute bag rendered onto the trust envelope that wraps trusted (first-party) content.\n */\nexport interface TrustedContentAttrs {\n /**\n * Nonce binding the envelope's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the fence cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Content classifier rendered on the envelope. */\n kind: string\n /** Name of the tool that produced the content, when applicable. */\n tool?: string\n /**\n * Same semantics as {@link UntrustedContentAttrs.modality}.\n */\n modality?: 'inert' | 'extractable' | 'opaque'\n}\n\n/**\n * Attribute bag rendered onto a standing-instruction block.\n */\nexport interface StandingInstructionAttrs {\n /** Optional version label for the standing instruction. */\n version?: string\n}\n\n/**\n * Attribute bag rendered onto a memory block.\n */\nexport interface MemoryAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Origin of the memory (e.g. the producing subsystem). */\n source?: string\n /** ISO-8601 creation timestamp of the memory. */\n createdAt?: string\n /** Memory classifier. */\n kind?: string\n /** Relevance/recall score, when the memory was retrieved by similarity. */\n score?: number\n}\n\n/**\n * Attribute bag rendered onto a retrievable block.\n */\nexport interface RetrievableAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Origin of the retrievable (e.g. the source document or system). */\n source?: string\n /** ISO-8601 creation timestamp of the retrievable. */\n createdAt?: string\n /** Retrievable classifier. */\n kind?: string\n /** Relevance score from the retrieval query. */\n score?: number\n}\n\n/**\n * Attribute bag rendered onto a thought block.\n */\nexport interface ThoughtAttrs {\n /**\n * Nonce binding the block's open and close markers together — it becomes part of the tag NAME\n * (`<..._<nonce>>`) so a model mirroring the block cannot forge a sibling's closer.\n *\n * FOOTGUN: this nonce MUST be unguessable AND non-path-shaped. It is typically the source record's id; a\n * path-shaped id (e.g. `chunk-assembly-events-9`) is copied by small models as a CITATION\n * (`/assembly/events-9`), which a doc-path validator then rejects → re-cite loop. Mint record ids with\n * `crypto.randomUUID()`; carry page/human provenance in `source=` (rendered before `nonce=`), never in the id.\n */\n nonce: string\n /** Whether the thought is the model's own, a peer's, or opaque vendor reasoning. */\n kind: 'self-reasoning' | 'peer-reasoning' | 'opaque-reasoning'\n /** Identity of the agent the thought originated from. */\n from: string\n /** ISO-8601 creation timestamp of the thought. */\n createdAt?: string\n /** Replay-compatibility label gating whether the thought is surfaced on replay. */\n replayCompatibility?: string\n}\n\n// ─── Bucket order ─────────────────────────────────────────────────────────────\n\n/**\n * Name of a system-prompt content bucket whose render order is configurable.\n */\nexport type ChatCompletionsBucketLabel =\n | 'standingInstructions'\n | 'memories'\n | 'retrievables'\n | 'timeline'\n\n/**\n * Ordered list of {@link ChatCompletionsBucketLabel}s controlling the sequence in which content\n * buckets are assembled into the prompt.\n */\nexport type ChatCompletionsBucketOrder = ReadonlyArray<ChatCompletionsBucketLabel>\n\n// ─── Function-tool wire shape (identical for OpenAI Chat Completions and Ollama) ──\n\n/**\n * Wire shape of a single function tool advertised to the model — identical for OpenAI Chat\n * Completions and Ollama.\n */\nexport interface ChatCompletionsTool {\n /** Tool kind; always `'function'` for the bundled batteries. */\n type: 'function'\n /** The function declaration: its name, description, and JSON-Schema parameters. */\n function: {\n name: string\n description?: string\n parameters?: JsonSchema\n }\n}\n\n// ─── Unsupported-media policy ─────────────────────────────────────────────────\n\n/**\n * Policy for how a Chat-family battery handles a {@link @nhtio/adk!Media} instance whose modality the\n * wire protocol cannot natively represent.\n *\n * @remarks\n * The option SHAPE is shared; each battery decides which modalities count as \"unsupported\"\n * (OpenAI Chat Completions: video; Ollama native `/api/chat`: everything except image). Three\n * modes:\n *\n * - `'throw'` — raise the battery's unsupported-media exception and fail the dispatch. Loud\n * failure; the default, so a misconfigured pipeline surfaces immediately.\n * - `'fallback-stash'` — look for a model-readable text entry in `media.stash`. If present, render\n * that text inside the appropriate trust envelope in lieu of a media block. If no entry is found,\n * fall through to `'synthetic-description'` behaviour. The shorthand string form uses the\n * battery's default key list (`['text:transcript', 'text:caption', 'text:description']`, walked\n * in order). The object form `{ mode: 'fallback-stash'; stashKeys }` overrides the key list.\n * - `'synthetic-description'` — always render a synthetic text description constructed from\n * `filename`, `byteLength`, and `mimeType` regardless of `stash` presence.\n */\nexport type UnsupportedMediaPolicy =\n | 'throw'\n | 'fallback-stash'\n | 'synthetic-description'\n | { mode: 'fallback-stash'; stashKeys: ReadonlyArray<string> }\n\n// ─── Media OUTPUT (generated media surfaced as assistant attachments) ─────────\n\n/**\n * One piece of media a model GENERATED as turn output — the descriptor a\n * {@link MediaOutputExtractorFn} returns for the adapter to persist + attach to the assistant\n * {@link @nhtio/adk!Message}.\n *\n * @remarks\n * The LLM batteries are multimodal-IN, text-OUT by default: the tested open-weight chat checkpoints\n * emit only text, so no media output is produced unless a consumer wraps a media-emitting model AND\n * supplies an extractor. The framework contract already supports the output direction —\n * `Message.attachments` is symmetric across roles and `ctx.storeMediaBytes` persists generated bytes —\n * so this descriptor is all the adapter needs: it calls `storeMediaBytes` with `bytes`, builds a\n * `Media.toolGenerated({ kind, mimeType, filename, reader })` from the returned reader, and attaches it.\n */\nexport interface GeneratedMediaOutput {\n /** Media modality (`'image'`/`'audio'`/`'video'`/`'document'`). */\n kind: MediaKind\n /** Concrete MIME type of the generated bytes (e.g. `'audio/wav'`, `'image/png'`). */\n mimeType: string\n /** The generated media bytes. */\n bytes: Uint8Array\n /** Optional filename for the attachment; the adapter supplies a default when omitted. */\n filename?: string\n}\n\n/**\n * Extracts generated media from a battery's raw generation result so the adapter can surface it as\n * assistant `Message.attachments`. Injectable + defaulted to absent (no media output) on every LLM\n * battery, mirroring the `toolCallParser` / `reasoningParser` / `decodeMedia` injection seams.\n *\n * @remarks\n * `result` is the battery-native generation object (transformers.js `model.generate` / pipeline output;\n * the LiteRT-LM final `Message` + raw content items) — deliberately typed `unknown` because its shape is\n * battery-specific and the extractor is supplied by whoever wraps a media-emitting model. Returning an\n * empty array (or not supplying the hook) yields today's text-only behavior, byte-for-byte unchanged.\n */\nexport type MediaOutputExtractorFn = (\n result: unknown\n) => GeneratedMediaOutput[] | Promise<GeneratedMediaOutput[]>\n\n// ─── Raw generation observability (the model's text BEFORE parsing) ───────────\n\n/**\n * One observation of a battery's raw model output for a single completed generation, fired the instant\n * the full text is in hand — AFTER envelope-token stripping + reasoning/tool-call parsing, but BEFORE\n * the parsed result is persisted. The whole point is to expose the gap between what the model literally\n * emitted (`rawText`) and what the battery managed to extract (`cleanedText` / `toolCalls` /\n * `reasoning`): when a small on-device model emits a tool call in a shape no parser matches, the call\n * silently leaks into `cleanedText` as prose, and this is the ONLY seam where that is visible.\n *\n * @remarks\n * This is a pure observability tap — it returns `void`, never mutates the result, and never throws into\n * the generation path (the adapter swallows callback errors). It fires once per terminal generation\n * (one per non-streamed turn; one per stream at stream end), for BOTH the transformers.js and LiteRT-LM\n * on-device batteries, at the identical point in each. Use it for parser bring-up against a new model,\n * live debugging (\"why did the agent abstain?\"), or capturing ground-truth fixtures — exactly the job\n * that previously required patching a temporary hook into the adapter.\n */\nexport interface RawGenerationObservation {\n /**\n * The model's complete decoded output for this generation, with non-semantic envelope/turn-boundary\n * special tokens already stripped (the same text handed to the parsers) — i.e. what the parsers\n * actually saw. This is the field to inspect when a tool call did not parse.\n */\n rawText: string\n /**\n * The residual prose after reasoning + tool-call extraction — what becomes the assistant message\n * `content`. If a tool call failed to parse, its source text is still here (the leak).\n */\n cleanedText: string\n /** The reasoning/thinking traces the reasoning parser extracted (empty when none / not applicable). */\n reasoning: ReadonlyArray<string>\n /** The tool calls the tool-call parser extracted (empty when the model emitted none, or none parsed). */\n toolCalls: ReadonlyArray<ParsedToolCall>\n /** Whether this generation streamed its prose to the consumer (vs. a single batch decode). */\n streamed: boolean\n /** The adapter's stream/message id for this generation, for correlating with other telemetry. */\n streamId: string\n}\n\n/**\n * Observe a battery's raw model output for one completed generation. Injectable + defaulted to absent\n * on the on-device LLM batteries (transformers.js, LiteRT-LM), mirroring the `toolCallParser` /\n * `reasoningParser` / `extractMediaOutputs` injection seams. Fired once per terminal generation, after\n * parsing and before persistence; purely observational (return value ignored, errors swallowed).\n */\nexport type RawGenerationObserverFn = (observation: RawGenerationObservation) => void\n\n// ─── Prompt observability (the exact request BEFORE it is dispatched) ──────────\n\n/**\n * One observation of the fully-assembled request a battery is about to send TO the model, fired the\n * instant assembly completes and BEFORE the engine/HTTP dispatch. It is the mirror of\n * {@link RawGenerationObservation}: that seam exposes the raw text coming back FROM the model; this one\n * exposes the raw request going TO it. Together they let you read ground truth at both ends of the wire —\n * e.g. to settle whether a \"smart quote\" in a rendered answer came from the model itself or from a\n * downstream markdown renderer, you inspect the bytes here, not the DOM.\n *\n * @remarks\n * This is a pure observability tap — it returns `void`, never mutates the request, and never throws into\n * the generation path (the adapter swallows callback errors). It fires once per terminal generation\n * (one per non-streamed turn; one per stream, at dispatch), across ALL five LLM batteries.\n *\n * **Handed back AS-IS — no redaction.** The observation carries the request exactly as assembled. The ADK\n * does not scrub credentials, headers, or any other field for you: what you put on the request is what you\n * see here, and if you route this to a persistent sink (a log, `localStorage`, a file) you may persist\n * secrets that rode the request (an `apiKey`, `Authorization` header, etc.). That is your responsibility to\n * handle, not the battery's — the ADK surfaces the truth and lets you decide what to do with it. (In\n * practice the API batteries strip ADK-control keys like `apiKey` out of the wire body before this fires,\n * but that is incidental to how the body is built, not a guarantee.)\n */\nexport interface PromptAssembledObservation {\n /** Which battery assembled this request (e.g. `'litert_lm'`, `'openai_chat_completions'`). */\n battery: string\n /**\n * The shape of the assembled request. `'rendered-prompt'` for the on-device batteries (transformers.js,\n * LiteRT-LM), which render a preface string + a messages array for the engine; `'request-body'` for the\n * API batteries (OpenAI-compatible, Ollama, WebLLM), which POST a JSON body.\n */\n kind: 'rendered-prompt' | 'request-body'\n /**\n * On-device leading/system content rendered ahead of the timeline (e.g. the LiteRT `preface` object,\n * which carries the assembled system message text and — for native tool delivery — the tool list), when\n * applicable. Its concrete shape is battery-specific; captured verbatim. Absent for the API batteries.\n */\n preface?: unknown\n /**\n * The per-turn messages exactly as handed to the engine (on-device) or placed on the wire (API): the\n * engine's message array, or the request body's `messages`.\n */\n messages: unknown\n /**\n * The tool declarations exactly as dispatched: the rendered `<tool_definitions>` prompt text (on-device\n * prompt-delivery) or the wire `tools` array (API / native tool delivery). Absent when no tools are sent.\n */\n tools?: unknown\n /**\n * API batteries only: the complete assembled request body, exactly as it will be sent (see the AS-IS /\n * no-redaction note above). Absent for the on-device batteries.\n */\n requestBody?: unknown\n /** Whether this generation streams its response (vs. a single batch call). */\n streamed: boolean\n /** The adapter's stream/message id for this generation, for correlating with other telemetry. */\n streamId: string\n}\n\n/**\n * Observe the fully-assembled request a battery is about to dispatch. Injectable + defaulted to absent on\n * every LLM battery, mirroring {@link RawGenerationObserverFn}. Fired once per terminal generation, after\n * assembly and before dispatch; purely observational (return value ignored, errors swallowed). The request\n * is handed back AS-IS — see {@link PromptAssembledObservation} for the no-redaction contract.\n */\nexport type PromptAssembledObserverFn = (observation: PromptAssembledObservation) => void\n\n// ─── Tool-call id ingress ─────────────────────────────────────────────────────\n\n/**\n * Shapes a provider-supplied tool-call id at adapter ingress, before the call is stored or used for\n * spool/result correlation. This hook exists to prevent the concrete failure seen with grok-4.3 on\n * Bedrock Mantle, which repeats `call_0` across tool-calling turns. Default absent = identity, so\n * adapters retain today's behaviour unless a consumer opts in.\n *\n * @remarks\n * `#doStoreToolCall` adds to `turnToolCalls` synchronously before its await, and adoption is a\n * sequential loop, so each call sees every prior call — including same-response siblings. A correctly\n * numbered parallel batch (`call_0`..`call_3`) is therefore safe because those ids are already\n * DISTINCT, not because the siblings are unstored. A genuine same-response duplicate IS de-collided,\n * which is intentional.\n */\nexport type ToolCallIdFilterFn = (id: string, ctx: DispatchContext) => string\n\n/**\n * De-collides a provider-supplied tool-call id against calls already adopted in this dispatch. It\n * prevents the concrete `call_0`-repeated-across-turns failure seen with grok-4.3 on Bedrock Mantle.\n * Default absent = identity; this implementation returns the original id when no collision exists.\n *\n * @remarks\n * `#doStoreToolCall` adds to `turnToolCalls` synchronously before its await, and adoption is a\n * sequential loop, so each call sees every prior call — including same-response siblings. A correctly\n * numbered parallel batch (`call_0`..`call_3`) passes through because those ids are already DISTINCT,\n * not because the siblings are unstored. A genuine same-response duplicate is de-collided, as intended.\n */\nexport const deCollideToolCallIds: ToolCallIdFilterFn = (id, ctx) =>\n [...ctx.turnToolCalls].some((tc) => tc.id === id) ? uuidv6() : id\n\n// ─── Retry config ─────────────────────────────────────────────────────────────\n\n/**\n * Retry/backoff configuration for a Chat-family battery's HTTP requests.\n */\nexport interface ChatCompletionsRetryConfig {\n /** Maximum number of attempts (including the first) before giving up. */\n maxAttempts?: number\n /** Base delay in milliseconds for the first retry; doubles each attempt. */\n baseDelayMs?: number\n /** Upper bound in milliseconds on any single backoff delay. */\n maxDelayMs?: number\n /** HTTP status codes that trigger a retry. */\n retriableStatuses?: number[]\n /** Whether to honour a server `Retry-After` header in place of computed backoff. */\n honorRetryAfter?: boolean\n}\n\n// ─── Shared helper contract (wire-shape-agnostic members) ─────────────────────\n\n/**\n * The wire-shape-agnostic subset of a Chat-family battery's translation helpers — every helper\n * that produces a plain `string` (or JSON Schema / tool-definition wire, which is identical across\n * the family) rather than a battery-specific message object.\n *\n * @remarks\n * Both `ChatCompletionsHelpers` (OpenAI battery) and `OllamaHelpers` (Ollama battery) extend this\n * contract and add their own wire-specific members (timeline-message rendering, tool-call-result\n * rendering, history assembly, and — for OpenAI — streaming tool-call delta accumulation). Helpers\n * that compose other helpers receive their dependents via explicit `deps` arguments typed against\n * THIS contract (never against a battery-specific bag), so the shared implementations carry no\n * import edge back to any individual battery.\n */\nexport interface ChatHelpersCommon {\n /** Converts a validator `describe()` envelope into the Chat-Completions JSON-Schema subset. */\n descriptionToChatCompletionsJsonSchema: (d: DescriptionLike) => JsonSchema\n /** Wraps untrusted (third-party) text in the untrusted-content trust envelope. */\n renderUntrustedContent: (content: string, attrs: UntrustedContentAttrs) => string\n /** Wraps trusted (first-party) text in the trusted-content trust envelope. */\n renderTrustedContent: (content: string, attrs: TrustedContentAttrs) => string\n /** Renders standing instructions into a single prompt block. */\n renderStandingInstructions: (\n items: Iterable<Tokenizable>,\n attrs?: StandingInstructionAttrs\n ) => string\n /** Renders memories (each with its attribute bag) into a single prompt block. */\n renderMemories: (items: Iterable<{ memory: Memory; attrs: MemoryAttrs }>) => string\n /** Renders the safety directive that precedes any retrievable content. */\n renderRetrievableSafetyDirective: () => string\n /** Renders first-party (trusted) retrievables into a single prompt block. */\n renderFirstPartyRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n ) => Promise<string>\n /** Renders third-party public retrievables, wrapping each in the untrusted-content envelope. */\n renderThirdPartyPublicRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /** Renders third-party private retrievables, wrapping each in the untrusted-content envelope. */\n renderThirdPartyPrivateRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /** Assembles the full retrievables block: safety directive plus the trust-tiered sub-renderers. */\n renderRetrievables: (\n items: Iterable<{ retrievable: Retrievable; attrs: RetrievableAttrs }>,\n deps: {\n renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n }\n ) => Promise<string>\n /**\n * Renders the directions-bearing \"handle\" body for a non-inlined {@link @nhtio/adk!SpooledArtifact}\n * tool result: metadata (callId/kind/byteLength/lineCount) plus the forged `artifact_*` tools the\n * model should call to read it incrementally.\n *\n * @remarks\n * Optional override seam. When omitted the battery uses the shared\n * {@link defaultRenderArtifactHandleBody}. A consumer overrides it to change WHICH reader the model\n * is steered toward first — e.g. promoting the JSON content-readers (`artifact_json_get` /\n * `artifact_json_keys`) ahead of the metadata-only `artifact_json_type` for a small model that grabs\n * the first listed tool. The tool list itself comes from the artifact's `constructor.toolMethods`;\n * an override typically reorders or re-annotates that list before delegating to the default renderer.\n */\n renderArtifactHandleBody?: (input: {\n callId: string\n artifact: unknown\n byteLength: number\n lineCount: number\n estimatedTokens?: number\n encoding?: string\n }) => string\n /**\n * Renders the directions-bearing \"handle\" body for a non-inlined {@link @nhtio/adk!Retrievable}\n * whose content is a {@link @nhtio/adk!SpooledArtifact}: metadata (callId/kind/byteLength/lineCount)\n * plus the forged `artifact_*` tools the model should call to read it incrementally.\n *\n * @remarks\n * Optional override seam, the retrievable-side counterpart to {@link renderArtifactHandleBody}.\n * When omitted the battery uses the shared {@link defaultRenderRetrievableHandleBody}.\n */\n renderRetrievableHandleBody?: (input: {\n callId: string\n artifact: unknown\n byteLength: number\n lineCount: number\n estimatedTokens?: number\n encoding?: string\n }) => string\n /** Renders a single thought into its prompt block, optionally carrying an opaque replay payload. */\n renderThought: (content: string, attrs: ThoughtAttrs, payload?: unknown) => string\n /** Selects which thoughts to surface, by surfacing mode, self identity, and replay compatibility. */\n filterThoughts: (\n thoughts: Iterable<Thought>,\n mode: 'all-self' | 'latest-self' | 'all',\n selfIdentity: string,\n replayCompatibility: ReadonlyArray<string>\n ) => Thought[]\n /** Translates the tool registry into the function-tool wire array advertised to the model. */\n toolsToChatCompletionsTools: (\n tools: ReadonlyArray<Tool | ArtifactTool>,\n deps: { descriptionToChatCompletionsJsonSchema: (d: DescriptionLike) => JsonSchema }\n ) => ChatCompletionsTool[]\n /** Assembles the system-prompt message from its constituent buckets in {@link ChatCompletionsBucketOrder}. */\n renderChatCompletionsSystemPrompt: (input: {\n systemPrompt: Tokenizable\n /**\n * Live dispatch context for resolving a DYNAMIC {@link Tokenizable} `systemPrompt` via\n * `.render(ctx)`. Optional; a static `systemPrompt` ignores it. The real implementation\n * (`chat_common/helpers.ts`) already accepts and forwards this — declared here so the type\n * matches what the function actually does.\n */\n renderCtx?: unknown\n standingInstructions: Iterable<Tokenizable>\n memories: Iterable<Memory>\n retrievables: Iterable<Retrievable>\n bucketOrder: ChatCompletionsBucketOrder\n renderStandingInstructions: ChatHelpersCommon['renderStandingInstructions']\n renderMemories: ChatHelpersCommon['renderMemories']\n renderRetrievables: ChatHelpersCommon['renderRetrievables']\n renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n }) => Promise<string>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwdA,IAAa,wBAA4C,IAAI,QAC3D,CAAC,GAAG,IAAI,aAAa,EAAE,MAAM,OAAO,GAAG,OAAO,EAAE,KAAA,GAAA,KAAA,IAAW,IAAI"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./tool_parsers-DgZhgxV8.mjs";
|
|
2
|
-
import "./helpers-
|
|
2
|
+
import "./helpers-mbn_EsDV.mjs";
|
|
3
3
|
import "./gpu_budget-Bi2nUUil.mjs";
|
|
4
4
|
import "./lifecycle-C4kwYJ-N.mjs";
|
|
5
5
|
import "./batteries/llm/chat_common/exceptions.mjs";
|
|
@@ -37,4 +37,4 @@ var deCollideToolCallIds = (id, ctx) => [...ctx.turnToolCalls].some((tc) => tc.i
|
|
|
37
37
|
//#endregion
|
|
38
38
|
export { deCollideToolCallIds as t };
|
|
39
39
|
|
|
40
|
-
//# sourceMappingURL=chat_common-
|
|
40
|
+
//# sourceMappingURL=chat_common-DKw8FDol.mjs.map
|