@fgv/ts-extras 5.1.0-2 → 5.1.0-20
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 +2 -1
- package/dist/index.browser.js.map +1 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/ai-assist/apiClient.js +792 -57
- package/dist/packlets/ai-assist/apiClient.js.map +1 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js +180 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/dist/packlets/ai-assist/converters.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +4 -3
- package/dist/packlets/ai-assist/index.js.map +1 -0
- package/dist/packlets/ai-assist/model.js +20 -3
- package/dist/packlets/ai-assist/model.js.map +1 -0
- package/dist/packlets/ai-assist/registry.js +111 -10
- package/dist/packlets/ai-assist/registry.js.map +1 -0
- package/dist/packlets/ai-assist/sseParser.js +122 -0
- package/dist/packlets/ai-assist/sseParser.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +192 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js +77 -0
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +160 -0
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +149 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +163 -0
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +157 -0
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/dist/packlets/ai-assist/streamingClient.js +88 -0
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
- package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
- package/dist/packlets/conversion/converters.js +34 -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.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/index.browser.js +2 -0
- package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
- package/dist/packlets/crypto-utils/index.js +2 -0
- package/dist/packlets/crypto-utils/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +57 -0
- package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/converters.js +101 -9
- package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/index.js +1 -0
- package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/dist/packlets/crypto-utils/keystore/keyStore.js +431 -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 +9 -0
- package/dist/packlets/crypto-utils/model.js.map +1 -0
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js +152 -1
- package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
- package/dist/packlets/csv/csvHelpers.js.map +1 -0
- 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.map +1 -0
- 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.map +1 -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 +1442 -45
- package/dist/tsdoc-metadata.json +1 -1
- package/lib/index.browser.d.ts +2 -1
- package/lib/index.browser.d.ts.map +1 -0
- package/lib/index.browser.js +3 -1
- 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 +111 -1
- package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/apiClient.js +795 -56
- package/lib/packlets/ai-assist/apiClient.js.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +89 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js +189 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
- package/lib/packlets/ai-assist/converters.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +4 -3
- package/lib/packlets/ai-assist/index.d.ts.map +1 -0
- package/lib/packlets/ai-assist/index.js +12 -1
- package/lib/packlets/ai-assist/index.js.map +1 -0
- package/lib/packlets/ai-assist/model.d.ts +332 -2
- package/lib/packlets/ai-assist/model.d.ts.map +1 -0
- package/lib/packlets/ai-assist/model.js +21 -3
- package/lib/packlets/ai-assist/model.js.map +1 -0
- package/lib/packlets/ai-assist/registry.d.ts +34 -1
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
- package/lib/packlets/ai-assist/registry.js +114 -11
- 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 +127 -0
- package/lib/packlets/ai-assist/sseParser.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +18 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +195 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +71 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js +81 -0
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +19 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +163 -0
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +18 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +152 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +19 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +166 -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 +160 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts +33 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamingClient.js +93 -0
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
- package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
- 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 +35 -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.map +1 -0
- 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/index.browser.d.ts +1 -0
- package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.browser.js +4 -1
- package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
- package/lib/packlets/crypto-utils/index.d.ts +1 -0
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/index.js +4 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +39 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +60 -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 +100 -8
- package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts +1 -0
- package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/index.js +1 -0
- package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +125 -12
- package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/keystore/keyStore.js +431 -118
- package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
- package/lib/packlets/crypto-utils/keystore/model.d.ts +248 -17
- 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 +50 -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 +140 -0
- package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/model.js +10 -1
- package/lib/packlets/crypto-utils/model.js.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +51 -1
- package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js +151 -0
- package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
- package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
- package/lib/packlets/csv/csvHelpers.js.map +1 -0
- package/lib/packlets/csv/index.browser.d.ts.map +1 -0
- 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.map +1 -0
- package/lib/packlets/mustache/index.js.map +1 -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.map +1 -0
- package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
- package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
- 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.map +1 -0
- package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
- package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -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 +24 -23
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming adapter for the OpenAI / xAI Responses API. This is the format
|
|
3
|
+
* used when server-side tools (e.g. web_search) are requested — Chat
|
|
4
|
+
* Completions doesn't support tool progress events, but the Responses API
|
|
5
|
+
* does.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import { type Logging, Result } from '@fgv/ts-utils';
|
|
10
|
+
import { AiPrompt, type AiServerToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';
|
|
11
|
+
import { IStreamApiConfig } from './common';
|
|
12
|
+
/**
|
|
13
|
+
* Issues a streaming Responses API request (with tools) and returns the
|
|
14
|
+
* unified-event iterable on success.
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export declare function callOpenAiResponsesStream(config: IStreamApiConfig, prompt: AiPrompt, tools: ReadonlyArray<AiServerToolConfig>, messagesBefore: ReadonlyArray<IChatMessage> | undefined, temperature: number, logger?: Logging.ILogger, signal?: AbortSignal): Promise<Result<AsyncIterable<IAiStreamEvent>>>;
|
|
19
|
+
//# sourceMappingURL=openaiResponses.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openaiResponses.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/openaiResponses.ts"],"names":[],"mappings":"AAoBA;;;;;;;GAOG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,EAAuC,MAAM,eAAe,CAAC;AAG1F,OAAO,EAAE,QAAQ,EAAE,KAAK,kBAAkB,EAAE,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAGrG,OAAO,EAAE,gBAAgB,EAA2C,MAAM,UAAU,CAAC;AAsHrF;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,QAAQ,EAChB,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,EACxC,cAAc,EAAE,aAAa,CAAC,YAAY,CAAC,GAAG,SAAS,EACvD,WAAW,EAAE,MAAM,EACnB,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,EACxB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CAmBhD"}
|
|
@@ -0,0 +1,166 @@
|
|
|
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.callOpenAiResponsesStream = callOpenAiResponsesStream;
|
|
43
|
+
/**
|
|
44
|
+
* Streaming adapter for the OpenAI / xAI Responses API. This is the format
|
|
45
|
+
* used when server-side tools (e.g. web_search) are requested — Chat
|
|
46
|
+
* Completions doesn't support tool progress events, but the Responses API
|
|
47
|
+
* does.
|
|
48
|
+
*
|
|
49
|
+
* @packageDocumentation
|
|
50
|
+
*/
|
|
51
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
52
|
+
const chatRequestBuilders_1 = require("../chatRequestBuilders");
|
|
53
|
+
const sseParser_1 = require("../sseParser");
|
|
54
|
+
const toolFormats_1 = require("../toolFormats");
|
|
55
|
+
const common_1 = require("./common");
|
|
56
|
+
const responsesDeltaPayload = ts_utils_1.Validators.object({
|
|
57
|
+
delta: ts_utils_1.Validators.string
|
|
58
|
+
});
|
|
59
|
+
const responsesCompletedPayload = ts_utils_1.Validators.object({
|
|
60
|
+
response: ts_utils_1.Validators.object({ status: ts_utils_1.Validators.string.optional() }, { options: { optionalFields: ['status'] } })
|
|
61
|
+
});
|
|
62
|
+
const responsesErrorInner = ts_utils_1.Validators.object({ message: ts_utils_1.Validators.string.optional() }, { options: { optionalFields: ['message'] } });
|
|
63
|
+
const responsesErrorPayload = ts_utils_1.Validators.object({
|
|
64
|
+
error: responsesErrorInner.optional(),
|
|
65
|
+
message: ts_utils_1.Validators.string.optional()
|
|
66
|
+
}, { options: { optionalFields: ['error', 'message'] } });
|
|
67
|
+
// ============================================================================
|
|
68
|
+
// Stream translator
|
|
69
|
+
// ============================================================================
|
|
70
|
+
/**
|
|
71
|
+
* Translates an OpenAI Responses API SSE stream into unified events.
|
|
72
|
+
*
|
|
73
|
+
* @internal
|
|
74
|
+
*/
|
|
75
|
+
function translateOpenAiResponsesStream(response) {
|
|
76
|
+
return __asyncGenerator(this, arguments, function* translateOpenAiResponsesStream_1() {
|
|
77
|
+
var _a, e_1, _b, _c;
|
|
78
|
+
var _d, _e, _f;
|
|
79
|
+
let fullText = '';
|
|
80
|
+
let truncated = false;
|
|
81
|
+
let completed = false;
|
|
82
|
+
try {
|
|
83
|
+
/* c8 ignore next - body is non-null at this point per openSseConnection */
|
|
84
|
+
if (!response.body)
|
|
85
|
+
return yield __await(void 0);
|
|
86
|
+
try {
|
|
87
|
+
for (var _g = true, _h = __asyncValues((0, sseParser_1.readSseEvents)(response.body)), _j; _j = yield __await(_h.next()), _a = _j.done, !_a; _g = true) {
|
|
88
|
+
_c = _j.value;
|
|
89
|
+
_g = false;
|
|
90
|
+
const message = _c;
|
|
91
|
+
const eventName = message.event;
|
|
92
|
+
if (eventName === 'response.output_text.delta') {
|
|
93
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), responsesDeltaPayload);
|
|
94
|
+
const delta = payload === null || payload === void 0 ? void 0 : payload.delta;
|
|
95
|
+
if (typeof delta === 'string' && delta.length > 0) {
|
|
96
|
+
fullText += delta;
|
|
97
|
+
yield yield __await({ type: 'text-delta', delta });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else if (eventName === 'response.web_search_call.in_progress') {
|
|
101
|
+
yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'started' });
|
|
102
|
+
}
|
|
103
|
+
else if (eventName === 'response.web_search_call.completed') {
|
|
104
|
+
yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'completed' });
|
|
105
|
+
}
|
|
106
|
+
else if (eventName === 'response.completed') {
|
|
107
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), responsesCompletedPayload);
|
|
108
|
+
truncated = (payload === null || payload === void 0 ? void 0 : payload.response.status) === 'incomplete';
|
|
109
|
+
completed = true;
|
|
110
|
+
}
|
|
111
|
+
else if (eventName === 'response.failed' || eventName === 'error') {
|
|
112
|
+
const payload = (0, common_1.validateEventPayload)((0, sseParser_1.parseSseEventJson)(message.data), responsesErrorPayload);
|
|
113
|
+
const errMsg = (_f = (_e = (_d = payload === null || payload === void 0 ? void 0 : payload.error) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : payload === null || payload === void 0 ? void 0 : payload.message) !== null && _f !== void 0 ? _f : 'Responses API stream failed';
|
|
114
|
+
yield yield __await({ type: 'error', message: errMsg });
|
|
115
|
+
return yield __await(void 0);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
120
|
+
finally {
|
|
121
|
+
try {
|
|
122
|
+
if (!_g && !_a && (_b = _h.return)) yield __await(_b.call(_h));
|
|
123
|
+
}
|
|
124
|
+
finally { if (e_1) throw e_1.error; }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
|
|
129
|
+
return yield __await(void 0);
|
|
130
|
+
}
|
|
131
|
+
if (completed) {
|
|
132
|
+
yield yield __await({ type: 'done', truncated, fullText });
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
yield yield __await({ type: 'error', message: 'Responses API stream ended without a completed event' });
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
// ============================================================================
|
|
140
|
+
// Per-format request caller
|
|
141
|
+
// ============================================================================
|
|
142
|
+
/**
|
|
143
|
+
* Issues a streaming Responses API request (with tools) and returns the
|
|
144
|
+
* unified-event iterable on success.
|
|
145
|
+
*
|
|
146
|
+
* @internal
|
|
147
|
+
*/
|
|
148
|
+
async function callOpenAiResponsesStream(config, prompt, tools, messagesBefore, temperature, logger, signal) {
|
|
149
|
+
const url = `${config.baseUrl}/responses`;
|
|
150
|
+
const input = (0, chatRequestBuilders_1.buildMessages)(prompt.system, (0, chatRequestBuilders_1.buildOpenAiResponsesUserContent)(prompt), {
|
|
151
|
+
head: messagesBefore
|
|
152
|
+
});
|
|
153
|
+
const body = {
|
|
154
|
+
model: config.model,
|
|
155
|
+
input,
|
|
156
|
+
tools: (0, toolFormats_1.toResponsesApiTools)(tools),
|
|
157
|
+
temperature,
|
|
158
|
+
stream: true
|
|
159
|
+
};
|
|
160
|
+
const headers = { Authorization: `Bearer ${config.apiKey}` };
|
|
161
|
+
/* c8 ignore next 1 - optional logger */
|
|
162
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI Responses streaming: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);
|
|
163
|
+
const conn = await (0, common_1.openSseConnection)(url, headers, body, logger, signal);
|
|
164
|
+
return conn.onSuccess((response) => (0, ts_utils_1.succeed)(translateOpenAiResponsesStream(response)));
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=openaiResponses.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openaiResponses.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/openaiResponses.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;;;;;;;;;;;;;;;;;;;;;;AA6IZ,8DA2BC;AAtKD;;;;;;;GAOG;AAEH,4CAA0F;AAE1F,gEAAwF;AAExF,4CAAgE;AAChE,gDAAqD;AACrD,qCAAqF;AAoCrF,MAAM,qBAAqB,GAAsC,qBAA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AAC,MAAM,CAAC,EAAE;QAClF,IAAI,EAAE,cAAc;KACrB,CAAC,CAAC;IACH,MAAM,IAAI,GAA4B;QACpC,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,KAAK;QACL,KAAK,EAAE,IAAA,iCAAmB,EAAC,KAAK,CAAC;QACjC,WAAW;QACX,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,OAAO,GAA2B,EAAE,aAAa,EAAE,UAAU,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;IACrF,wCAAwC;IACxC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CACV,qCAAqC,MAAM,CAAC,KAAK,WAAW,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CACjG,CAAC;IACF,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,8BAA8B,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AACzF,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 OpenAI / xAI Responses API. This is the format\n * used when server-side tools (e.g. web_search) are requested — Chat\n * Completions doesn't support tool progress events, but the Responses API\n * does.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport { buildMessages, buildOpenAiResponsesUserContent } from '../chatRequestBuilders';\nimport { AiPrompt, type AiServerToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toResponsesApiTools } from '../toolFormats';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `response.output_text.delta` SSE event.\n *\n * @internal\n */\ninterface IResponsesDeltaPayload {\n readonly delta: string;\n}\n\n/**\n * Payload of a `response.completed` SSE event. `status === 'incomplete'`\n * signals the stream was cut short (max output tokens, etc.).\n *\n * @internal\n */\ninterface IResponsesCompletedPayload {\n readonly response: { readonly status?: string };\n}\n\n/**\n * Payload of a `response.failed` or `error` SSE event. Both shapes appear\n * in the wild — sometimes `error.message`, sometimes a top-level `message`.\n *\n * @internal\n */\ninterface IResponsesErrorPayload {\n readonly error?: { readonly message?: string };\n readonly message?: string;\n}\n\nconst responsesDeltaPayload: Validator<IResponsesDeltaPayload> = Validators.object<IResponsesDeltaPayload>({\n delta: Validators.string\n});\n\nconst responsesCompletedPayload: Validator<IResponsesCompletedPayload> =\n Validators.object<IResponsesCompletedPayload>({\n response: Validators.object<{ status?: string }>(\n { status: Validators.string.optional() },\n { options: { optionalFields: ['status'] } }\n )\n });\n\nconst responsesErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst responsesErrorPayload: Validator<IResponsesErrorPayload> = Validators.object<IResponsesErrorPayload>(\n {\n error: responsesErrorInner.optional(),\n message: Validators.string.optional()\n },\n { options: { optionalFields: ['error', 'message'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates an OpenAI Responses API SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateOpenAiResponsesStream(response: Response): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let completed = false;\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 if (eventName === 'response.output_text.delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), responsesDeltaPayload);\n const delta = payload?.delta;\n if (typeof delta === 'string' && delta.length > 0) {\n fullText += delta;\n yield { type: 'text-delta', delta };\n }\n } else if (eventName === 'response.web_search_call.in_progress') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (eventName === 'response.web_search_call.completed') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n } else if (eventName === 'response.completed') {\n const payload = validateEventPayload(parseSseEventJson(message.data), responsesCompletedPayload);\n truncated = payload?.response.status === 'incomplete';\n completed = true;\n } else if (eventName === 'response.failed' || eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), responsesErrorPayload);\n const errMsg = payload?.error?.message ?? payload?.message ?? 'Responses API stream failed';\n yield { type: 'error', message: errMsg };\n return;\n }\n }\n } catch (err: unknown) {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n }\n\n if (completed) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Responses API stream ended without a completed event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Responses API request (with tools) and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callOpenAiResponsesStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n tools: ReadonlyArray<AiServerToolConfig>,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/responses`;\n const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {\n head: messagesBefore\n });\n const body: Record<string, unknown> = {\n model: config.model,\n input,\n tools: toResponsesApiTools(tools),\n temperature,\n stream: true\n };\n const headers: Record<string, string> = { Authorization: `Bearer ${config.apiKey}` };\n /* c8 ignore next 1 - optional logger */\n logger?.info(\n `OpenAI Responses streaming: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`\n );\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateOpenAiResponsesStream(response)));\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming adapter for a caller-provided proxy server. Unlike the
|
|
3
|
+
* provider-specific adapters, the proxy speaks our own unified vocabulary
|
|
4
|
+
* directly: each `data:` line is a JSON-serialized {@link AiAssist.IAiStreamEvent},
|
|
5
|
+
* so this adapter only validates the event-type discriminator and forwards.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import { Result } from '@fgv/ts-utils';
|
|
10
|
+
import { type IAiStreamEvent } from '../model';
|
|
11
|
+
import { IProviderCompletionStreamParams } from './common';
|
|
12
|
+
/**
|
|
13
|
+
* Calls the streaming chat endpoint on a proxy server instead of calling
|
|
14
|
+
* the provider directly from the browser.
|
|
15
|
+
*
|
|
16
|
+
* @remarks
|
|
17
|
+
* Proxy contract:
|
|
18
|
+
* - Endpoint: `POST ${proxyUrl}/api/ai/completion-stream`
|
|
19
|
+
* - Request body: same JSON as `/api/ai/completion` plus `"stream": true`
|
|
20
|
+
* - Response: `Content-Type: text/event-stream`; body is the unified
|
|
21
|
+
* {@link AiAssist.IAiStreamEvent} JSON-serialized one event per SSE `data:` line
|
|
22
|
+
* (no `event:` line needed since the type discriminator is in the JSON).
|
|
23
|
+
* - Error response (when the proxy can't even start): JSON `{error: string}`
|
|
24
|
+
* with a non-2xx status, surfaced as `proxy: ${error}`.
|
|
25
|
+
*
|
|
26
|
+
* The proxy server is responsible for opening the upstream SSE connection,
|
|
27
|
+
* translating provider-native events to the unified vocabulary, and
|
|
28
|
+
* forwarding events as they arrive (no buffering). The library does not
|
|
29
|
+
* ship a proxy implementation.
|
|
30
|
+
*
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
export declare function callProxiedCompletionStream(proxyUrl: string, params: IProviderCompletionStreamParams): Promise<Result<AsyncIterable<IAiStreamEvent>>>;
|
|
34
|
+
//# sourceMappingURL=proxy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/proxy.ts"],"names":[],"mappings":"AAoBA;;;;;;;GAOG;AAEH,OAAO,EAAE,MAAM,EAAuC,MAAM,eAAe,CAAC;AAE5E,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAA2C,MAAM,UAAU,CAAC;AAgEpG;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,2BAA2B,CAC/C,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CA+BhD"}
|
|
@@ -0,0 +1,160 @@
|
|
|
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.callProxiedCompletionStream = callProxiedCompletionStream;
|
|
43
|
+
/**
|
|
44
|
+
* Streaming adapter for a caller-provided proxy server. Unlike the
|
|
45
|
+
* provider-specific adapters, the proxy speaks our own unified vocabulary
|
|
46
|
+
* directly: each `data:` line is a JSON-serialized {@link AiAssist.IAiStreamEvent},
|
|
47
|
+
* so this adapter only validates the event-type discriminator and forwards.
|
|
48
|
+
*
|
|
49
|
+
* @packageDocumentation
|
|
50
|
+
*/
|
|
51
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
52
|
+
const sseParser_1 = require("../sseParser");
|
|
53
|
+
const common_1 = require("./common");
|
|
54
|
+
const proxyEventTypes = ['text-delta', 'tool-event', 'done', 'error'];
|
|
55
|
+
const proxyEventEnvelope = ts_utils_1.Validators.object({
|
|
56
|
+
type: ts_utils_1.Validators.enumeratedValue(proxyEventTypes)
|
|
57
|
+
});
|
|
58
|
+
// ============================================================================
|
|
59
|
+
// Stream translator
|
|
60
|
+
// ============================================================================
|
|
61
|
+
/**
|
|
62
|
+
* Translates a proxied SSE stream back into {@link AiAssist.IAiStreamEvent} objects.
|
|
63
|
+
* Validation is limited to the type discriminator; the proxy is contractually
|
|
64
|
+
* required to emit shape-correct unified events.
|
|
65
|
+
*
|
|
66
|
+
* @internal
|
|
67
|
+
*/
|
|
68
|
+
function translateProxyStream(response) {
|
|
69
|
+
return __asyncGenerator(this, arguments, function* translateProxyStream_1() {
|
|
70
|
+
var _a, e_1, _b, _c;
|
|
71
|
+
try {
|
|
72
|
+
/* c8 ignore next - body is non-null at this point per openSseConnection */
|
|
73
|
+
if (!response.body)
|
|
74
|
+
return yield __await(void 0);
|
|
75
|
+
try {
|
|
76
|
+
for (var _d = true, _e = __asyncValues((0, sseParser_1.readSseEvents)(response.body)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
77
|
+
_c = _f.value;
|
|
78
|
+
_d = false;
|
|
79
|
+
const message = _c;
|
|
80
|
+
const json = (0, sseParser_1.parseSseEventJson)(message.data);
|
|
81
|
+
if (json === undefined) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const envelope = (0, common_1.validateEventPayload)(json, proxyEventEnvelope);
|
|
85
|
+
if (!envelope) {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const event = json;
|
|
89
|
+
yield yield __await(event);
|
|
90
|
+
if (envelope.type === 'done' || envelope.type === 'error') {
|
|
91
|
+
return yield __await(void 0);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
96
|
+
finally {
|
|
97
|
+
try {
|
|
98
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
99
|
+
}
|
|
100
|
+
finally { if (e_1) throw e_1.error; }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
// ============================================================================
|
|
109
|
+
// Public entry point
|
|
110
|
+
// ============================================================================
|
|
111
|
+
/**
|
|
112
|
+
* Calls the streaming chat endpoint on a proxy server instead of calling
|
|
113
|
+
* the provider directly from the browser.
|
|
114
|
+
*
|
|
115
|
+
* @remarks
|
|
116
|
+
* Proxy contract:
|
|
117
|
+
* - Endpoint: `POST ${proxyUrl}/api/ai/completion-stream`
|
|
118
|
+
* - Request body: same JSON as `/api/ai/completion` plus `"stream": true`
|
|
119
|
+
* - Response: `Content-Type: text/event-stream`; body is the unified
|
|
120
|
+
* {@link AiAssist.IAiStreamEvent} JSON-serialized one event per SSE `data:` line
|
|
121
|
+
* (no `event:` line needed since the type discriminator is in the JSON).
|
|
122
|
+
* - Error response (when the proxy can't even start): JSON `{error: string}`
|
|
123
|
+
* with a non-2xx status, surfaced as `proxy: ${error}`.
|
|
124
|
+
*
|
|
125
|
+
* The proxy server is responsible for opening the upstream SSE connection,
|
|
126
|
+
* translating provider-native events to the unified vocabulary, and
|
|
127
|
+
* forwarding events as they arrive (no buffering). The library does not
|
|
128
|
+
* ship a proxy implementation.
|
|
129
|
+
*
|
|
130
|
+
* @public
|
|
131
|
+
*/
|
|
132
|
+
async function callProxiedCompletionStream(proxyUrl, params) {
|
|
133
|
+
const { descriptor, apiKey, prompt, messagesBefore, temperature, modelOverride, logger, tools, signal } = params;
|
|
134
|
+
const promptBody = { system: prompt.system, user: prompt.user };
|
|
135
|
+
if (prompt.attachments.length > 0) {
|
|
136
|
+
promptBody.attachments = prompt.attachments;
|
|
137
|
+
}
|
|
138
|
+
const body = {
|
|
139
|
+
providerId: descriptor.id,
|
|
140
|
+
apiKey,
|
|
141
|
+
prompt: promptBody,
|
|
142
|
+
temperature: temperature !== null && temperature !== void 0 ? temperature : 0.7,
|
|
143
|
+
stream: true
|
|
144
|
+
};
|
|
145
|
+
if (messagesBefore && messagesBefore.length > 0) {
|
|
146
|
+
body.messagesBefore = messagesBefore;
|
|
147
|
+
}
|
|
148
|
+
if (modelOverride !== undefined) {
|
|
149
|
+
body.modelOverride = modelOverride;
|
|
150
|
+
}
|
|
151
|
+
if (tools && tools.length > 0) {
|
|
152
|
+
body.tools = tools;
|
|
153
|
+
}
|
|
154
|
+
/* c8 ignore next 1 - optional logger */
|
|
155
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`AI streaming proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
156
|
+
const url = `${proxyUrl}/api/ai/completion-stream`;
|
|
157
|
+
const conn = await (0, common_1.openSseConnection)(url, {}, body, logger, signal);
|
|
158
|
+
return conn.onSuccess((response) => (0, ts_utils_1.succeed)(translateProxyStream(response)));
|
|
159
|
+
}
|
|
160
|
+
//# sourceMappingURL=proxy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/proxy.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;;;;;;;;;;;;;;;;;;;;;;AAoGZ,kEAkCC;AAp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,CAAE,IAAI,CAAC,wCAAwC,UAAU,CAAC,EAAE,WAAW,QAAQ,EAAE,CAAC,CAAC;IAEzF,MAAM,GAAG,GAAG,GAAG,QAAQ,2BAA2B,CAAC;IACnD,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACpE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC/E,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 a caller-provided proxy server. Unlike the\n * provider-specific adapters, the proxy speaks our own unified vocabulary\n * directly: each `data:` line is a JSON-serialized {@link AiAssist.IAiStreamEvent},\n * so this adapter only validates the event-type discriminator and forwards.\n *\n * @packageDocumentation\n */\n\nimport { Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport { type IAiStreamEvent } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { IProviderCompletionStreamParams, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Event payload shape — a tagged-event envelope\n// ============================================================================\n\ntype ProxyEventType = 'text-delta' | 'tool-event' | 'done' | 'error';\n\n/**\n * Minimal envelope used to identify and discriminate proxy events. Once the\n * `type` is recognized, the event is forwarded as-is — the unified shape is\n * the proxy contract, so there's no further per-type validation here.\n *\n * @internal\n */\ninterface IProxyEventEnvelope {\n readonly type: ProxyEventType;\n}\n\nconst proxyEventTypes: ReadonlyArray<ProxyEventType> = ['text-delta', 'tool-event', 'done', 'error'];\n\nconst proxyEventEnvelope: Validator<IProxyEventEnvelope> = Validators.object<IProxyEventEnvelope>({\n type: Validators.enumeratedValue<ProxyEventType>(proxyEventTypes)\n});\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates a proxied SSE stream back into {@link AiAssist.IAiStreamEvent} objects.\n * Validation is limited to the type discriminator; the proxy is contractually\n * required to emit shape-correct unified events.\n *\n * @internal\n */\nasync function* translateProxyStream(response: Response): AsyncGenerator<IAiStreamEvent> {\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 json = parseSseEventJson(message.data);\n if (json === undefined) {\n continue;\n }\n const envelope = validateEventPayload(json, proxyEventEnvelope);\n if (!envelope) {\n continue;\n }\n const event = json as IAiStreamEvent;\n yield event;\n if (envelope.type === 'done' || envelope.type === 'error') {\n return;\n }\n }\n } catch (err: unknown) {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ============================================================================\n// Public entry point\n// ============================================================================\n\n/**\n * Calls the streaming chat endpoint on a proxy server instead of calling\n * the provider directly from the browser.\n *\n * @remarks\n * Proxy contract:\n * - Endpoint: `POST ${proxyUrl}/api/ai/completion-stream`\n * - Request body: same JSON as `/api/ai/completion` plus `\"stream\": true`\n * - Response: `Content-Type: text/event-stream`; body is the unified\n * {@link AiAssist.IAiStreamEvent} JSON-serialized one event per SSE `data:` line\n * (no `event:` line needed since the type discriminator is in the JSON).\n * - Error response (when the proxy can't even start): JSON `{error: string}`\n * with a non-2xx status, surfaced as `proxy: ${error}`.\n *\n * The proxy server is responsible for opening the upstream SSE connection,\n * translating provider-native events to the unified vocabulary, and\n * forwarding events as they arrive (no buffering). The library does not\n * ship a proxy implementation.\n *\n * @public\n */\nexport async function callProxiedCompletionStream(\n proxyUrl: string,\n params: IProviderCompletionStreamParams\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const { descriptor, apiKey, prompt, messagesBefore, temperature, modelOverride, logger, tools, signal } =\n params;\n\n const promptBody: Record<string, unknown> = { system: prompt.system, user: prompt.user };\n if (prompt.attachments.length > 0) {\n promptBody.attachments = prompt.attachments;\n }\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey,\n prompt: promptBody,\n temperature: temperature ?? 0.7,\n stream: true\n };\n if (messagesBefore && messagesBefore.length > 0) {\n body.messagesBefore = messagesBefore;\n }\n if (modelOverride !== undefined) {\n body.modelOverride = modelOverride;\n }\n if (tools && tools.length > 0) {\n body.tools = tools;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI streaming proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n\n const url = `${proxyUrl}/api/ai/completion-stream`;\n const conn = await openSseConnection(url, {}, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateProxyStream(response)));\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming chat completion client. Public façade over the per-format
|
|
3
|
+
* adapters under `streamingAdapters/`: provider dispatch and pre-flight
|
|
4
|
+
* validation live here; format-specific request/translation logic and the
|
|
5
|
+
* typed event-payload validators live with each adapter.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import { Result } from '@fgv/ts-utils';
|
|
10
|
+
import { type IAiStreamEvent } from './model';
|
|
11
|
+
import { type IProviderCompletionStreamParams } from './streamingAdapters/common';
|
|
12
|
+
export { callProxiedCompletionStream } from './streamingAdapters/proxy';
|
|
13
|
+
export type { IProviderCompletionStreamParams } from './streamingAdapters/common';
|
|
14
|
+
/**
|
|
15
|
+
* Calls the appropriate streaming chat completion API for a given provider.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`
|
|
19
|
+
* and the call isn't being routed through a proxy, this returns
|
|
20
|
+
* `Result.fail` before fetch is invoked. Callers should route through
|
|
21
|
+
* {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.
|
|
22
|
+
*
|
|
23
|
+
* Connection-time failures (auth, network, non-2xx) surface as the outer
|
|
24
|
+
* `Result.fail`. Once iteration begins, errors mid-stream surface as a
|
|
25
|
+
* terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable
|
|
26
|
+
* ending. The final successful event is {@link AiAssist.IAiStreamDone}.
|
|
27
|
+
*
|
|
28
|
+
* @param params - Request parameters including descriptor, API key, prompt, and optional tools
|
|
29
|
+
* @returns A streaming iterable of unified events, or a Result.fail
|
|
30
|
+
* @public
|
|
31
|
+
*/
|
|
32
|
+
export declare function callProviderCompletionStream(params: IProviderCompletionStreamParams): Promise<Result<AsyncIterable<IAiStreamEvent>>>;
|
|
33
|
+
//# sourceMappingURL=streamingClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streamingClient.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/streamingClient.ts"],"names":[],"mappings":"AAoBA;;;;;;;GAOG;AAEH,OAAO,EAAQ,MAAM,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAE,KAAK,cAAc,EAAgB,MAAM,SAAS,CAAC;AAE5D,OAAO,EAAE,KAAK,+BAA+B,EAAyB,MAAM,4BAA4B,CAAC;AAKzG,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACxE,YAAY,EAAE,+BAA+B,EAAE,MAAM,4BAA4B,CAAC;AAElF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,4BAA4B,CAChD,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CAgDhD"}
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.callProxiedCompletionStream = void 0;
|
|
23
|
+
exports.callProviderCompletionStream = callProviderCompletionStream;
|
|
24
|
+
/**
|
|
25
|
+
* Streaming chat completion client. Public façade over the per-format
|
|
26
|
+
* adapters under `streamingAdapters/`: provider dispatch and pre-flight
|
|
27
|
+
* validation live here; format-specific request/translation logic and the
|
|
28
|
+
* typed event-payload validators live with each adapter.
|
|
29
|
+
*
|
|
30
|
+
* @packageDocumentation
|
|
31
|
+
*/
|
|
32
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
33
|
+
const model_1 = require("./model");
|
|
34
|
+
const anthropic_1 = require("./streamingAdapters/anthropic");
|
|
35
|
+
const gemini_1 = require("./streamingAdapters/gemini");
|
|
36
|
+
const openaiChat_1 = require("./streamingAdapters/openaiChat");
|
|
37
|
+
const openaiResponses_1 = require("./streamingAdapters/openaiResponses");
|
|
38
|
+
var proxy_1 = require("./streamingAdapters/proxy");
|
|
39
|
+
Object.defineProperty(exports, "callProxiedCompletionStream", { enumerable: true, get: function () { return proxy_1.callProxiedCompletionStream; } });
|
|
40
|
+
/**
|
|
41
|
+
* Calls the appropriate streaming chat completion API for a given provider.
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`
|
|
45
|
+
* and the call isn't being routed through a proxy, this returns
|
|
46
|
+
* `Result.fail` before fetch is invoked. Callers should route through
|
|
47
|
+
* {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.
|
|
48
|
+
*
|
|
49
|
+
* Connection-time failures (auth, network, non-2xx) surface as the outer
|
|
50
|
+
* `Result.fail`. Once iteration begins, errors mid-stream surface as a
|
|
51
|
+
* terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable
|
|
52
|
+
* ending. The final successful event is {@link AiAssist.IAiStreamDone}.
|
|
53
|
+
*
|
|
54
|
+
* @param params - Request parameters including descriptor, API key, prompt, and optional tools
|
|
55
|
+
* @returns A streaming iterable of unified events, or a Result.fail
|
|
56
|
+
* @public
|
|
57
|
+
*/
|
|
58
|
+
async function callProviderCompletionStream(params) {
|
|
59
|
+
const { descriptor, apiKey, prompt, messagesBefore, temperature = 0.7, modelOverride, logger, tools, signal } = params;
|
|
60
|
+
if (!descriptor.baseUrl) {
|
|
61
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}" has no API endpoint configured`);
|
|
62
|
+
}
|
|
63
|
+
if (descriptor.streamingCorsRestricted) {
|
|
64
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}" requires a proxy for streaming; none is configured`);
|
|
65
|
+
}
|
|
66
|
+
if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {
|
|
67
|
+
return (0, ts_utils_1.fail)(`provider "${descriptor.id}" does not accept image input`);
|
|
68
|
+
}
|
|
69
|
+
const hasTools = tools !== undefined && tools.length > 0;
|
|
70
|
+
const modelContext = hasTools ? 'tools' : undefined;
|
|
71
|
+
const config = {
|
|
72
|
+
baseUrl: descriptor.baseUrl,
|
|
73
|
+
apiKey,
|
|
74
|
+
model: (0, model_1.resolveModel)(modelOverride !== null && modelOverride !== void 0 ? modelOverride : descriptor.defaultModel, modelContext)
|
|
75
|
+
};
|
|
76
|
+
switch (descriptor.apiFormat) {
|
|
77
|
+
case 'openai':
|
|
78
|
+
if (hasTools) {
|
|
79
|
+
return (0, openaiResponses_1.callOpenAiResponsesStream)(config, prompt, tools, messagesBefore, temperature, logger, signal);
|
|
80
|
+
}
|
|
81
|
+
return (0, openaiChat_1.callOpenAiChatStream)(config, prompt, messagesBefore, temperature, logger, signal);
|
|
82
|
+
case 'anthropic':
|
|
83
|
+
return (0, anthropic_1.callAnthropicStream)(config, prompt, messagesBefore, temperature, tools, logger, signal);
|
|
84
|
+
case 'gemini':
|
|
85
|
+
return (0, gemini_1.callGeminiStream)(config, prompt, messagesBefore, temperature, tools, logger, signal);
|
|
86
|
+
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
87
|
+
default: {
|
|
88
|
+
const _exhaustive = descriptor.apiFormat;
|
|
89
|
+
return (0, ts_utils_1.fail)(`unsupported API format: ${String(_exhaustive)}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=streamingClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streamingClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/streamingClient.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;;;AAyCZ,oEAkDC;AAzFD;;;;;;;GAOG;AAEH,4CAA6C;AAE7C,mCAA4D;AAC5D,6DAAoE;AAEpE,uDAA8D;AAC9D,+DAAsE;AACtE,yEAAgF;AAEhF,mDAAwE;AAA/D,oHAAA,2BAA2B,OAAA;AAGpC;;;;;;;;;;;;;;;;;GAiBG;AACI,KAAK,UAAU,4BAA4B,CAChD,MAAuC;IAEvC,MAAM,EACJ,UAAU,EACV,MAAM,EACN,MAAM,EACN,cAAc,EACd,WAAW,GAAG,GAAG,EACjB,aAAa,EACb,MAAM,EACN,KAAK,EACL,MAAM,EACP,GAAG,MAAM,CAAC;IAEX,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;QACxB,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,kCAAkC,CAAC,CAAC;IAC5E,CAAC;IACD,IAAI,UAAU,CAAC,uBAAuB,EAAE,CAAC;QACvC,OAAO,IAAA,eAAI,EAAC,aAAa,UAAU,CAAC,EAAE,sDAAsD,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AC,CAAC;YACR,MAAM,WAAW,GAAU,UAAU,CAAC,SAAS,CAAC;YAChD,OAAO,IAAA,eAAI,EAAC,2BAA2B,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;AACH,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 chat completion client. Public façade over the per-format\n * adapters under `streamingAdapters/`: provider dispatch and pre-flight\n * validation live here; format-specific request/translation logic and the\n * typed event-payload validators live with each adapter.\n *\n * @packageDocumentation\n */\n\nimport { fail, Result } from '@fgv/ts-utils';\n\nimport { type IAiStreamEvent, resolveModel } from './model';\nimport { callAnthropicStream } from './streamingAdapters/anthropic';\nimport { type IProviderCompletionStreamParams, type IStreamApiConfig } from './streamingAdapters/common';\nimport { callGeminiStream } from './streamingAdapters/gemini';\nimport { callOpenAiChatStream } from './streamingAdapters/openaiChat';\nimport { callOpenAiResponsesStream } from './streamingAdapters/openaiResponses';\n\nexport { callProxiedCompletionStream } from './streamingAdapters/proxy';\nexport type { IProviderCompletionStreamParams } from './streamingAdapters/common';\n\n/**\n * Calls the appropriate streaming chat completion API for a given provider.\n *\n * @remarks\n * Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`\n * and the call isn't being routed through a proxy, this returns\n * `Result.fail` before fetch is invoked. Callers should route through\n * {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.\n *\n * Connection-time failures (auth, network, non-2xx) surface as the outer\n * `Result.fail`. Once iteration begins, errors mid-stream surface as a\n * terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable\n * ending. The final successful event is {@link AiAssist.IAiStreamDone}.\n *\n * @param params - Request parameters including descriptor, API key, prompt, and optional tools\n * @returns A streaming iterable of unified events, or a Result.fail\n * @public\n */\nexport async function callProviderCompletionStream(\n params: IProviderCompletionStreamParams\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const {\n descriptor,\n apiKey,\n prompt,\n messagesBefore,\n temperature = 0.7,\n modelOverride,\n logger,\n tools,\n signal\n } = params;\n\n if (!descriptor.baseUrl) {\n return fail(`provider \"${descriptor.id}\" has no API endpoint configured`);\n }\n if (descriptor.streamingCorsRestricted) {\n return fail(`provider \"${descriptor.id}\" requires a proxy for streaming; none is configured`);\n }\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const hasTools = tools !== undefined && tools.length > 0;\n const modelContext = hasTools ? 'tools' : undefined;\n\n const config: IStreamApiConfig = {\n baseUrl: descriptor.baseUrl,\n apiKey,\n model: resolveModel(modelOverride ?? descriptor.defaultModel, modelContext)\n };\n\n switch (descriptor.apiFormat) {\n case 'openai':\n if (hasTools) {\n return callOpenAiResponsesStream(config, prompt, tools, messagesBefore, temperature, logger, signal);\n }\n return callOpenAiChatStream(config, prompt, messagesBefore, temperature, logger, signal);\n case 'anthropic':\n return callAnthropicStream(config, prompt, messagesBefore, temperature, tools, logger, signal);\n case 'gemini':\n return callGeminiStream(config, prompt, messagesBefore, temperature, tools, logger, signal);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = descriptor.apiFormat;\n return fail(`unsupported API format: ${String(_exhaustive)}`);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toolFormats.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AAEH,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EAEvB,MAAM,SAAS,CAAC;AAMjB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,qBAAqB,EACjC,aAAa,CAAC,EAAE,aAAa,CAAC,iBAAiB,CAAC,EAChD,YAAY,CAAC,EAAE,aAAa,CAAC,kBAAkB,CAAC,GAC/C,aAAa,CAAC,kBAAkB,CAAC,CAcnC;AA+BD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,CAYvG;AA6BD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,CAYpG;AAMD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,CAiBjG"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toolFormats.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;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E,MAAM,CAAC,WAAW,CAAC,EAAgB,CAAC,CAAC;YAC3D,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,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 * Provider-specific tool format translation and tool resolution logic.\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport {\n type AiServerToolConfig,\n type IAiProviderDescriptor,\n type IAiToolEnablement,\n type IAiWebSearchToolConfig\n} from './model';\n\n// ============================================================================\n// Tool resolution\n// ============================================================================\n\n/**\n * Resolves the effective tools for a completion call.\n *\n * - If per-call tools are provided, they override settings-level tools entirely.\n * - Otherwise, settings-level enabled tools are used.\n * - Only tools supported by the provider are included.\n * - Returns an empty array if no tools are enabled (= no tools sent).\n *\n * @param descriptor - The provider descriptor (used to filter by supported tools)\n * @param settingsTools - Tool enablement from provider settings (optional)\n * @param perCallTools - Per-call tool override (optional)\n * @returns The resolved list of tool configs to include in the request\n * @public\n */\nexport function resolveEffectiveTools(\n descriptor: IAiProviderDescriptor,\n settingsTools?: ReadonlyArray<IAiToolEnablement>,\n perCallTools?: ReadonlyArray<AiServerToolConfig>\n): ReadonlyArray<AiServerToolConfig> {\n const supported = new Set(descriptor.supportedTools);\n\n if (perCallTools !== undefined) {\n return perCallTools.filter((t) => supported.has(t.type));\n }\n\n if (settingsTools === undefined) {\n return [];\n }\n\n return settingsTools\n .filter((e) => e.enabled && supported.has(e.type))\n .map((e): AiServerToolConfig => e.config ?? { type: e.type });\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction webSearchToResponsesApi(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = { type: 'web_search' };\n\n if (config.allowedDomains || config.blockedDomains) {\n const filters: Record<string, unknown> = {};\n if (config.allowedDomains) {\n filters.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n filters.excluded_domains = [...config.blockedDomains];\n }\n tool.filters = filters;\n }\n\n if (config.enableImageUnderstanding) {\n tool.enable_image_understanding = true;\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats tool configs for the xAI/OpenAI Responses API.\n * @param tools - The resolved tool configs\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toResponsesApiTools(tools: ReadonlyArray<AiServerToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToResponsesApi(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t.type;\n return { type: String(_exhaustive) } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Anthropic Messages API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the Anthropic Messages API.\n * @internal\n */\nfunction webSearchToAnthropic(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = {\n type: 'web_search_20250305',\n name: 'web_search'\n };\n\n if (config.maxUses !== undefined) {\n tool.max_uses = config.maxUses;\n }\n if (config.allowedDomains) {\n tool.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n tool.blocked_domains = [...config.blockedDomains];\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats tool configs for the Anthropic Messages API.\n * @param tools - The resolved tool configs\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toAnthropicTools(tools: ReadonlyArray<AiServerToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToAnthropic(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t.type;\n return { type: String(_exhaustive) } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Gemini generateContent API format\n// ============================================================================\n\n/**\n * Formats tool configs for the Gemini generateContent API.\n * Gemini uses `google_search` for search grounding — no per-tool config options.\n * @param tools - The resolved tool configs\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toGeminiTools(tools: ReadonlyArray<AiServerToolConfig>): ReadonlyArray<JsonObject> {\n const result: JsonObject[] = [];\n\n for (const t of tools) {\n switch (t.type) {\n case 'web_search':\n result.push({ google_search: {} } as JsonObject);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t.type;\n result.push({ type: String(_exhaustive) } as JsonObject);\n }\n }\n }\n\n return result;\n}\n"]}
|