@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
|
@@ -30,41 +30,76 @@
|
|
|
30
30
|
* @packageDocumentation
|
|
31
31
|
*/
|
|
32
32
|
import { isJsonObject } from '@fgv/ts-json-base';
|
|
33
|
-
import { fail, succeed, Validators } from '@fgv/ts-utils';
|
|
33
|
+
import { fail, mapResults, succeed, Validators } from '@fgv/ts-utils';
|
|
34
34
|
import { resolveModel } from './model';
|
|
35
|
+
import { buildAnthropicMessages, buildGeminiContents, buildMessages, buildOpenAiChatUserContent, buildOpenAiResponsesUserContent } from './chatRequestBuilders';
|
|
36
|
+
import { DEFAULT_MODEL_CAPABILITY_CONFIG, resolveImageCapability, supportsImageGeneration } from './registry';
|
|
35
37
|
import { toAnthropicTools, toGeminiTools, toResponsesApiTools } from './toolFormats';
|
|
36
38
|
// ============================================================================
|
|
37
39
|
// Shared helpers
|
|
38
40
|
// ============================================================================
|
|
39
41
|
/**
|
|
40
|
-
*
|
|
42
|
+
* Makes an HTTP request and returns the parsed JSON, or a failure.
|
|
41
43
|
* @internal
|
|
42
44
|
*/
|
|
43
|
-
function
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
45
|
+
async function fetchJson(url, headers, body, logger, signal) {
|
|
46
|
+
/* c8 ignore next 1 - optional logger */
|
|
47
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API request: POST ${url}`);
|
|
48
|
+
let response;
|
|
49
|
+
try {
|
|
50
|
+
response = await fetch(url, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
|
|
53
|
+
body: JSON.stringify(body),
|
|
54
|
+
signal
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
59
|
+
/* c8 ignore next 1 - optional logger */
|
|
60
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API request failed: ${detail}`);
|
|
61
|
+
return fail(`AI API request failed: ${detail}`);
|
|
62
|
+
}
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
const errorText = await response.text().catch(() => 'unknown error');
|
|
65
|
+
/* c8 ignore next 1 - optional logger */
|
|
66
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API returned ${response.status}: ${errorText}`);
|
|
67
|
+
return fail(`AI API returned ${response.status}: ${errorText}`);
|
|
52
68
|
}
|
|
53
|
-
|
|
69
|
+
/* c8 ignore next 1 - optional logger */
|
|
70
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API response: ${response.status}`);
|
|
71
|
+
let json;
|
|
72
|
+
try {
|
|
73
|
+
json = await response.json();
|
|
74
|
+
}
|
|
75
|
+
catch (_a) {
|
|
76
|
+
/* c8 ignore next 1 - optional logger */
|
|
77
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned invalid JSON response');
|
|
78
|
+
return fail('AI API returned invalid JSON response');
|
|
79
|
+
}
|
|
80
|
+
if (!isJsonObject(json)) {
|
|
81
|
+
/* c8 ignore next 1 - optional logger */
|
|
82
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned non-object JSON response');
|
|
83
|
+
return fail('AI API returned non-object JSON response');
|
|
84
|
+
}
|
|
85
|
+
return succeed(json);
|
|
54
86
|
}
|
|
55
87
|
/**
|
|
56
|
-
* Makes
|
|
88
|
+
* Makes a multipart/form-data POST request and returns the parsed JSON, or a
|
|
89
|
+
* failure. The Content-Type header (with boundary) is set automatically by
|
|
90
|
+
* `fetch` from the `FormData` body — callers must NOT pass it explicitly.
|
|
57
91
|
* @internal
|
|
58
92
|
*/
|
|
59
|
-
async function
|
|
93
|
+
async function fetchMultipart(url, headers, body, logger, signal) {
|
|
60
94
|
/* c8 ignore next 1 - optional logger */
|
|
61
|
-
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API request: POST ${url}`);
|
|
95
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API request: POST ${url} (multipart)`);
|
|
62
96
|
let response;
|
|
63
97
|
try {
|
|
64
98
|
response = await fetch(url, {
|
|
65
99
|
method: 'POST',
|
|
66
|
-
headers
|
|
67
|
-
body
|
|
100
|
+
headers,
|
|
101
|
+
body,
|
|
102
|
+
signal
|
|
68
103
|
});
|
|
69
104
|
}
|
|
70
105
|
catch (err) {
|
|
@@ -97,6 +132,95 @@ async function fetchJson(url, headers, body, logger) {
|
|
|
97
132
|
}
|
|
98
133
|
return succeed(json);
|
|
99
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Decodes a base64-encoded image attachment into a `Blob` suitable for use as
|
|
137
|
+
* a multipart file field. On Node hands the `Buffer` straight to `Blob`
|
|
138
|
+
* (Buffer extends Uint8Array) to skip an intermediate copy; falls back to
|
|
139
|
+
* `atob` in browsers. Inputs come from `FileReader` or prior provider
|
|
140
|
+
* responses, which are trusted to be valid. Note that Node's
|
|
141
|
+
* `Buffer.from(..., 'base64')` silently strips invalid characters rather
|
|
142
|
+
* than throwing, so failures are only observable in the browser path.
|
|
143
|
+
* @internal
|
|
144
|
+
*/
|
|
145
|
+
function attachmentToBlob(attachment) {
|
|
146
|
+
if (typeof Buffer !== 'undefined') {
|
|
147
|
+
return succeed(new Blob([Buffer.from(attachment.base64, 'base64')], { type: attachment.mimeType }));
|
|
148
|
+
}
|
|
149
|
+
/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */
|
|
150
|
+
try {
|
|
151
|
+
const binary = atob(attachment.base64);
|
|
152
|
+
const bytes = new Uint8Array(binary.length);
|
|
153
|
+
for (let i = 0; i < binary.length; i++) {
|
|
154
|
+
bytes[i] = binary.charCodeAt(i);
|
|
155
|
+
}
|
|
156
|
+
return succeed(new Blob([bytes], { type: attachment.mimeType }));
|
|
157
|
+
}
|
|
158
|
+
catch (e) {
|
|
159
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
160
|
+
return fail(`Invalid base64: ${message}`);
|
|
161
|
+
}
|
|
162
|
+
/* c8 ignore stop */
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Maps a MIME type to a sensible file extension for multipart filenames.
|
|
166
|
+
* @internal
|
|
167
|
+
*/
|
|
168
|
+
function extensionForMimeType(mimeType) {
|
|
169
|
+
switch (mimeType) {
|
|
170
|
+
case 'image/png':
|
|
171
|
+
return 'png';
|
|
172
|
+
case 'image/jpeg':
|
|
173
|
+
case 'image/jpg':
|
|
174
|
+
return 'jpg';
|
|
175
|
+
case 'image/webp':
|
|
176
|
+
return 'webp';
|
|
177
|
+
case 'image/gif':
|
|
178
|
+
return 'gif';
|
|
179
|
+
default:
|
|
180
|
+
return 'bin';
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Makes an HTTP GET request and returns the parsed JSON, or a failure.
|
|
185
|
+
* @internal
|
|
186
|
+
*/
|
|
187
|
+
async function fetchGetJson(url, headers, logger, signal) {
|
|
188
|
+
/* c8 ignore next 1 - optional logger */
|
|
189
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API request: GET ${url}`);
|
|
190
|
+
let response;
|
|
191
|
+
try {
|
|
192
|
+
response = await fetch(url, { method: 'GET', headers, signal });
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
196
|
+
/* c8 ignore next 1 - optional logger */
|
|
197
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API request failed: ${detail}`);
|
|
198
|
+
return fail(`AI API request failed: ${detail}`);
|
|
199
|
+
}
|
|
200
|
+
if (!response.ok) {
|
|
201
|
+
const errorText = await response.text().catch(() => 'unknown error');
|
|
202
|
+
/* c8 ignore next 1 - optional logger */
|
|
203
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API returned ${response.status}: ${errorText}`);
|
|
204
|
+
return fail(`AI API returned ${response.status}: ${errorText}`);
|
|
205
|
+
}
|
|
206
|
+
/* c8 ignore next 1 - optional logger */
|
|
207
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API response: ${response.status}`);
|
|
208
|
+
let json;
|
|
209
|
+
try {
|
|
210
|
+
json = await response.json();
|
|
211
|
+
}
|
|
212
|
+
catch (_a) {
|
|
213
|
+
/* c8 ignore next 1 - optional logger */
|
|
214
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned invalid JSON response');
|
|
215
|
+
return fail('AI API returned invalid JSON response');
|
|
216
|
+
}
|
|
217
|
+
if (!isJsonObject(json)) {
|
|
218
|
+
/* c8 ignore next 1 - optional logger */
|
|
219
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned non-object JSON response');
|
|
220
|
+
return fail('AI API returned non-object JSON response');
|
|
221
|
+
}
|
|
222
|
+
return succeed(json);
|
|
223
|
+
}
|
|
100
224
|
const openAiMessage = Validators.object({
|
|
101
225
|
content: Validators.string
|
|
102
226
|
});
|
|
@@ -149,16 +273,18 @@ const geminiResponse = Validators.object({
|
|
|
149
273
|
* Works for xAI Grok, OpenAI, Groq, and Mistral.
|
|
150
274
|
* @internal
|
|
151
275
|
*/
|
|
152
|
-
async function callOpenAiCompletion(config, prompt, additionalMessages, temperature = 0.7, logger) {
|
|
276
|
+
async function callOpenAiCompletion(config, prompt, additionalMessages, temperature = 0.7, logger, signal) {
|
|
153
277
|
const url = `${config.baseUrl}/chat/completions`;
|
|
154
|
-
const messages = buildMessages(prompt,
|
|
278
|
+
const messages = buildMessages(prompt.system, buildOpenAiChatUserContent(prompt), {
|
|
279
|
+
tail: additionalMessages
|
|
280
|
+
});
|
|
155
281
|
const body = { model: config.model, messages, temperature };
|
|
156
282
|
const headers = {
|
|
157
283
|
Authorization: `Bearer ${config.apiKey}`
|
|
158
284
|
};
|
|
159
285
|
/* c8 ignore next 1 - optional logger */
|
|
160
286
|
logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI completion: model=${config.model}`);
|
|
161
|
-
const jsonResult = await fetchJson(url, headers, body, logger);
|
|
287
|
+
const jsonResult = await fetchJson(url, headers, body, logger, signal);
|
|
162
288
|
if (jsonResult.isFailure()) {
|
|
163
289
|
return fail(jsonResult.message);
|
|
164
290
|
}
|
|
@@ -197,9 +323,11 @@ function extractResponsesApiText(output) {
|
|
|
197
323
|
* Used when tools are configured for an openai-format provider.
|
|
198
324
|
* @internal
|
|
199
325
|
*/
|
|
200
|
-
async function callOpenAiResponsesCompletion(config, prompt, tools, additionalMessages, temperature = 0.7, logger) {
|
|
326
|
+
async function callOpenAiResponsesCompletion(config, prompt, tools, additionalMessages, temperature = 0.7, logger, signal) {
|
|
201
327
|
const url = `${config.baseUrl}/responses`;
|
|
202
|
-
const input = buildMessages(prompt,
|
|
328
|
+
const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {
|
|
329
|
+
tail: additionalMessages
|
|
330
|
+
});
|
|
203
331
|
const body = {
|
|
204
332
|
model: config.model,
|
|
205
333
|
input,
|
|
@@ -211,7 +339,7 @@ async function callOpenAiResponsesCompletion(config, prompt, tools, additionalMe
|
|
|
211
339
|
};
|
|
212
340
|
/* c8 ignore next 1 - optional logger */
|
|
213
341
|
logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI Responses API: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);
|
|
214
|
-
const jsonResult = await fetchJson(url, headers, body, logger);
|
|
342
|
+
const jsonResult = await fetchJson(url, headers, body, logger, signal);
|
|
215
343
|
if (jsonResult.isFailure()) {
|
|
216
344
|
return fail(jsonResult.message);
|
|
217
345
|
}
|
|
@@ -256,18 +384,10 @@ function extractAnthropicText(content) {
|
|
|
256
384
|
* mixed content block responses.
|
|
257
385
|
* @internal
|
|
258
386
|
*/
|
|
259
|
-
async function callAnthropicCompletion(config, prompt, additionalMessages, temperature = 0.7, logger, tools) {
|
|
387
|
+
async function callAnthropicCompletion(config, prompt, additionalMessages, temperature = 0.7, logger, tools, signal) {
|
|
260
388
|
const url = `${config.baseUrl}/messages`;
|
|
261
389
|
// Anthropic uses system as a top-level field, not in messages
|
|
262
|
-
const messages =
|
|
263
|
-
if (additionalMessages) {
|
|
264
|
-
for (const msg of additionalMessages) {
|
|
265
|
-
// Anthropic doesn't have a system role in messages
|
|
266
|
-
if (msg.role !== 'system') {
|
|
267
|
-
messages.push({ role: msg.role, content: msg.content });
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
390
|
+
const messages = buildAnthropicMessages(prompt, { tail: additionalMessages });
|
|
271
391
|
const body = {
|
|
272
392
|
model: config.model,
|
|
273
393
|
system: prompt.system,
|
|
@@ -289,7 +409,7 @@ async function callAnthropicCompletion(config, prompt, additionalMessages, tempe
|
|
|
289
409
|
'anthropic-version': '2023-06-01',
|
|
290
410
|
'anthropic-dangerous-direct-browser-access': 'true'
|
|
291
411
|
};
|
|
292
|
-
const jsonResult = await fetchJson(url, headers, body, logger);
|
|
412
|
+
const jsonResult = await fetchJson(url, headers, body, logger, signal);
|
|
293
413
|
if (jsonResult.isFailure()) {
|
|
294
414
|
return fail(jsonResult.message);
|
|
295
415
|
}
|
|
@@ -324,22 +444,10 @@ async function callAnthropicCompletion(config, prompt, additionalMessages, tempe
|
|
|
324
444
|
* When tools are configured, includes Google Search grounding.
|
|
325
445
|
* @internal
|
|
326
446
|
*/
|
|
327
|
-
async function callGeminiCompletion(config, prompt, additionalMessages, temperature = 0.7, logger, tools) {
|
|
447
|
+
async function callGeminiCompletion(config, prompt, additionalMessages, temperature = 0.7, logger, tools, signal) {
|
|
328
448
|
const url = `${config.baseUrl}/models/${config.model}:generateContent`;
|
|
329
449
|
// Gemini uses 'contents' with 'parts', and 'model' role instead of 'assistant'
|
|
330
|
-
const contents =
|
|
331
|
-
{ role: 'user', parts: [{ text: prompt.user }] }
|
|
332
|
-
];
|
|
333
|
-
if (additionalMessages) {
|
|
334
|
-
for (const msg of additionalMessages) {
|
|
335
|
-
if (msg.role !== 'system') {
|
|
336
|
-
contents.push({
|
|
337
|
-
role: msg.role === 'assistant' ? 'model' : msg.role,
|
|
338
|
-
parts: [{ text: msg.content }]
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
450
|
+
const contents = buildGeminiContents(prompt, { tail: additionalMessages });
|
|
343
451
|
const body = {
|
|
344
452
|
systemInstruction: { parts: [{ text: prompt.system }] },
|
|
345
453
|
contents,
|
|
@@ -357,7 +465,7 @@ async function callGeminiCompletion(config, prompt, additionalMessages, temperat
|
|
|
357
465
|
const headers = {
|
|
358
466
|
'x-goog-api-key': config.apiKey
|
|
359
467
|
};
|
|
360
|
-
const jsonResult = await fetchJson(url, headers, body, logger);
|
|
468
|
+
const jsonResult = await fetchJson(url, headers, body, logger, signal);
|
|
361
469
|
if (jsonResult.isFailure()) {
|
|
362
470
|
return fail(jsonResult.message);
|
|
363
471
|
}
|
|
@@ -393,10 +501,13 @@ async function callGeminiCompletion(config, prompt, additionalMessages, temperat
|
|
|
393
501
|
* @public
|
|
394
502
|
*/
|
|
395
503
|
export async function callProviderCompletion(params) {
|
|
396
|
-
const { descriptor, apiKey, prompt, additionalMessages, temperature = 0.7, modelOverride, logger, tools } = params;
|
|
504
|
+
const { descriptor, apiKey, prompt, additionalMessages, temperature = 0.7, modelOverride, logger, tools, signal } = params;
|
|
397
505
|
if (!descriptor.baseUrl) {
|
|
398
506
|
return fail(`provider "${descriptor.id}" has no API endpoint configured`);
|
|
399
507
|
}
|
|
508
|
+
if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {
|
|
509
|
+
return fail(`provider "${descriptor.id}" does not accept image input`);
|
|
510
|
+
}
|
|
400
511
|
const hasTools = tools !== undefined && tools.length > 0;
|
|
401
512
|
const modelContext = hasTools ? 'tools' : undefined;
|
|
402
513
|
const config = {
|
|
@@ -414,13 +525,13 @@ export async function callProviderCompletion(params) {
|
|
|
414
525
|
switch (descriptor.apiFormat) {
|
|
415
526
|
case 'openai':
|
|
416
527
|
if (hasTools) {
|
|
417
|
-
return callOpenAiResponsesCompletion(config, prompt, tools, additionalMessages, temperature, logger);
|
|
528
|
+
return callOpenAiResponsesCompletion(config, prompt, tools, additionalMessages, temperature, logger, signal);
|
|
418
529
|
}
|
|
419
|
-
return callOpenAiCompletion(config, prompt, additionalMessages, temperature, logger);
|
|
530
|
+
return callOpenAiCompletion(config, prompt, additionalMessages, temperature, logger, signal);
|
|
420
531
|
case 'anthropic':
|
|
421
|
-
return callAnthropicCompletion(config, prompt, additionalMessages, temperature, logger, tools);
|
|
532
|
+
return callAnthropicCompletion(config, prompt, additionalMessages, temperature, logger, tools, signal);
|
|
422
533
|
case 'gemini':
|
|
423
|
-
return callGeminiCompletion(config, prompt, additionalMessages, temperature, logger, tools);
|
|
534
|
+
return callGeminiCompletion(config, prompt, additionalMessages, temperature, logger, tools, signal);
|
|
424
535
|
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
425
536
|
default: {
|
|
426
537
|
const _exhaustive = descriptor.apiFormat;
|
|
@@ -428,6 +539,576 @@ export async function callProviderCompletion(params) {
|
|
|
428
539
|
}
|
|
429
540
|
}
|
|
430
541
|
}
|
|
542
|
+
const openAiImageItem = Validators.object({
|
|
543
|
+
b64_json: Validators.string,
|
|
544
|
+
revised_prompt: Validators.string.optional()
|
|
545
|
+
});
|
|
546
|
+
const openAiImageResponse = Validators.object({
|
|
547
|
+
data: Validators.arrayOf(openAiImageItem).withConstraint((arr) => arr.length > 0)
|
|
548
|
+
});
|
|
549
|
+
const imagenPrediction = Validators.object({
|
|
550
|
+
bytesBase64Encoded: Validators.string,
|
|
551
|
+
mimeType: Validators.string.optional()
|
|
552
|
+
});
|
|
553
|
+
const imagenResponse = Validators.object({
|
|
554
|
+
predictions: Validators.arrayOf(imagenPrediction).withConstraint((arr) => arr.length > 0)
|
|
555
|
+
});
|
|
556
|
+
const geminiImageInlineData = Validators.object({
|
|
557
|
+
mimeType: Validators.string,
|
|
558
|
+
data: Validators.string
|
|
559
|
+
});
|
|
560
|
+
const geminiImageOutPart = Validators.object({
|
|
561
|
+
text: Validators.string.optional(),
|
|
562
|
+
inlineData: geminiImageInlineData.optional()
|
|
563
|
+
});
|
|
564
|
+
const geminiImageOutContent = Validators.object({
|
|
565
|
+
parts: Validators.arrayOf(geminiImageOutPart).withConstraint((arr) => arr.length > 0)
|
|
566
|
+
});
|
|
567
|
+
const geminiImageOutCandidate = Validators.object({
|
|
568
|
+
content: geminiImageOutContent,
|
|
569
|
+
finishReason: Validators.string.optional()
|
|
570
|
+
});
|
|
571
|
+
const geminiImageOutResponse = Validators.object({
|
|
572
|
+
candidates: Validators.arrayOf(geminiImageOutCandidate).withConstraint((arr) => arr.length > 0)
|
|
573
|
+
});
|
|
574
|
+
// ---- Proxied image generation response ----
|
|
575
|
+
const proxiedGeneratedImage = Validators.object({
|
|
576
|
+
mimeType: Validators.string,
|
|
577
|
+
base64: Validators.string,
|
|
578
|
+
revisedPrompt: Validators.string.optional()
|
|
579
|
+
});
|
|
580
|
+
const proxiedImageGenerationResponse = Validators.object({
|
|
581
|
+
images: Validators.arrayOf(proxiedGeneratedImage).withConstraint((arr) => arr.length > 0)
|
|
582
|
+
});
|
|
583
|
+
const proxiedListModelsEntry = Validators.object({
|
|
584
|
+
id: Validators.string,
|
|
585
|
+
capabilities: Validators.arrayOf(Validators.enumeratedValue(['chat', 'tools', 'vision', 'image-generation'])),
|
|
586
|
+
displayName: Validators.string.optional()
|
|
587
|
+
});
|
|
588
|
+
const proxiedListModelsResponse = Validators.object({
|
|
589
|
+
models: Validators.arrayOf(proxiedListModelsEntry)
|
|
590
|
+
});
|
|
591
|
+
// ============================================================================
|
|
592
|
+
// Image generation — adapters
|
|
593
|
+
// ============================================================================
|
|
594
|
+
/**
|
|
595
|
+
* Calls the OpenAI Images API. Used for both `openai-images` and `xai-images`
|
|
596
|
+
* formats — the request shape is the same; the only difference is whether the
|
|
597
|
+
* `size` field is honored (OpenAI: yes, xAI: ignored at the provider).
|
|
598
|
+
*
|
|
599
|
+
* When `request.referenceImages` is non-empty, routes to `/images/edits`
|
|
600
|
+
* (multipart) instead of `/images/generations` (JSON). Per-model edit support
|
|
601
|
+
* is not validated here (e.g. dall-e-3 does not support edits) — the
|
|
602
|
+
* provider's 400 surfaces through the failure path.
|
|
603
|
+
*
|
|
604
|
+
* @internal
|
|
605
|
+
*/
|
|
606
|
+
async function callOpenAiImageGeneration(config, request, defaultMimeType, logger, signal) {
|
|
607
|
+
var _a, _b, _c;
|
|
608
|
+
const opts = (_a = request.options) !== null && _a !== void 0 ? _a : {};
|
|
609
|
+
const refs = (_b = request.referenceImages) !== null && _b !== void 0 ? _b : [];
|
|
610
|
+
const headers = {
|
|
611
|
+
Authorization: `Bearer ${config.apiKey}`
|
|
612
|
+
};
|
|
613
|
+
const n = (_c = opts.count) !== null && _c !== void 0 ? _c : 1;
|
|
614
|
+
const fetched = refs.length > 0
|
|
615
|
+
? await callOpenAiImagesEdits(config, request, headers, n, refs, logger, signal)
|
|
616
|
+
: await callOpenAiImagesGenerations(config, request, headers, n, logger, signal);
|
|
617
|
+
return fetched.onSuccess((json) => openAiImageResponse
|
|
618
|
+
.validate(json)
|
|
619
|
+
.withErrorFormat((msg) => `OpenAI images API response: ${msg}`)
|
|
620
|
+
.onSuccess((response) => succeed({
|
|
621
|
+
images: response.data.map((item) => (Object.assign({ mimeType: defaultMimeType, base64: item.b64_json }, (item.revised_prompt !== undefined ? { revisedPrompt: item.revised_prompt } : {}))))
|
|
622
|
+
})));
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Builds and posts the JSON `/images/generations` request (no refs).
|
|
626
|
+
* @internal
|
|
627
|
+
*/
|
|
628
|
+
function callOpenAiImagesGenerations(config, request, headers, n, logger, signal) {
|
|
629
|
+
var _a;
|
|
630
|
+
const opts = (_a = request.options) !== null && _a !== void 0 ? _a : {};
|
|
631
|
+
const body = {
|
|
632
|
+
model: config.model,
|
|
633
|
+
prompt: request.prompt,
|
|
634
|
+
n,
|
|
635
|
+
response_format: 'b64_json'
|
|
636
|
+
};
|
|
637
|
+
if (opts.size !== undefined) {
|
|
638
|
+
body.size = opts.size;
|
|
639
|
+
}
|
|
640
|
+
if (opts.quality !== undefined) {
|
|
641
|
+
body.quality = opts.quality;
|
|
642
|
+
}
|
|
643
|
+
if (opts.seed !== undefined) {
|
|
644
|
+
body.seed = opts.seed;
|
|
645
|
+
}
|
|
646
|
+
/* c8 ignore next 1 - optional logger */
|
|
647
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`Image generation: model=${config.model}, n=${n}`);
|
|
648
|
+
return fetchJson(`${config.baseUrl}/images/generations`, headers, body, logger, signal);
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Builds and posts the multipart `/images/edits` request (with refs).
|
|
652
|
+
* @internal
|
|
653
|
+
*/
|
|
654
|
+
async function callOpenAiImagesEdits(config, request, headers, n, refs, logger, signal) {
|
|
655
|
+
var _a;
|
|
656
|
+
const blobsResult = mapResults(refs.map((ref, i) => attachmentToBlob(ref).withErrorFormat((msg) => `reference image ${i}: ${msg}`)));
|
|
657
|
+
/* c8 ignore next 3 - decode failure unreachable via Node's Buffer.from (silently strips invalid input) */
|
|
658
|
+
if (blobsResult.isFailure()) {
|
|
659
|
+
return fail(blobsResult.message);
|
|
660
|
+
}
|
|
661
|
+
const opts = (_a = request.options) !== null && _a !== void 0 ? _a : {};
|
|
662
|
+
const form = new FormData();
|
|
663
|
+
form.append('model', config.model);
|
|
664
|
+
form.append('prompt', request.prompt);
|
|
665
|
+
form.append('n', String(n));
|
|
666
|
+
form.append('response_format', 'b64_json');
|
|
667
|
+
if (opts.size !== undefined) {
|
|
668
|
+
form.append('size', opts.size);
|
|
669
|
+
}
|
|
670
|
+
if (opts.quality !== undefined) {
|
|
671
|
+
form.append('quality', opts.quality);
|
|
672
|
+
}
|
|
673
|
+
if (opts.seed !== undefined) {
|
|
674
|
+
form.append('seed', String(opts.seed));
|
|
675
|
+
}
|
|
676
|
+
blobsResult.value.forEach((blob, i) => {
|
|
677
|
+
form.append('image[]', blob, `ref-${i}.${extensionForMimeType(refs[i].mimeType)}`);
|
|
678
|
+
});
|
|
679
|
+
/* c8 ignore next 1 - optional logger */
|
|
680
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`Image edit: model=${config.model}, n=${n}, refs=${refs.length}`);
|
|
681
|
+
return fetchMultipart(`${config.baseUrl}/images/edits`, headers, form, logger, signal);
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Calls Gemini's chat-style `:generateContent` endpoint for image output
|
|
685
|
+
* (Gemini 2.5 Flash Image / "Nano Banana"). Accepts reference images, which
|
|
686
|
+
* are passed as `inlineData` parts alongside the text prompt.
|
|
687
|
+
*
|
|
688
|
+
* @internal
|
|
689
|
+
*/
|
|
690
|
+
async function callGeminiImageOutGeneration(config, request, logger, signal) {
|
|
691
|
+
var _a;
|
|
692
|
+
const url = `${config.baseUrl}/models/${config.model}:generateContent`;
|
|
693
|
+
const refs = (_a = request.referenceImages) !== null && _a !== void 0 ? _a : [];
|
|
694
|
+
const parts = [{ text: request.prompt }];
|
|
695
|
+
for (const ref of refs) {
|
|
696
|
+
parts.push({ inlineData: { mimeType: ref.mimeType, data: ref.base64 } });
|
|
697
|
+
}
|
|
698
|
+
const body = {
|
|
699
|
+
contents: [{ role: 'user', parts }]
|
|
700
|
+
};
|
|
701
|
+
const headers = {
|
|
702
|
+
'x-goog-api-key': config.apiKey
|
|
703
|
+
};
|
|
704
|
+
/* c8 ignore next 1 - optional logger */
|
|
705
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`Gemini image-out: model=${config.model}, refs=${refs.length}`);
|
|
706
|
+
return (await fetchJson(url, headers, body, logger, signal)).onSuccess((json) => geminiImageOutResponse
|
|
707
|
+
.validate(json)
|
|
708
|
+
.withErrorFormat((msg) => `Gemini image API response: ${msg}`)
|
|
709
|
+
.onSuccess((response) => {
|
|
710
|
+
const images = [];
|
|
711
|
+
for (const candidate of response.candidates) {
|
|
712
|
+
for (const part of candidate.content.parts) {
|
|
713
|
+
if (part.inlineData) {
|
|
714
|
+
images.push({
|
|
715
|
+
mimeType: part.inlineData.mimeType,
|
|
716
|
+
base64: part.inlineData.data
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (images.length === 0) {
|
|
722
|
+
return fail('Gemini image API response: no image parts in response');
|
|
723
|
+
}
|
|
724
|
+
return succeed({ images });
|
|
725
|
+
}));
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Calls the Gemini Imagen `:predict` endpoint.
|
|
729
|
+
* @internal
|
|
730
|
+
*/
|
|
731
|
+
async function callImagenGeneration(config, request, logger, signal) {
|
|
732
|
+
var _a, _b, _c, _d;
|
|
733
|
+
const url = `${config.baseUrl}/models/${config.model}:predict`;
|
|
734
|
+
const opts = (_a = request.options) !== null && _a !== void 0 ? _a : {};
|
|
735
|
+
const parameters = {
|
|
736
|
+
sampleCount: (_b = opts.count) !== null && _b !== void 0 ? _b : 1
|
|
737
|
+
};
|
|
738
|
+
if (((_c = opts.imagen) === null || _c === void 0 ? void 0 : _c.aspectRatio) !== undefined) {
|
|
739
|
+
parameters.aspectRatio = opts.imagen.aspectRatio;
|
|
740
|
+
}
|
|
741
|
+
if (((_d = opts.imagen) === null || _d === void 0 ? void 0 : _d.negativePrompt) !== undefined) {
|
|
742
|
+
parameters.negativePrompt = opts.imagen.negativePrompt;
|
|
743
|
+
}
|
|
744
|
+
if (opts.seed !== undefined) {
|
|
745
|
+
parameters.seed = opts.seed;
|
|
746
|
+
}
|
|
747
|
+
const body = {
|
|
748
|
+
instances: [{ prompt: request.prompt }],
|
|
749
|
+
parameters
|
|
750
|
+
};
|
|
751
|
+
const headers = {
|
|
752
|
+
'x-goog-api-key': config.apiKey
|
|
753
|
+
};
|
|
754
|
+
/* c8 ignore next 1 - optional logger */
|
|
755
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`Imagen generation: model=${config.model}, n=${parameters.sampleCount}`);
|
|
756
|
+
const jsonResult = await fetchJson(url, headers, body, logger, signal);
|
|
757
|
+
if (jsonResult.isFailure()) {
|
|
758
|
+
return fail(jsonResult.message);
|
|
759
|
+
}
|
|
760
|
+
return imagenResponse
|
|
761
|
+
.validate(jsonResult.value)
|
|
762
|
+
.withErrorFormat((msg) => `Imagen API response: ${msg}`)
|
|
763
|
+
.onSuccess((response) => {
|
|
764
|
+
const images = response.predictions.map((p) => {
|
|
765
|
+
var _a;
|
|
766
|
+
return ({
|
|
767
|
+
mimeType: (_a = p.mimeType) !== null && _a !== void 0 ? _a : 'image/png',
|
|
768
|
+
base64: p.bytesBase64Encoded
|
|
769
|
+
});
|
|
770
|
+
});
|
|
771
|
+
return succeed({ images });
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
// ============================================================================
|
|
775
|
+
// Image generation — dispatcher
|
|
776
|
+
// ============================================================================
|
|
777
|
+
/**
|
|
778
|
+
* Calls the appropriate image-generation API for a given provider.
|
|
779
|
+
*
|
|
780
|
+
* Resolves a {@link IAiImageModelCapability} from
|
|
781
|
+
* {@link IAiProviderDescriptor.imageGeneration} for the requested model and
|
|
782
|
+
* routes by its `format`:
|
|
783
|
+
* - `'openai-images'` for OpenAI (DALL-E, gpt-image-1)
|
|
784
|
+
* - `'xai-images'` for xAI Grok image models
|
|
785
|
+
* - `'gemini-imagen'` for Google Imagen `:predict`
|
|
786
|
+
* - `'gemini-image-out'` for Gemini chat-style image output (Nano Banana)
|
|
787
|
+
*
|
|
788
|
+
* Image-model selection reuses the existing `'image'` {@link ModelSpecKey}.
|
|
789
|
+
* When `request.referenceImages` is non-empty, the call is rejected up front
|
|
790
|
+
* unless the resolved capability declares `acceptsImageReferenceInput`.
|
|
791
|
+
*
|
|
792
|
+
* @param params - Request parameters including descriptor, API key, and prompt
|
|
793
|
+
* @returns The generated images, or a failure
|
|
794
|
+
* @public
|
|
795
|
+
*/
|
|
796
|
+
export async function callProviderImageGeneration(params) {
|
|
797
|
+
var _a, _b;
|
|
798
|
+
const { descriptor, apiKey, params: request, modelOverride, logger, signal } = params;
|
|
799
|
+
if (!supportsImageGeneration(descriptor)) {
|
|
800
|
+
return fail(`provider "${descriptor.id}" does not support image generation`);
|
|
801
|
+
}
|
|
802
|
+
if (!descriptor.baseUrl) {
|
|
803
|
+
return fail(`provider "${descriptor.id}" has no API endpoint configured`);
|
|
804
|
+
}
|
|
805
|
+
const model = resolveModel(modelOverride !== null && modelOverride !== void 0 ? modelOverride : descriptor.defaultModel, 'image');
|
|
806
|
+
const capability = resolveImageCapability(descriptor, model);
|
|
807
|
+
if (capability === undefined) {
|
|
808
|
+
return fail(`provider "${descriptor.id}" does not support image generation for model "${model}"`);
|
|
809
|
+
}
|
|
810
|
+
if (((_b = (_a = request.referenceImages) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0 && !capability.acceptsImageReferenceInput) {
|
|
811
|
+
return fail(`model "${model}" does not support reference images`);
|
|
812
|
+
}
|
|
813
|
+
const config = {
|
|
814
|
+
baseUrl: descriptor.baseUrl,
|
|
815
|
+
apiKey,
|
|
816
|
+
model
|
|
817
|
+
};
|
|
818
|
+
/* c8 ignore next 6 - optional logger diagnostic output */
|
|
819
|
+
if (logger) {
|
|
820
|
+
logger.info(`AI image generation: provider=${descriptor.id}, format=${capability.format}, ` +
|
|
821
|
+
`model=${config.model}`);
|
|
822
|
+
}
|
|
823
|
+
switch (capability.format) {
|
|
824
|
+
case 'openai-images':
|
|
825
|
+
return callOpenAiImageGeneration(config, request, 'image/png', logger, signal);
|
|
826
|
+
case 'xai-images':
|
|
827
|
+
return callOpenAiImageGeneration(config, request, 'image/jpeg', logger, signal);
|
|
828
|
+
case 'gemini-imagen':
|
|
829
|
+
return callImagenGeneration(config, request, logger, signal);
|
|
830
|
+
case 'gemini-image-out':
|
|
831
|
+
return callGeminiImageOutGeneration(config, request, logger, signal);
|
|
832
|
+
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
833
|
+
default: {
|
|
834
|
+
const _exhaustive = capability.format;
|
|
835
|
+
return fail(`unsupported image API format: ${String(_exhaustive)}`);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
const openAiListEntry = Validators.object({
|
|
840
|
+
id: Validators.string
|
|
841
|
+
});
|
|
842
|
+
const openAiListResponse = Validators.object({
|
|
843
|
+
data: Validators.arrayOf(openAiListEntry)
|
|
844
|
+
});
|
|
845
|
+
const anthropicListEntry = Validators.object({
|
|
846
|
+
id: Validators.string,
|
|
847
|
+
display_name: Validators.string.optional()
|
|
848
|
+
});
|
|
849
|
+
const anthropicListResponse = Validators.object({
|
|
850
|
+
data: Validators.arrayOf(anthropicListEntry)
|
|
851
|
+
});
|
|
852
|
+
const geminiListEntry = Validators.object({
|
|
853
|
+
name: Validators.string,
|
|
854
|
+
displayName: Validators.string.optional(),
|
|
855
|
+
supportedGenerationMethods: Validators.arrayOf(Validators.string).optional()
|
|
856
|
+
});
|
|
857
|
+
const geminiListResponse = Validators.object({
|
|
858
|
+
models: Validators.arrayOf(geminiListEntry)
|
|
859
|
+
});
|
|
860
|
+
// ============================================================================
|
|
861
|
+
// List models — capability resolution
|
|
862
|
+
// ============================================================================
|
|
863
|
+
/**
|
|
864
|
+
* Translates Gemini's `supportedGenerationMethods` strings into our abstract
|
|
865
|
+
* capability vocabulary. Methods without a mapping are ignored.
|
|
866
|
+
* @internal
|
|
867
|
+
*/
|
|
868
|
+
function geminiMethodsToCapabilities(methods) {
|
|
869
|
+
const out = [];
|
|
870
|
+
for (const m of methods) {
|
|
871
|
+
if (m === 'generateContent') {
|
|
872
|
+
out.push('chat');
|
|
873
|
+
}
|
|
874
|
+
else if (m === 'predict') {
|
|
875
|
+
out.push('image-generation');
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return out;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Strips the `models/` prefix Gemini includes on listed model names.
|
|
882
|
+
* @internal
|
|
883
|
+
*/
|
|
884
|
+
function geminiBareId(name) {
|
|
885
|
+
return name.startsWith('models/') ? name.substring('models/'.length) : name;
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Applies a capability config to a model id. Walks per-provider rules then
|
|
889
|
+
* global rules; unions all matching rules' capabilities. Returns the union
|
|
890
|
+
* and the first matching `displayName` (if any).
|
|
891
|
+
* @internal
|
|
892
|
+
*/
|
|
893
|
+
function applyCapabilityConfig(config, providerId, modelId) {
|
|
894
|
+
var _a, _b, _c;
|
|
895
|
+
const caps = new Set();
|
|
896
|
+
let displayName;
|
|
897
|
+
const rulesets = [
|
|
898
|
+
(_b = (_a = config.perProvider) === null || _a === void 0 ? void 0 : _a[providerId]) !== null && _b !== void 0 ? _b : [],
|
|
899
|
+
(_c = config.global) !== null && _c !== void 0 ? _c : []
|
|
900
|
+
];
|
|
901
|
+
for (const rules of rulesets) {
|
|
902
|
+
for (const rule of rules) {
|
|
903
|
+
rule.idPattern.lastIndex = 0;
|
|
904
|
+
if (rule.idPattern.test(modelId)) {
|
|
905
|
+
for (const cap of rule.capabilities) {
|
|
906
|
+
caps.add(cap);
|
|
907
|
+
}
|
|
908
|
+
if (displayName === undefined && rule.displayName !== undefined) {
|
|
909
|
+
displayName = typeof rule.displayName === 'function' ? rule.displayName(modelId) : rule.displayName;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return { capabilities: Array.from(caps), displayName };
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Combines provider-native capability info (when supplied) and config-derived
|
|
918
|
+
* capability info into a final {@link IAiModelInfo}.
|
|
919
|
+
* @internal
|
|
920
|
+
*/
|
|
921
|
+
function buildModelInfo(providerId, id, nativeCapabilities, nativeDisplayName, config) {
|
|
922
|
+
const fromConfig = applyCapabilityConfig(config, providerId, id);
|
|
923
|
+
const all = new Set([...nativeCapabilities, ...fromConfig.capabilities]);
|
|
924
|
+
return Object.assign({ id, capabilities: all }, (nativeDisplayName !== undefined
|
|
925
|
+
? { displayName: nativeDisplayName }
|
|
926
|
+
: fromConfig.displayName !== undefined
|
|
927
|
+
? { displayName: fromConfig.displayName }
|
|
928
|
+
: {}));
|
|
929
|
+
}
|
|
930
|
+
// ============================================================================
|
|
931
|
+
// List models — adapters
|
|
932
|
+
// ============================================================================
|
|
933
|
+
/**
|
|
934
|
+
* Calls the OpenAI-style `GET /models` endpoint. Used by openai, xai-grok,
|
|
935
|
+
* groq, and mistral. Provider supplies no capability info — capabilities are
|
|
936
|
+
* derived entirely from the config.
|
|
937
|
+
* @internal
|
|
938
|
+
*/
|
|
939
|
+
async function callOpenAiListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
940
|
+
const url = `${config.baseUrl}/models`;
|
|
941
|
+
const headers = {
|
|
942
|
+
Authorization: `Bearer ${config.apiKey}`
|
|
943
|
+
};
|
|
944
|
+
/* c8 ignore next 1 - optional logger */
|
|
945
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=openai`);
|
|
946
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
947
|
+
if (jsonResult.isFailure()) {
|
|
948
|
+
return fail(jsonResult.message);
|
|
949
|
+
}
|
|
950
|
+
return openAiListResponse
|
|
951
|
+
.validate(jsonResult.value)
|
|
952
|
+
.withErrorFormat((msg) => `OpenAI models API response: ${msg}`)
|
|
953
|
+
.onSuccess((response) => {
|
|
954
|
+
const models = response.data.map((entry) => buildModelInfo(providerId, entry.id, [], undefined, capabilityConfig));
|
|
955
|
+
return succeed(models);
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Calls the Anthropic `GET /models` endpoint. Provider supplies a
|
|
960
|
+
* `display_name` but no native capability info.
|
|
961
|
+
* @internal
|
|
962
|
+
*/
|
|
963
|
+
async function callAnthropicListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
964
|
+
const url = `${config.baseUrl}/models`;
|
|
965
|
+
const headers = {
|
|
966
|
+
'x-api-key': config.apiKey,
|
|
967
|
+
'anthropic-version': '2023-06-01',
|
|
968
|
+
'anthropic-dangerous-direct-browser-access': 'true'
|
|
969
|
+
};
|
|
970
|
+
/* c8 ignore next 1 - optional logger */
|
|
971
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=anthropic`);
|
|
972
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
973
|
+
if (jsonResult.isFailure()) {
|
|
974
|
+
return fail(jsonResult.message);
|
|
975
|
+
}
|
|
976
|
+
return anthropicListResponse
|
|
977
|
+
.validate(jsonResult.value)
|
|
978
|
+
.withErrorFormat((msg) => `Anthropic models API response: ${msg}`)
|
|
979
|
+
.onSuccess((response) => {
|
|
980
|
+
const models = response.data.map((entry) => buildModelInfo(providerId, entry.id, [], entry.display_name, capabilityConfig));
|
|
981
|
+
return succeed(models);
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Calls the Gemini `GET /models` endpoint. Provider supplies both a
|
|
986
|
+
* `displayName` and `supportedGenerationMethods` — translated to native
|
|
987
|
+
* capabilities and unioned with config-derived capabilities.
|
|
988
|
+
* @internal
|
|
989
|
+
*/
|
|
990
|
+
async function callGeminiListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
991
|
+
const url = `${config.baseUrl}/models`;
|
|
992
|
+
const headers = {
|
|
993
|
+
'x-goog-api-key': config.apiKey
|
|
994
|
+
};
|
|
995
|
+
/* c8 ignore next 1 - optional logger */
|
|
996
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=gemini`);
|
|
997
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
998
|
+
if (jsonResult.isFailure()) {
|
|
999
|
+
return fail(jsonResult.message);
|
|
1000
|
+
}
|
|
1001
|
+
return geminiListResponse
|
|
1002
|
+
.validate(jsonResult.value)
|
|
1003
|
+
.withErrorFormat((msg) => `Gemini models API response: ${msg}`)
|
|
1004
|
+
.onSuccess((response) => {
|
|
1005
|
+
const models = response.models.map((entry) => {
|
|
1006
|
+
const id = geminiBareId(entry.name);
|
|
1007
|
+
const native = entry.supportedGenerationMethods
|
|
1008
|
+
? geminiMethodsToCapabilities(entry.supportedGenerationMethods)
|
|
1009
|
+
: [];
|
|
1010
|
+
return buildModelInfo(providerId, id, native, entry.displayName, capabilityConfig);
|
|
1011
|
+
});
|
|
1012
|
+
return succeed(models);
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
// ============================================================================
|
|
1016
|
+
// List models — dispatcher
|
|
1017
|
+
// ============================================================================
|
|
1018
|
+
/**
|
|
1019
|
+
* Lists models available from a provider, with capabilities resolved from
|
|
1020
|
+
* native provider info (where supplied) and a configurable rule set.
|
|
1021
|
+
*
|
|
1022
|
+
* Routes based on `descriptor.apiFormat` — listing reuses the existing
|
|
1023
|
+
* format dispatch and does not require a separate descriptor field.
|
|
1024
|
+
*
|
|
1025
|
+
* @param params - Request parameters including descriptor, API key, and optional capability filter
|
|
1026
|
+
* @returns The resolved model list, or a failure
|
|
1027
|
+
* @public
|
|
1028
|
+
*/
|
|
1029
|
+
export async function callProviderListModels(params) {
|
|
1030
|
+
const { descriptor, apiKey, capability, capabilityConfig, logger, signal } = params;
|
|
1031
|
+
if (!descriptor.baseUrl) {
|
|
1032
|
+
return fail(`provider "${descriptor.id}" has no API endpoint configured`);
|
|
1033
|
+
}
|
|
1034
|
+
const config = {
|
|
1035
|
+
baseUrl: descriptor.baseUrl,
|
|
1036
|
+
apiKey,
|
|
1037
|
+
model: '' // unused by listing
|
|
1038
|
+
};
|
|
1039
|
+
const effectiveConfig = capabilityConfig !== null && capabilityConfig !== void 0 ? capabilityConfig : DEFAULT_MODEL_CAPABILITY_CONFIG;
|
|
1040
|
+
let listResult;
|
|
1041
|
+
switch (descriptor.apiFormat) {
|
|
1042
|
+
case 'openai':
|
|
1043
|
+
listResult = await callOpenAiListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
1044
|
+
break;
|
|
1045
|
+
case 'anthropic':
|
|
1046
|
+
listResult = await callAnthropicListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
1047
|
+
break;
|
|
1048
|
+
case 'gemini':
|
|
1049
|
+
listResult = await callGeminiListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
1050
|
+
break;
|
|
1051
|
+
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
1052
|
+
default: {
|
|
1053
|
+
const _exhaustive = descriptor.apiFormat;
|
|
1054
|
+
return fail(`unsupported API format: ${String(_exhaustive)}`);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
if (listResult.isFailure()) {
|
|
1058
|
+
return listResult;
|
|
1059
|
+
}
|
|
1060
|
+
if (capability === undefined) {
|
|
1061
|
+
return listResult;
|
|
1062
|
+
}
|
|
1063
|
+
return succeed(listResult.value.filter((m) => m.capabilities.has(capability)));
|
|
1064
|
+
}
|
|
1065
|
+
// ============================================================================
|
|
1066
|
+
// Proxied list models
|
|
1067
|
+
// ============================================================================
|
|
1068
|
+
/**
|
|
1069
|
+
* Calls the model-listing endpoint on a proxy server.
|
|
1070
|
+
*
|
|
1071
|
+
* @remarks
|
|
1072
|
+
* Proxy contract:
|
|
1073
|
+
* - Endpoint: `POST ${proxyUrl}/api/ai/list-models`
|
|
1074
|
+
* - Request body: `{providerId, apiKey, capability?}`. Capability config is
|
|
1075
|
+
* not forwarded — the proxy applies its own (typically the same default
|
|
1076
|
+
* the library ships).
|
|
1077
|
+
* - Success response body: an `IAiModelInfo[]` (under key `models`) where
|
|
1078
|
+
* `capabilities` is serialized as a string array (not Set, which doesn't
|
|
1079
|
+
* round-trip through JSON).
|
|
1080
|
+
* - Error response body: `{error: string}`, surfaced as `proxy: ${error}`.
|
|
1081
|
+
*
|
|
1082
|
+
* @public
|
|
1083
|
+
*/
|
|
1084
|
+
export async function callProxiedListModels(proxyUrl, params) {
|
|
1085
|
+
const { descriptor, apiKey, capability, logger, signal } = params;
|
|
1086
|
+
const body = {
|
|
1087
|
+
providerId: descriptor.id,
|
|
1088
|
+
apiKey
|
|
1089
|
+
};
|
|
1090
|
+
if (capability !== undefined) {
|
|
1091
|
+
body.capability = capability;
|
|
1092
|
+
}
|
|
1093
|
+
/* c8 ignore next 1 - optional logger */
|
|
1094
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`AI list-models proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
1095
|
+
const url = `${proxyUrl}/api/ai/list-models`;
|
|
1096
|
+
const jsonResult = await fetchJson(url, {}, body, logger, signal);
|
|
1097
|
+
if (jsonResult.isFailure()) {
|
|
1098
|
+
return fail(jsonResult.message);
|
|
1099
|
+
}
|
|
1100
|
+
const response = jsonResult.value;
|
|
1101
|
+
if (typeof response.error === 'string') {
|
|
1102
|
+
return fail(`proxy: ${response.error}`);
|
|
1103
|
+
}
|
|
1104
|
+
return proxiedListModelsResponse
|
|
1105
|
+
.validate(response)
|
|
1106
|
+
.withErrorFormat((msg) => `proxy returned invalid response: ${msg}`)
|
|
1107
|
+
.onSuccess((parsed) => {
|
|
1108
|
+
const models = parsed.models.map((m) => (Object.assign({ id: m.id, capabilities: new Set(m.capabilities) }, (m.displayName !== undefined ? { displayName: m.displayName } : {}))));
|
|
1109
|
+
return succeed(models);
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
431
1112
|
// ============================================================================
|
|
432
1113
|
// Proxied completion (routes through a backend server)
|
|
433
1114
|
// ============================================================================
|
|
@@ -445,11 +1126,15 @@ export async function callProviderCompletion(params) {
|
|
|
445
1126
|
* @public
|
|
446
1127
|
*/
|
|
447
1128
|
export async function callProxiedCompletion(proxyUrl, params) {
|
|
448
|
-
const { descriptor, apiKey, prompt, additionalMessages, temperature, modelOverride, logger, tools } = params;
|
|
1129
|
+
const { descriptor, apiKey, prompt, additionalMessages, temperature, modelOverride, logger, tools, signal } = params;
|
|
1130
|
+
const promptBody = { system: prompt.system, user: prompt.user };
|
|
1131
|
+
if (prompt.attachments.length > 0) {
|
|
1132
|
+
promptBody.attachments = prompt.attachments;
|
|
1133
|
+
}
|
|
449
1134
|
const body = {
|
|
450
1135
|
providerId: descriptor.id,
|
|
451
1136
|
apiKey,
|
|
452
|
-
prompt:
|
|
1137
|
+
prompt: promptBody,
|
|
453
1138
|
temperature: temperature !== null && temperature !== void 0 ? temperature : 0.7
|
|
454
1139
|
};
|
|
455
1140
|
if (additionalMessages && additionalMessages.length > 0) {
|
|
@@ -464,7 +1149,7 @@ export async function callProxiedCompletion(proxyUrl, params) {
|
|
|
464
1149
|
/* c8 ignore next 1 - optional logger */
|
|
465
1150
|
logger === null || logger === void 0 ? void 0 : logger.info(`AI proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
466
1151
|
const url = `${proxyUrl}/api/ai/completion`;
|
|
467
|
-
const jsonResult = await fetchJson(url, {}, body, logger);
|
|
1152
|
+
const jsonResult = await fetchJson(url, {}, body, logger, signal);
|
|
468
1153
|
if (jsonResult.isFailure()) {
|
|
469
1154
|
return fail(jsonResult.message);
|
|
470
1155
|
}
|
|
@@ -481,4 +1166,54 @@ export async function callProxiedCompletion(proxyUrl, params) {
|
|
|
481
1166
|
truncated: response.truncated === true
|
|
482
1167
|
});
|
|
483
1168
|
}
|
|
1169
|
+
// ============================================================================
|
|
1170
|
+
// Proxied image generation
|
|
1171
|
+
// ============================================================================
|
|
1172
|
+
/**
|
|
1173
|
+
* Calls the image-generation endpoint on a proxy server instead of calling
|
|
1174
|
+
* the provider API directly from the browser.
|
|
1175
|
+
*
|
|
1176
|
+
* @remarks
|
|
1177
|
+
* The proxy contract:
|
|
1178
|
+
* - Endpoint: `POST ${proxyUrl}/api/ai/image-generation`
|
|
1179
|
+
* - Request body: `{providerId, apiKey, params, modelOverride?}`
|
|
1180
|
+
* - Success response body: an {@link IAiImageGenerationResponse}
|
|
1181
|
+
* - Error response body: `{error: string}` (surfaced as `proxy: ${error}`)
|
|
1182
|
+
*
|
|
1183
|
+
* The proxy server is responsible for descriptor lookup, model resolution,
|
|
1184
|
+
* provider dispatch, and response normalization. When `params.referenceImages`
|
|
1185
|
+
* is present, the proxy is also responsible for repackaging it into the
|
|
1186
|
+
* upstream wire format (e.g. multipart/form-data for OpenAI `/images/edits`,
|
|
1187
|
+
* `inlineData` parts for Gemini `:generateContent`).
|
|
1188
|
+
*
|
|
1189
|
+
* @param proxyUrl - Base URL of the proxy server (e.g. `http://localhost:3001`)
|
|
1190
|
+
* @param params - Same parameters as {@link callProviderImageGeneration}
|
|
1191
|
+
* @returns The generated images, or a failure
|
|
1192
|
+
* @public
|
|
1193
|
+
*/
|
|
1194
|
+
export async function callProxiedImageGeneration(proxyUrl, params) {
|
|
1195
|
+
const { descriptor, apiKey, params: request, modelOverride, logger, signal } = params;
|
|
1196
|
+
const body = {
|
|
1197
|
+
providerId: descriptor.id,
|
|
1198
|
+
apiKey,
|
|
1199
|
+
params: request
|
|
1200
|
+
};
|
|
1201
|
+
if (modelOverride !== undefined) {
|
|
1202
|
+
body.modelOverride = modelOverride;
|
|
1203
|
+
}
|
|
1204
|
+
/* c8 ignore next 1 - optional logger */
|
|
1205
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`AI image proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
1206
|
+
const url = `${proxyUrl}/api/ai/image-generation`;
|
|
1207
|
+
const jsonResult = await fetchJson(url, {}, body, logger, signal);
|
|
1208
|
+
if (jsonResult.isFailure()) {
|
|
1209
|
+
return fail(jsonResult.message);
|
|
1210
|
+
}
|
|
1211
|
+
const response = jsonResult.value;
|
|
1212
|
+
if (typeof response.error === 'string') {
|
|
1213
|
+
return fail(`proxy: ${response.error}`);
|
|
1214
|
+
}
|
|
1215
|
+
return proxiedImageGenerationResponse
|
|
1216
|
+
.validate(response)
|
|
1217
|
+
.withErrorFormat((msg) => `proxy returned invalid response: ${msg}`);
|
|
1218
|
+
}
|
|
484
1219
|
//# sourceMappingURL=apiClient.js.map
|