@fgv/ts-extras 5.1.0-4 → 5.1.0-40
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/dist/index.browser.js +4 -2
- package/dist/index.browser.js.map +1 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/ai-assist/apiClient.js +886 -158
- package/dist/packlets/ai-assist/apiClient.js.map +1 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js +282 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/dist/packlets/ai-assist/converters.js +47 -3
- package/dist/packlets/ai-assist/converters.js.map +1 -0
- package/dist/packlets/ai-assist/embeddingClient.js +345 -0
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -0
- package/dist/packlets/ai-assist/endpoint.js +78 -0
- package/dist/packlets/ai-assist/endpoint.js.map +1 -0
- package/dist/packlets/ai-assist/http.js +75 -0
- package/dist/packlets/ai-assist/http.js.map +1 -0
- package/dist/packlets/ai-assist/imageOptionsResolver.js +193 -0
- package/dist/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +10 -4
- package/dist/packlets/ai-assist/index.js.map +1 -0
- package/dist/packlets/ai-assist/jsonCompletion.js +93 -0
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -0
- package/dist/packlets/ai-assist/jsonResponse.js +149 -0
- package/dist/packlets/ai-assist/jsonResponse.js.map +1 -0
- package/dist/packlets/ai-assist/model.js +193 -9
- package/dist/packlets/ai-assist/model.js.map +1 -0
- package/dist/packlets/ai-assist/registry.js +314 -12
- package/dist/packlets/ai-assist/registry.js.map +1 -0
- package/dist/packlets/ai-assist/sseParser.js +123 -0
- package/dist/packlets/ai-assist/sseParser.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +368 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +687 -0
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js +187 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +204 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +170 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +386 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +173 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/dist/packlets/ai-assist/streamingClient.js +140 -0
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js +288 -0
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
- package/dist/packlets/ai-assist/toolFormats.js +106 -10
- package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
- package/dist/packlets/conversion/converters.js +35 -1
- package/dist/packlets/conversion/converters.js.map +1 -0
- package/dist/packlets/conversion/index.js.map +1 -0
- package/dist/packlets/crypto-utils/constants.js.map +1 -0
- package/dist/packlets/crypto-utils/converters.js +42 -4
- package/dist/packlets/crypto-utils/converters.js.map +1 -0
- package/dist/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
- package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -0
- package/dist/packlets/crypto-utils/hpkeProvider.js +333 -0
- package/dist/packlets/crypto-utils/hpkeProvider.js.map +1 -0
- package/dist/packlets/crypto-utils/index.browser.js +10 -2
- package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
- package/dist/packlets/crypto-utils/index.js +6 -0
- package/dist/packlets/crypto-utils/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +71 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/converters.js +103 -11
- package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +287 -0
- package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/index.browser.js +36 -0
- package/dist/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/index.js +3 -0
- package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/keyStore.js +633 -118
- package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/model.js +22 -1
- package/dist/packlets/crypto-utils/keystore/model.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
- package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
- package/dist/packlets/crypto-utils/model.js +32 -0
- package/dist/packlets/crypto-utils/model.js.map +1 -0
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +270 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/dist/packlets/crypto-utils/spkiHelpers.js +209 -0
- package/dist/packlets/crypto-utils/spkiHelpers.js.map +1 -0
- package/dist/packlets/csv/csvFileHelpers.js +0 -14
- package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
- package/dist/packlets/csv/csvHelpers.js +14 -0
- package/dist/packlets/csv/csvHelpers.js.map +1 -0
- package/dist/packlets/csv/index.browser.js +1 -3
- package/dist/packlets/csv/index.browser.js.map +1 -0
- package/dist/packlets/csv/index.js.map +1 -0
- package/dist/packlets/experimental/extendedArray.js.map +1 -0
- package/dist/packlets/experimental/formatter.js.map +1 -0
- package/dist/packlets/experimental/index.js.map +1 -0
- package/dist/packlets/experimental/rangeOf.js.map +1 -0
- package/dist/packlets/hash/index.browser.js.map +1 -0
- package/dist/packlets/hash/index.js.map +1 -0
- package/dist/packlets/hash/index.node.js.map +1 -0
- package/dist/packlets/hash/md5Normalizer.browser.js.map +1 -0
- package/dist/packlets/hash/md5Normalizer.js.map +1 -0
- package/dist/packlets/mustache/index.js.map +1 -0
- package/dist/packlets/mustache/interfaces.js.map +1 -0
- package/dist/packlets/mustache/mustacheTemplate.js +42 -4
- package/dist/packlets/mustache/mustacheTemplate.js.map +1 -0
- package/dist/packlets/record-jar/index.browser.js +1 -3
- package/dist/packlets/record-jar/index.browser.js.map +1 -0
- package/dist/packlets/record-jar/index.js.map +1 -0
- package/dist/packlets/record-jar/recordJarFileHelpers.js +0 -18
- package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
- package/dist/packlets/record-jar/recordJarHelpers.js +18 -0
- package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -0
- package/dist/packlets/yaml/converters.js.map +1 -0
- package/dist/packlets/yaml/index.js +1 -0
- package/dist/packlets/yaml/index.js.map +1 -0
- package/dist/packlets/yaml/serializers.js +48 -0
- package/dist/packlets/yaml/serializers.js.map +1 -0
- package/dist/packlets/zip-file-tree/index.js.map +1 -0
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
- package/dist/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
- package/dist/ts-extras.d.ts +3880 -105
- package/dist/tsdoc-metadata.json +1 -1
- package/lib/index.browser.d.ts +4 -2
- package/lib/index.browser.d.ts.map +1 -0
- package/lib/index.browser.js +8 -3
- package/lib/index.browser.js.map +1 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/ai-assist/apiClient.d.ts +115 -32
- package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/apiClient.js +888 -156
- package/lib/packlets/ai-assist/apiClient.js.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +149 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js +293 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/lib/packlets/ai-assist/converters.d.ts +15 -1
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
- package/lib/packlets/ai-assist/converters.js +47 -3
- package/lib/packlets/ai-assist/converters.js.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.d.ts +69 -0
- package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.js +349 -0
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -0
- package/lib/packlets/ai-assist/endpoint.d.ts +28 -0
- package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -0
- package/lib/packlets/ai-assist/endpoint.js +82 -0
- package/lib/packlets/ai-assist/endpoint.js.map +1 -0
- package/lib/packlets/ai-assist/http.d.ts +24 -0
- package/lib/packlets/ai-assist/http.d.ts.map +1 -0
- package/lib/packlets/ai-assist/http.js +78 -0
- package/lib/packlets/ai-assist/http.js.map +1 -0
- package/lib/packlets/ai-assist/imageOptionsResolver.d.ts +66 -0
- package/lib/packlets/ai-assist/imageOptionsResolver.d.ts.map +1 -0
- package/lib/packlets/ai-assist/imageOptionsResolver.js +197 -0
- package/lib/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +10 -4
- package/lib/packlets/ai-assist/index.d.ts.map +1 -0
- package/lib/packlets/ai-assist/index.js +36 -1
- package/lib/packlets/ai-assist/index.js.map +1 -0
- package/lib/packlets/ai-assist/jsonCompletion.d.ts +93 -0
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -0
- package/lib/packlets/ai-assist/jsonCompletion.js +97 -0
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -0
- package/lib/packlets/ai-assist/jsonResponse.d.ts +91 -0
- package/lib/packlets/ai-assist/jsonResponse.d.ts.map +1 -0
- package/lib/packlets/ai-assist/jsonResponse.js +154 -0
- package/lib/packlets/ai-assist/jsonResponse.js.map +1 -0
- package/lib/packlets/ai-assist/model.d.ts +1202 -12
- package/lib/packlets/ai-assist/model.d.ts.map +1 -0
- package/lib/packlets/ai-assist/model.js +198 -10
- package/lib/packlets/ai-assist/model.js.map +1 -0
- package/lib/packlets/ai-assist/registry.d.ts +56 -1
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
- package/lib/packlets/ai-assist/registry.js +319 -13
- package/lib/packlets/ai-assist/registry.js.map +1 -0
- package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
- package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -0
- package/lib/packlets/ai-assist/sseParser.js +128 -0
- package/lib/packlets/ai-assist/sseParser.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +72 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +371 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +260 -0
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +694 -0
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +154 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js +193 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +43 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +207 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +19 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +173 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +33 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +389 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js +176 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts +50 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.js +146 -0
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +87 -0
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -0
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js +294 -0
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
- package/lib/packlets/ai-assist/toolFormats.d.ts +40 -9
- package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
- package/lib/packlets/ai-assist/toolFormats.js +107 -10
- package/lib/packlets/ai-assist/toolFormats.js.map +1 -0
- package/lib/packlets/conversion/converters.d.ts +8 -1
- package/lib/packlets/conversion/converters.d.ts.map +1 -0
- package/lib/packlets/conversion/converters.js +36 -2
- package/lib/packlets/conversion/converters.js.map +1 -0
- package/lib/packlets/conversion/index.d.ts.map +1 -0
- package/lib/packlets/conversion/index.js.map +1 -0
- package/lib/packlets/crypto-utils/constants.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/constants.js.map +1 -0
- package/lib/packlets/crypto-utils/converters.d.ts +20 -1
- package/lib/packlets/crypto-utils/converters.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/converters.js +43 -5
- package/lib/packlets/crypto-utils/converters.js.map +1 -0
- package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
- package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -0
- package/lib/packlets/crypto-utils/hpkeProvider.d.ts +142 -0
- package/lib/packlets/crypto-utils/hpkeProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/hpkeProvider.js +337 -0
- package/lib/packlets/crypto-utils/hpkeProvider.js.map +1 -0
- package/lib/packlets/crypto-utils/index.browser.d.ts +4 -1
- package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.browser.js +21 -3
- package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
- package/lib/packlets/crypto-utils/index.d.ts +3 -0
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.js +17 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +54 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +74 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
- package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/converters.js +101 -9
- package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts +148 -0
- package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +324 -0
- package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.browser.d.ts +10 -0
- package/lib/packlets/crypto-utils/keystore/index.browser.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.browser.js +76 -0
- package/lib/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts +2 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.js +5 -1
- package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +205 -13
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.js +639 -124
- package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/model.d.ts +275 -19
- package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/model.js +24 -2
- package/lib/packlets/crypto-utils/keystore/model.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +53 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
- package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
- package/lib/packlets/crypto-utils/model.d.ts +348 -10
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/model.js +33 -1
- package/lib/packlets/crypto-utils/model.js.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +110 -2
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js +269 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/lib/packlets/crypto-utils/spkiHelpers.d.ts +110 -0
- package/lib/packlets/crypto-utils/spkiHelpers.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/spkiHelpers.js +219 -0
- package/lib/packlets/crypto-utils/spkiHelpers.js.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.d.ts +0 -10
- package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.js +0 -15
- package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
- package/lib/packlets/csv/csvHelpers.d.ts +10 -0
- package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvHelpers.js +15 -0
- package/lib/packlets/csv/csvHelpers.js.map +1 -0
- package/lib/packlets/csv/index.browser.d.ts +0 -1
- package/lib/packlets/csv/index.browser.d.ts.map +1 -0
- package/lib/packlets/csv/index.browser.js +1 -5
- package/lib/packlets/csv/index.browser.js.map +1 -0
- package/lib/packlets/csv/index.d.ts.map +1 -0
- package/lib/packlets/csv/index.js.map +1 -0
- package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
- package/lib/packlets/experimental/extendedArray.js.map +1 -0
- package/lib/packlets/experimental/formatter.d.ts.map +1 -0
- package/lib/packlets/experimental/formatter.js.map +1 -0
- package/lib/packlets/experimental/index.d.ts.map +1 -0
- package/lib/packlets/experimental/index.js.map +1 -0
- package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
- package/lib/packlets/experimental/rangeOf.js.map +1 -0
- package/lib/packlets/hash/index.browser.d.ts.map +1 -0
- package/lib/packlets/hash/index.browser.js.map +1 -0
- package/lib/packlets/hash/index.d.ts.map +1 -0
- package/lib/packlets/hash/index.js.map +1 -0
- package/lib/packlets/hash/index.node.d.ts.map +1 -0
- package/lib/packlets/hash/index.node.js.map +1 -0
- package/lib/packlets/hash/md5Normalizer.browser.d.ts.map +1 -0
- package/lib/packlets/hash/md5Normalizer.browser.js.map +1 -0
- package/lib/packlets/hash/md5Normalizer.d.ts.map +1 -0
- package/lib/packlets/hash/md5Normalizer.js.map +1 -0
- package/lib/packlets/mustache/index.d.ts +1 -1
- package/lib/packlets/mustache/index.d.ts.map +1 -0
- package/lib/packlets/mustache/index.js.map +1 -0
- package/lib/packlets/mustache/interfaces.d.ts +34 -0
- package/lib/packlets/mustache/interfaces.d.ts.map +1 -0
- package/lib/packlets/mustache/interfaces.js.map +1 -0
- package/lib/packlets/mustache/mustacheTemplate.d.ts +2 -0
- package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -0
- package/lib/packlets/mustache/mustacheTemplate.js +42 -4
- package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
- package/lib/packlets/record-jar/index.browser.d.ts +0 -1
- package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
- package/lib/packlets/record-jar/index.browser.js +1 -5
- package/lib/packlets/record-jar/index.browser.js.map +1 -0
- package/lib/packlets/record-jar/index.d.ts.map +1 -0
- package/lib/packlets/record-jar/index.js.map +1 -0
- package/lib/packlets/record-jar/recordJarFileHelpers.d.ts +0 -11
- package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -0
- package/lib/packlets/record-jar/recordJarFileHelpers.js +0 -19
- package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
- package/lib/packlets/record-jar/recordJarHelpers.d.ts +11 -0
- package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
- package/lib/packlets/record-jar/recordJarHelpers.js +19 -0
- package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
- package/lib/packlets/yaml/converters.d.ts.map +1 -0
- package/lib/packlets/yaml/converters.js.map +1 -0
- package/lib/packlets/yaml/index.d.ts +1 -0
- package/lib/packlets/yaml/index.d.ts.map +1 -0
- package/lib/packlets/yaml/index.js +1 -0
- package/lib/packlets/yaml/index.js.map +1 -0
- package/lib/packlets/yaml/serializers.d.ts +45 -0
- package/lib/packlets/yaml/serializers.d.ts.map +1 -0
- package/lib/packlets/yaml/serializers.js +84 -0
- package/lib/packlets/yaml/serializers.js.map +1 -0
- package/lib/packlets/zip-file-tree/index.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/index.js.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts.map +1 -0
- package/lib/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
- package/package.json +20 -15
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sseParser.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/sseParser.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;;;;;;;;;;;;;AA+BZ,sCAgBC;AASD,sCAmCC;AASD,8CASC;AArFD;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,KAAa;IACzC,IAAI,KAAyB,CAAC;IAC9B,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,KAAK,M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C","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Server-Sent Events (SSE) parser primitives shared by the streaming format\n * adapters in `streamingClient.ts`. Implements the subset of the SSE wire\n * format that LLM providers actually emit: optional `event:` line, one or\n * more `data:` lines per message, messages separated by a blank line.\n *\n * @packageDocumentation\n */\n\n/**\n * One parsed SSE message (the SSE spec calls each blank-line-terminated\n * record an \"event\").\n *\n * @internal\n */\nexport interface ISseEvent {\n /** The `event:` field, if present (some providers omit it). */\n readonly event?: string;\n /** Concatenated contents of the message's `data:` lines. */\n readonly data: string;\n}\n\n/**\n * Parses a single SSE message (the text between blank-line separators) into\n * an {@link ISseEvent}. Returns undefined for messages with no `data:` lines\n * (comments, heartbeats).\n *\n * @internal\n */\nexport function parseSseEvent(chunk: string): ISseEvent | undefined {\n let event: string | undefined;\n const dataLines: string[] = [];\n for (const line of chunk.split('\\n')) {\n if (line.startsWith('event:')) {\n event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n // Per the SSE spec the value starts after the colon, with one optional leading space stripped.\n const value = line.slice(5);\n dataLines.push(value.startsWith(' ') ? value.slice(1) : value);\n }\n }\n if (dataLines.length === 0) {\n return undefined;\n }\n return event !== undefined ? { event, data: dataLines.join('\\n') } : { data: dataLines.join('\\n') };\n}\n\n/**\n * Reads an SSE response body and yields parsed events. Buffers across read()\n * boundaries so a message split mid-chunk still parses cleanly. Terminates\n * when the stream closes (normal EOF or aborted fetch).\n *\n * @internal\n */\nexport async function* readSseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<ISseEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n let streaming = true;\n while (streaming) {\n const { value, done } = await reader.read();\n if (done) {\n streaming = false;\n if (buffer.length > 0) {\n const tail = parseSseEvent(buffer.replace(/\\r\\n/g, '\\n'));\n if (tail) {\n yield tail;\n }\n }\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n // SSE messages are separated by a blank line; some servers use \\r\\n.\n const normalized = buffer.replace(/\\r\\n/g, '\\n');\n const parts = normalized.split('\\n\\n');\n // Last element is the partial chunk (no terminating blank line yet); buffer it.\n /* c8 ignore next 1 - defensive: parts.pop() returning undefined is unreachable after split */\n buffer = parts.pop() ?? '';\n for (const chunk of parts) {\n const event = parseSseEvent(chunk);\n if (event) {\n yield event;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Parses the `data` payload of an SSE event as JSON. Returns undefined for\n * the OpenAI `[DONE]` sentinel and for any payload that fails to parse —\n * adapters treat both as \"skip this event.\"\n *\n * @internal\n */\nexport function parseSseEventJson(data: string): unknown | undefined {\n if (data === '[DONE]') {\n return undefined;\n }\n try {\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming adapter for the Anthropic Messages API. Handles server tool
|
|
3
|
+
* use (e.g. `web_search`) as unified `tool-event` markers and client-defined
|
|
4
|
+
* tool calls (type `tool_use`) with B4 thinking-block accumulation.
|
|
5
|
+
*
|
|
6
|
+
* The ordered accumulation buffer preserves all content blocks from the
|
|
7
|
+
* assistant turn in their original stream positions. The C3 continuation
|
|
8
|
+
* builder reads this buffer to reconstruct the assistant turn for the
|
|
9
|
+
* follow-up request.
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
import { type Logging, Result } from '@fgv/ts-utils';
|
|
14
|
+
import { type JsonObject } from '@fgv/ts-json-base';
|
|
15
|
+
import { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';
|
|
16
|
+
import { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';
|
|
17
|
+
import { IStreamApiConfig } from './common';
|
|
18
|
+
/**
|
|
19
|
+
* An accumulated `thinking` block from the assistant turn. The `thinking` text
|
|
20
|
+
* and `signature` are both concatenated across their respective delta events.
|
|
21
|
+
* The full block is passed to the C3 continuation builder for round-trip preservation.
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
export interface IAccumulatedThinkingBlock {
|
|
25
|
+
readonly type: 'thinking';
|
|
26
|
+
thinking: string;
|
|
27
|
+
signature: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* An accumulated `redacted_thinking` block from the assistant turn. The `data`
|
|
31
|
+
* field is opaque and arrives complete in the `content_block_start` event — no
|
|
32
|
+
* delta events follow. Passed through unmodified to the C3 continuation builder.
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
export interface IAccumulatedRedactedThinkingBlock {
|
|
36
|
+
readonly type: 'redacted_thinking';
|
|
37
|
+
readonly data: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* An accumulated `text` block from the assistant turn.
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
export interface IAccumulatedTextBlock {
|
|
44
|
+
readonly type: 'text';
|
|
45
|
+
text: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* An accumulated `tool_use` block from the assistant turn (client-defined tool call).
|
|
49
|
+
* The `argsBuffer` is the concatenation of all `input_json_delta` chunks.
|
|
50
|
+
* @internal
|
|
51
|
+
*/
|
|
52
|
+
export interface IAccumulatedToolUseBlock {
|
|
53
|
+
readonly type: 'tool_use';
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly name: string;
|
|
56
|
+
argsBuffer: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Discriminated union of all accumulated Anthropic content block types.
|
|
60
|
+
* The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed
|
|
61
|
+
* by the SSE `index` field from `content_block_start` events.
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
export type IAccumulatedBlock = IAccumulatedThinkingBlock | IAccumulatedRedactedThinkingBlock | IAccumulatedTextBlock | IAccumulatedToolUseBlock;
|
|
65
|
+
/**
|
|
66
|
+
* Issues a streaming Anthropic Messages request and returns the
|
|
67
|
+
* unified-event iterable on success.
|
|
68
|
+
*
|
|
69
|
+
* @internal
|
|
70
|
+
*/
|
|
71
|
+
export declare function callAnthropicStream(config: IStreamApiConfig, prompt: AiPrompt, messagesBefore: ReadonlyArray<IChatMessage> | undefined, temperature: number | undefined, tools: ReadonlyArray<AiToolConfig> | undefined, logger?: Logging.ILogger, signal?: AbortSignal, resolvedThinking?: IResolvedThinkingConfig, accumulationBuffer?: Map<number, IAccumulatedBlock>, continuationMessages?: ReadonlyArray<JsonObject>): Promise<Result<AsyncIterable<IAiStreamEvent>>>;
|
|
72
|
+
//# sourceMappingURL=anthropic.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,KAAK,OAAO,EAA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Aa,CAAC,YAAY,CAAC,GAAG,SAAS,EAC9C,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,EACxB,MAAM,CAAC,EAAE,WAAW,EACpB,gBAAgB,CAAC,EAAE,uBAAuB,EAC1C,kBAAkB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,EACnD,oBAAoB,CAAC,EAAE,aAAa,CAAC,UAAU,CAAC,GAC/C,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CA8ChD"}
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright (c) 2026 Erik Fortune
|
|
3
|
+
//
|
|
4
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
// in the Software without restriction, including without limitation the rights
|
|
7
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
// furnished to do so, subject to the following conditions:
|
|
10
|
+
//
|
|
11
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
// copies or substantial portions of the Software.
|
|
13
|
+
//
|
|
14
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
// SOFTWARE.
|
|
21
|
+
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
|
|
22
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
23
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
24
|
+
var m = o[Symbol.asyncIterator], i;
|
|
25
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
26
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
27
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
28
|
+
};
|
|
29
|
+
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
|
|
30
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
31
|
+
var g = generator.apply(thisArg, _arguments || []), i, q = [];
|
|
32
|
+
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
|
|
33
|
+
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
|
|
34
|
+
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
|
|
35
|
+
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
|
|
36
|
+
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
|
|
37
|
+
function fulfill(value) { resume("next", value); }
|
|
38
|
+
function reject(value) { resume("throw", value); }
|
|
39
|
+
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
|
|
40
|
+
};
|
|
41
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
+
exports.callAnthropicStream = callAnthropicStream;
|
|
43
|
+
/**
|
|
44
|
+
* Streaming adapter for the Anthropic Messages API. Handles server tool
|
|
45
|
+
* use (e.g. `web_search`) as unified `tool-event` markers and client-defined
|
|
46
|
+
* tool calls (type `tool_use`) with B4 thinking-block accumulation.
|
|
47
|
+
*
|
|
48
|
+
* The ordered accumulation buffer preserves all content blocks from the
|
|
49
|
+
* assistant turn in their original stream positions. The C3 continuation
|
|
50
|
+
* builder reads this buffer to reconstruct the assistant turn for the
|
|
51
|
+
* follow-up request.
|
|
52
|
+
*
|
|
53
|
+
* @packageDocumentation
|
|
54
|
+
*/
|
|
55
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
56
|
+
const chatRequestBuilders_1 = require("../chatRequestBuilders");
|
|
57
|
+
const sseParser_1 = require("../sseParser");
|
|
58
|
+
const toolFormats_1 = require("../toolFormats");
|
|
59
|
+
const thinkingOptionsResolver_1 = require("../thinkingOptionsResolver");
|
|
60
|
+
const common_1 = require("./common");
|
|
61
|
+
const anthropicContentBlockInner = ts_utils_1.Validators.object({
|
|
62
|
+
type: ts_utils_1.Validators.string.optional(),
|
|
63
|
+
name: ts_utils_1.Validators.string.optional(),
|
|
64
|
+
id: ts_utils_1.Validators.string.optional(),
|
|
65
|
+
data: ts_utils_1.Validators.string.optional()
|
|
66
|
+
}, { options: { optionalFields: ['type', 'name', 'id', 'data'] } });
|
|
67
|
+
const anthropicContentBlockStartPayload = ts_utils_1.Validators.object({
|
|
68
|
+
index: ts_utils_1.Validators.number.optional(),
|
|
69
|
+
content_block: anthropicContentBlockInner
|
|
70
|
+
}, { options: { optionalFields: ['index'] } });
|
|
71
|
+
const anthropicContentBlockDeltaInner = ts_utils_1.Validators.object({
|
|
72
|
+
type: ts_utils_1.Validators.string.optional(),
|
|
73
|
+
text: ts_utils_1.Validators.string.optional(),
|
|
74
|
+
partial_json: ts_utils_1.Validators.string.optional(),
|
|
75
|
+
thinking: ts_utils_1.Validators.string.optional(),
|
|
76
|
+
signature: ts_utils_1.Validators.string.optional()
|
|
77
|
+
}, { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } });
|
|
78
|
+
const anthropicContentBlockDeltaPayload = ts_utils_1.Validators.object({
|
|
79
|
+
index: ts_utils_1.Validators.number.optional(),
|
|
80
|
+
delta: anthropicContentBlockDeltaInner
|
|
81
|
+
}, { options: { optionalFields: ['index'] } });
|
|
82
|
+
const anthropicContentBlockStopPayload = ts_utils_1.Validators.object({ index: ts_utils_1.Validators.number.optional() }, { options: { optionalFields: ['index'] } });
|
|
83
|
+
const anthropicMessageDeltaInner = ts_utils_1.Validators.object({ stop_reason: ts_utils_1.Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });
|
|
84
|
+
const anthropicMessageDeltaPayload = ts_utils_1.Validators.object({
|
|
85
|
+
delta: anthropicMessageDeltaInner
|
|
86
|
+
});
|
|
87
|
+
const anthropicErrorInner = ts_utils_1.Validators.object({ message: ts_utils_1.Validators.string.optional() }, { options: { optionalFields: ['message'] } });
|
|
88
|
+
const anthropicErrorPayload = ts_utils_1.Validators.object({ error: anthropicErrorInner.optional() }, { options: { optionalFields: ['error'] } });
|
|
89
|
+
// ============================================================================
|
|
90
|
+
// Stream translator
|
|
91
|
+
// ============================================================================
|
|
92
|
+
/**
|
|
93
|
+
* Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a
|
|
94
|
+
* one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's
|
|
95
|
+
* `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set
|
|
96
|
+
* when a new event type is observed and confirmed safe to ignore.
|
|
97
|
+
*
|
|
98
|
+
* @internal
|
|
99
|
+
*/
|
|
100
|
+
const RECOGNIZED_ANTHROPIC_EVENTS = new Set([
|
|
101
|
+
// ---- handled by the translator ----
|
|
102
|
+
'content_block_start',
|
|
103
|
+
'content_block_delta',
|
|
104
|
+
'content_block_stop',
|
|
105
|
+
'message_delta',
|
|
106
|
+
'message_stop',
|
|
107
|
+
'error',
|
|
108
|
+
// ---- lifecycle / heartbeats: intentionally silent ----
|
|
109
|
+
'message_start',
|
|
110
|
+
'ping'
|
|
111
|
+
]);
|
|
112
|
+
/**
|
|
113
|
+
* Translates an Anthropic Messages API SSE stream into unified events.
|
|
114
|
+
*
|
|
115
|
+
* Maintains an ordered accumulation buffer (keyed by SSE `index`) for all
|
|
116
|
+
* content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.
|
|
117
|
+
* The buffer is available on the returned generator via `.accumulationBuffer`.
|
|
118
|
+
*
|
|
119
|
+
* Unrecognized event names are reported once per stream via `logger?.warn` —
|
|
120
|
+
* see {@link RECOGNIZED_ANTHROPIC_EVENTS}.
|
|
121
|
+
*
|
|
122
|
+
* @internal
|
|
123
|
+
*/
|
|
124
|
+
function translateAnthropicStream(response, accumulationBuffer, logger) {
|
|
125
|
+
return __asyncGenerator(this, arguments, function* translateAnthropicStream_1() {
|
|
126
|
+
var _a, e_1, _b, _c;
|
|
127
|
+
var _d, _e, _f, _g;
|
|
128
|
+
let fullText = '';
|
|
129
|
+
let truncated = false;
|
|
130
|
+
let stopped = false;
|
|
131
|
+
// Track unrecognized event names we have already warned about, so a hot stream of
|
|
132
|
+
// an unknown event type produces exactly one log line per name per stream.
|
|
133
|
+
const warnedEvents = new Set();
|
|
134
|
+
try {
|
|
135
|
+
/* c8 ignore next - body is non-null at this point per openSseConnection */
|
|
136
|
+
if (!response.body)
|
|
137
|
+
return yield __await(void 0);
|
|
138
|
+
try {
|
|
139
|
+
for (var _h = true, _j = __asyncValues((0, sseParser_1.readSseEvents)(response.body)), _k; _k = yield __await(_j.next()), _a = _k.done, !_a; _h = true) {
|
|
140
|
+
_c = _k.value;
|
|
141
|
+
_h = false;
|
|
142
|
+
const message = _c;
|
|
143
|
+
const eventName = message.event;
|
|
144
|
+
if (eventName === 'content_block_start') {
|
|
145
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), anthropicContentBlockStartPayload);
|
|
146
|
+
/* c8 ignore next 1 - defensive: payload null branch unreachable after validation */
|
|
147
|
+
if (!payload)
|
|
148
|
+
continue;
|
|
149
|
+
const { index: rawIndex, content_block: block } = payload;
|
|
150
|
+
const index = rawIndex !== null && rawIndex !== void 0 ? rawIndex : 0;
|
|
151
|
+
if (block.type === 'thinking') {
|
|
152
|
+
accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });
|
|
153
|
+
}
|
|
154
|
+
else if (block.type === 'redacted_thinking') {
|
|
155
|
+
accumulationBuffer.set(index, {
|
|
156
|
+
type: 'redacted_thinking',
|
|
157
|
+
/* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */
|
|
158
|
+
data: (_d = block.data) !== null && _d !== void 0 ? _d : ''
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
else if (block.type === 'text') {
|
|
162
|
+
accumulationBuffer.set(index, { type: 'text', text: '' });
|
|
163
|
+
}
|
|
164
|
+
else if (block.type === 'tool_use') {
|
|
165
|
+
// A tool_use block_start MUST carry a non-empty id and name: the id is the
|
|
166
|
+
// sole correlation key for the follow-up tool_result, and dropping the block
|
|
167
|
+
// silently (then ignoring its input_json_delta chunks at the delta handler
|
|
168
|
+
// below) is exactly how an orphaned block leaves the harness without a clean
|
|
169
|
+
// id and corrupts the continuation. Surface it loudly instead of dropping it.
|
|
170
|
+
if (block.id && block.name) {
|
|
171
|
+
accumulationBuffer.set(index, {
|
|
172
|
+
type: 'tool_use',
|
|
173
|
+
id: block.id,
|
|
174
|
+
name: block.name,
|
|
175
|
+
argsBuffer: ''
|
|
176
|
+
});
|
|
177
|
+
yield yield __await({ type: 'client-tool-call-start', toolName: block.name, callId: block.id });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
logger === null || logger === void 0 ? void 0 : logger.warn(`${common_1.MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +
|
|
181
|
+
`at index ${index} is missing a usable id and/or name ` +
|
|
182
|
+
`(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +
|
|
183
|
+
`No client tool call will be issued for this block; its argument deltas are dropped. ` +
|
|
184
|
+
`This usually indicates provider drift or a truncated stream.`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else if (block.type === 'server_tool_use' && block.name === 'web_search') {
|
|
188
|
+
yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'started' });
|
|
189
|
+
}
|
|
190
|
+
else if (block.type === 'web_search_tool_result') {
|
|
191
|
+
yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'completed' });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else if (eventName === 'content_block_delta') {
|
|
195
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), anthropicContentBlockDeltaPayload);
|
|
196
|
+
/* c8 ignore next 1 - defensive: payload null branch unreachable after validation */
|
|
197
|
+
if (!payload)
|
|
198
|
+
continue;
|
|
199
|
+
const { index: rawDeltaIndex, delta } = payload;
|
|
200
|
+
const index = rawDeltaIndex !== null && rawDeltaIndex !== void 0 ? rawDeltaIndex : 0;
|
|
201
|
+
const block = accumulationBuffer.get(index);
|
|
202
|
+
if (delta.type === 'text_delta' && typeof delta.text === 'string') {
|
|
203
|
+
/* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */
|
|
204
|
+
if ((block === null || block === void 0 ? void 0 : block.type) === 'text') {
|
|
205
|
+
block.text += delta.text;
|
|
206
|
+
}
|
|
207
|
+
if (delta.text.length > 0) {
|
|
208
|
+
fullText += delta.text;
|
|
209
|
+
yield yield __await({ type: 'text-delta', delta: delta.text });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
|
|
213
|
+
/* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */
|
|
214
|
+
if ((block === null || block === void 0 ? void 0 : block.type) === 'tool_use') {
|
|
215
|
+
block.argsBuffer += delta.partial_json;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
|
|
219
|
+
/* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */
|
|
220
|
+
if ((block === null || block === void 0 ? void 0 : block.type) === 'thinking') {
|
|
221
|
+
block.thinking += delta.thinking;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {
|
|
225
|
+
// CRITICAL (E5): signature must be APPENDED, not overwritten.
|
|
226
|
+
// The signature is base64 arriving in multiple chunks.
|
|
227
|
+
// Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.
|
|
228
|
+
/* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */
|
|
229
|
+
if ((block === null || block === void 0 ? void 0 : block.type) === 'thinking') {
|
|
230
|
+
block.signature += delta.signature;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else if (eventName === 'content_block_stop') {
|
|
235
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), anthropicContentBlockStopPayload);
|
|
236
|
+
/* c8 ignore next 1 - defensive: payload null branch unreachable after validation */
|
|
237
|
+
if (!payload)
|
|
238
|
+
continue;
|
|
239
|
+
/* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */
|
|
240
|
+
const block = accumulationBuffer.get((_e = payload.index) !== null && _e !== void 0 ? _e : 0);
|
|
241
|
+
/* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */
|
|
242
|
+
if ((block === null || block === void 0 ? void 0 : block.type) === 'tool_use') {
|
|
243
|
+
let args;
|
|
244
|
+
try {
|
|
245
|
+
/* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */
|
|
246
|
+
const parsed = JSON.parse(block.argsBuffer || '{}');
|
|
247
|
+
/* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */
|
|
248
|
+
args =
|
|
249
|
+
parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
250
|
+
? parsed
|
|
251
|
+
: {};
|
|
252
|
+
}
|
|
253
|
+
catch (_l) {
|
|
254
|
+
args = {};
|
|
255
|
+
}
|
|
256
|
+
/* c8 ignore stop */
|
|
257
|
+
yield yield __await({ type: 'client-tool-call-done', toolName: block.name, callId: block.id, args });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
else if (eventName === 'message_delta') {
|
|
261
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), anthropicMessageDeltaPayload);
|
|
262
|
+
/* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */
|
|
263
|
+
if ((payload === null || payload === void 0 ? void 0 : payload.delta.stop_reason) === 'max_tokens') {
|
|
264
|
+
truncated = true;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
else if (eventName === 'message_stop') {
|
|
268
|
+
stopped = true;
|
|
269
|
+
}
|
|
270
|
+
else if (eventName === 'error') {
|
|
271
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), anthropicErrorPayload);
|
|
272
|
+
yield yield __await({
|
|
273
|
+
type: 'error',
|
|
274
|
+
/* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */
|
|
275
|
+
message: (_g = (_f = payload === null || payload === void 0 ? void 0 : payload.error) === null || _f === void 0 ? void 0 : _f.message) !== null && _g !== void 0 ? _g : 'Anthropic stream returned an error event'
|
|
276
|
+
});
|
|
277
|
+
return yield __await(void 0);
|
|
278
|
+
}
|
|
279
|
+
else if (typeof eventName === 'string' &&
|
|
280
|
+
!RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&
|
|
281
|
+
!warnedEvents.has(eventName)) {
|
|
282
|
+
// Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time
|
|
283
|
+
// warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either
|
|
284
|
+
// handled or confirmed safe to ignore.
|
|
285
|
+
warnedEvents.add(eventName);
|
|
286
|
+
logger === null || logger === void 0 ? void 0 : logger.warn(`${common_1.UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +
|
|
287
|
+
`'${eventName}'. ` +
|
|
288
|
+
`payload preview: ${(0, common_1.formatUnrecognizedEventPayloadPreview)(message.data)}. ` +
|
|
289
|
+
`This may indicate provider drift — if the new event carries data the adapter ` +
|
|
290
|
+
`should surface, add a handler; otherwise add the name to ` +
|
|
291
|
+
`RECOGNIZED_ANTHROPIC_EVENTS.`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
296
|
+
finally {
|
|
297
|
+
try {
|
|
298
|
+
if (!_h && !_a && (_b = _j.return)) yield __await(_b.call(_j));
|
|
299
|
+
}
|
|
300
|
+
finally { if (e_1) throw e_1.error; }
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
catch (err) /* c8 ignore start - defensive: stream errors are always Error instances */ {
|
|
304
|
+
yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
|
|
305
|
+
return yield __await(void 0);
|
|
306
|
+
} /* c8 ignore stop */
|
|
307
|
+
if (stopped) {
|
|
308
|
+
yield yield __await({ type: 'done', truncated, fullText });
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
yield yield __await({ type: 'error', message: 'Anthropic stream ended without a message_stop event' });
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
// ============================================================================
|
|
316
|
+
// Per-format request caller
|
|
317
|
+
// ============================================================================
|
|
318
|
+
/**
|
|
319
|
+
* Issues a streaming Anthropic Messages request and returns the
|
|
320
|
+
* unified-event iterable on success.
|
|
321
|
+
*
|
|
322
|
+
* @internal
|
|
323
|
+
*/
|
|
324
|
+
async function callAnthropicStream(config, prompt, messagesBefore, temperature, tools, logger, signal, resolvedThinking, accumulationBuffer, continuationMessages) {
|
|
325
|
+
const url = `${config.baseUrl}/messages`;
|
|
326
|
+
const messages = (0, chatRequestBuilders_1.buildAnthropicMessages)(prompt, {
|
|
327
|
+
head: messagesBefore,
|
|
328
|
+
rawTail: continuationMessages
|
|
329
|
+
});
|
|
330
|
+
const body = {
|
|
331
|
+
model: config.model,
|
|
332
|
+
system: prompt.system,
|
|
333
|
+
messages,
|
|
334
|
+
max_tokens: 4096,
|
|
335
|
+
stream: true
|
|
336
|
+
};
|
|
337
|
+
// Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When
|
|
338
|
+
// thinking is active it is also rejected — the completion/streaming paths validate this upstream,
|
|
339
|
+
// and the effort gate here is the safety net for the (unguarded) client-tool path.
|
|
340
|
+
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.anthropicEffort) === undefined) {
|
|
341
|
+
if (temperature !== undefined) {
|
|
342
|
+
body.temperature = temperature;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.anthropicEffort) !== undefined) {
|
|
346
|
+
body.thinking = {
|
|
347
|
+
type: 'enabled',
|
|
348
|
+
budget_tokens: (0, thinkingOptionsResolver_1.anthropicEffortToBudgetTokens)(resolvedThinking.anthropicEffort)
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
|
|
352
|
+
Object.assign(body, resolvedThinking.otherParams);
|
|
353
|
+
}
|
|
354
|
+
if (tools && tools.length > 0) {
|
|
355
|
+
body.tools = (0, toolFormats_1.toAnthropicTools)(tools);
|
|
356
|
+
}
|
|
357
|
+
const headers = {
|
|
358
|
+
'x-api-key': config.apiKey,
|
|
359
|
+
'anthropic-version': '2023-06-01',
|
|
360
|
+
'anthropic-dangerous-direct-browser-access': 'true'
|
|
361
|
+
};
|
|
362
|
+
/* c8 ignore next 4 - optional logger diagnostic output */
|
|
363
|
+
if (logger) {
|
|
364
|
+
const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';
|
|
365
|
+
logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);
|
|
366
|
+
}
|
|
367
|
+
const buffer = accumulationBuffer !== null && accumulationBuffer !== void 0 ? accumulationBuffer : new Map();
|
|
368
|
+
const conn = await (0, common_1.openSseConnection)(url, headers, body, logger, signal);
|
|
369
|
+
return conn.onSuccess((response) => (0, ts_utils_1.succeed)(translateAnthropicStream(response, buffer, logger)));
|
|
370
|
+
}
|
|
371
|
+
//# sourceMappingURL=anthropic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;;;;;;;;;;;;;;;;;;;;AAidZ,kDAyDC;AAxgBD;;;;;;;;;;;GAWG;AAEH,4CAA0F;AAG1F,gEAAgE;AAEhE,4CAAgE;AAChE,gDAAkD;AAClD,wEAAyG;AACzG,qCAOkB;AAiIlB,MAAM,0BAA0B,GAK3B,qBAAU,CAAC,MAAM,CACpB;IACE,IAAI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hB,gBAAgB,CAAE,WAAW,MAAK,SAAS,EAAE,CAAC;QAChD,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,WAAW,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAA,8BAAgB,EAAC,KAAK,CAAC,CAAC;IACvC,CAAC;IACD,MAAM,OAAO,GAA2B;QACtC,WAAW,EAAE,MAAM,CAAC,MAAM;QAC1B,mBAAmB,EAAE,YAAY;QACjC,2CAA2C,EAAE,MAAM;KACpD,CAAC;IACF,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,8BAA8B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,MAAM,GAAG,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,IAAI,GAAG,EAA6B,CAAC;IAC1E,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;AACnG,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for the Anthropic Messages API. Handles server tool\n * use (e.g. `web_search`) as unified `tool-event` markers and client-defined\n * tool calls (type `tool_use`) with B4 thinking-block accumulation.\n *\n * The ordered accumulation buffer preserves all content blocks from the\n * assistant turn in their original stream positions. The C3 continuation\n * builder reads this buffer to reconstruct the assistant turn for the\n * follow-up request.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport {\n IStreamApiConfig,\n MALFORMED_TOOL_USE_WARN_TAG,\n UNRECOGNIZED_EVENT_WARN_TAG,\n formatUnrecognizedEventPayloadPreview,\n openSseConnection,\n validateEventPayload\n} from './common';\n\n// ============================================================================\n// Accumulated block types (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated `thinking` block from the assistant turn. The `thinking` text\n * and `signature` are both concatenated across their respective delta events.\n * The full block is passed to the C3 continuation builder for round-trip preservation.\n * @internal\n */\nexport interface IAccumulatedThinkingBlock {\n readonly type: 'thinking';\n thinking: string;\n signature: string;\n}\n\n/**\n * An accumulated `redacted_thinking` block from the assistant turn. The `data`\n * field is opaque and arrives complete in the `content_block_start` event — no\n * delta events follow. Passed through unmodified to the C3 continuation builder.\n * @internal\n */\nexport interface IAccumulatedRedactedThinkingBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\n/**\n * An accumulated `text` block from the assistant turn.\n * @internal\n */\nexport interface IAccumulatedTextBlock {\n readonly type: 'text';\n text: string;\n}\n\n/**\n * An accumulated `tool_use` block from the assistant turn (client-defined tool call).\n * The `argsBuffer` is the concatenation of all `input_json_delta` chunks.\n * @internal\n */\nexport interface IAccumulatedToolUseBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n argsBuffer: string;\n}\n\n/**\n * Discriminated union of all accumulated Anthropic content block types.\n * The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed\n * by the SSE `index` field from `content_block_start` events.\n * @internal\n */\nexport type IAccumulatedBlock =\n | IAccumulatedThinkingBlock\n | IAccumulatedRedactedThinkingBlock\n | IAccumulatedTextBlock\n | IAccumulatedToolUseBlock;\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event with the `index` field.\n * The `index` field is optional for backward compatibility with providers that\n * omit it; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly index?: number;\n readonly content_block: {\n readonly type?: string;\n readonly name?: string;\n readonly id?: string;\n readonly data?: string;\n };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. Various delta types are\n * discriminated on `delta.type`:\n * - `text_delta`: text content\n * - `input_json_delta`: tool argument accumulation\n * - `thinking_delta`: thinking text accumulation\n * - `signature_delta`: thinking signature accumulation (MUST be appended, not overwritten)\n *\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly index?: number;\n readonly delta: {\n readonly type?: string;\n readonly text?: string;\n readonly partial_json?: string;\n readonly thinking?: string;\n readonly signature?: string;\n };\n}\n\n/**\n * Payload of a `content_block_stop` SSE event.\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStopPayload {\n readonly index?: number;\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{\n type?: string;\n name?: string;\n id?: string;\n data?: string;\n}> = Validators.object<{ type?: string; name?: string; id?: string; data?: string }>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional(),\n id: Validators.string.optional(),\n data: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name', 'id', 'data'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>(\n {\n index: Validators.number.optional(),\n content_block: anthropicContentBlockInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockDeltaInner: Validator<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}> = Validators.object<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional(),\n partial_json: Validators.string.optional(),\n thinking: Validators.string.optional(),\n signature: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>(\n {\n index: Validators.number.optional(),\n delta: anthropicContentBlockDeltaInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockStopPayload: Validator<IAnthropicContentBlockStopPayload> =\n Validators.object<IAnthropicContentBlockStopPayload>(\n { index: Validators.number.optional() },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a\n * one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's\n * `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set\n * when a new event type is observed and confirmed safe to ignore.\n *\n * @internal\n */\nconst RECOGNIZED_ANTHROPIC_EVENTS: ReadonlySet<string> = new Set<string>([\n // ---- handled by the translator ----\n 'content_block_start',\n 'content_block_delta',\n 'content_block_stop',\n 'message_delta',\n 'message_stop',\n 'error',\n // ---- lifecycle / heartbeats: intentionally silent ----\n 'message_start',\n 'ping'\n]);\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * Maintains an ordered accumulation buffer (keyed by SSE `index`) for all\n * content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.\n * The buffer is available on the returned generator via `.accumulationBuffer`.\n *\n * Unrecognized event names are reported once per stream via `logger?.warn` —\n * see {@link RECOGNIZED_ANTHROPIC_EVENTS}.\n *\n * @internal\n */\nasync function* translateAnthropicStream(\n response: Response,\n accumulationBuffer: Map<number, IAccumulatedBlock>,\n logger?: Logging.ILogger\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n // Track unrecognized event names we have already warned about, so a hot stream of\n // an unknown event type produces exactly one log line per name per stream.\n const warnedEvents = new Set<string>();\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawIndex, content_block: block } = payload;\n const index = rawIndex ?? 0;\n\n if (block.type === 'thinking') {\n accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });\n } else if (block.type === 'redacted_thinking') {\n accumulationBuffer.set(index, {\n type: 'redacted_thinking',\n /* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */\n data: block.data ?? ''\n });\n } else if (block.type === 'text') {\n accumulationBuffer.set(index, { type: 'text', text: '' });\n } else if (block.type === 'tool_use') {\n // A tool_use block_start MUST carry a non-empty id and name: the id is the\n // sole correlation key for the follow-up tool_result, and dropping the block\n // silently (then ignoring its input_json_delta chunks at the delta handler\n // below) is exactly how an orphaned block leaves the harness without a clean\n // id and corrupts the continuation. Surface it loudly instead of dropping it.\n if (block.id && block.name) {\n accumulationBuffer.set(index, {\n type: 'tool_use',\n id: block.id,\n name: block.name,\n argsBuffer: ''\n });\n yield { type: 'client-tool-call-start', toolName: block.name, callId: block.id };\n } else {\n logger?.warn(\n `${MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +\n `at index ${index} is missing a usable id and/or name ` +\n `(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +\n `No client tool call will be issued for this block; its argument deltas are dropped. ` +\n `This usually indicates provider drift or a truncated stream.`\n );\n }\n } else if (block.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawDeltaIndex, delta } = payload;\n const index = rawDeltaIndex ?? 0;\n const block = accumulationBuffer.get(index);\n\n if (delta.type === 'text_delta' && typeof delta.text === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'text') {\n block.text += delta.text;\n }\n if (delta.text.length > 0) {\n fullText += delta.text;\n yield { type: 'text-delta', delta: delta.text };\n }\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'tool_use') {\n block.argsBuffer += delta.partial_json;\n }\n } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.thinking += delta.thinking;\n }\n } else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {\n // CRITICAL (E5): signature must be APPENDED, not overwritten.\n // The signature is base64 arriving in multiple chunks.\n // Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.signature += delta.signature;\n }\n }\n } else if (eventName === 'content_block_stop') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStopPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n /* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */\n const block = accumulationBuffer.get(payload.index ?? 0);\n /* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */\n if (block?.type === 'tool_use') {\n let args: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */\n const parsed = JSON.parse(block.argsBuffer || '{}') as unknown;\n /* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */\n args =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : {};\n } catch {\n args = {};\n }\n /* c8 ignore stop */\n yield { type: 'client-tool-call-done', toolName: block.name, callId: block.id, args };\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n } else if (\n typeof eventName === 'string' &&\n !RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&\n !warnedEvents.has(eventName)\n ) {\n // Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time\n // warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either\n // handled or confirmed safe to ignore.\n warnedEvents.add(eventName);\n logger?.warn(\n `${UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +\n `'${eventName}'. ` +\n `payload preview: ${formatUnrecognizedEventPayloadPreview(message.data)}. ` +\n `This may indicate provider drift — if the new event carries data the adapter ` +\n `should surface, add a handler; otherwise add the name to ` +\n `RECOGNIZED_ANTHROPIC_EVENTS.`\n );\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n accumulationBuffer?: Map<number, IAccumulatedBlock>,\n continuationMessages?: ReadonlyArray<JsonObject>\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n max_tokens: 4096,\n stream: true\n };\n // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When\n // thinking is active it is also rejected — the completion/streaming paths validate this upstream,\n // and the effort gate here is the safety net for the (unguarded) client-tool path.\n if (resolvedThinking?.anthropicEffort === undefined) {\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n }\n if (resolvedThinking?.anthropicEffort !== undefined) {\n body.thinking = {\n type: 'enabled',\n budget_tokens: anthropicEffortToBudgetTokens(resolvedThinking.anthropicEffort)\n };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = {\n 'x-api-key': config.apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true'\n };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const buffer = accumulationBuffer ?? new Map<number, IAccumulatedBlock>();\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response, buffer, logger)));\n}\n"]}
|