@fgv/ts-extras 5.1.0-48 → 5.1.0-49
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/packlets/ai-assist/completionClient.js +435 -0
- package/dist/packlets/ai-assist/completionClient.js.map +1 -0
- package/dist/packlets/ai-assist/embeddingClient.js +2 -2
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/dist/packlets/ai-assist/endpoint.js +29 -0
- package/dist/packlets/ai-assist/endpoint.js.map +1 -1
- package/dist/packlets/ai-assist/http.js +48 -19
- package/dist/packlets/ai-assist/http.js.map +1 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js +454 -0
- package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +3 -1
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/dist/packlets/ai-assist/listModelsClient.js +294 -0
- package/dist/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/dist/packlets/crypto-utils/encryptedFile.js +37 -0
- package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +1 -1
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/dist/ts-extras.d.ts +59 -4
- package/lib/packlets/ai-assist/completionClient.d.ts +74 -0
- package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/completionClient.js +439 -0
- package/lib/packlets/ai-assist/completionClient.js.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.js +1 -1
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/lib/packlets/ai-assist/endpoint.d.ts +21 -0
- package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -1
- package/lib/packlets/ai-assist/endpoint.js +31 -0
- package/lib/packlets/ai-assist/endpoint.js.map +1 -1
- package/lib/packlets/ai-assist/http.d.ts +12 -2
- package/lib/packlets/ai-assist/http.d.ts.map +1 -1
- package/lib/packlets/ai-assist/http.js +49 -18
- package/lib/packlets/ai-assist/http.js.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts +46 -0
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js +458 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +3 -1
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +9 -7
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.js +2 -2
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.d.ts +46 -0
- package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/listModelsClient.js +298 -0
- package/lib/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.d.ts +25 -0
- package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.js +38 -0
- package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +1 -1
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +2 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +30 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/package.json +7 -7
- package/dist/packlets/ai-assist/apiClient.js +0 -1236
- package/dist/packlets/ai-assist/apiClient.js.map +0 -1
- package/lib/packlets/ai-assist/apiClient.d.ts +0 -152
- package/lib/packlets/ai-assist/apiClient.d.ts.map +0 -1
- package/lib/packlets/ai-assist/apiClient.js +0 -1244
- package/lib/packlets/ai-assist/apiClient.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jsonCompletion.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonCompletion.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;;;;;;;;;;;;AAEZ;;;;;;;GAOG;AAEH,OAAO,EAAkB,IAAI,EAAU,OAAO,EAA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,GAAG,OAAO,EAAE,MAAM,KAAc,MAAM,EAAf,IAAI,UAAK,MAAM,EAA5E,sDAAmE,CAAS,CAAC;IAEnF,IAAI,aAAa,KAAK,SAAS,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC3D,OAAO,IAAI,CAAC,6EAA6E,CAAC,CAAC;IAC7F,CAAC;IAED,MAAM,QAAQ,GAAiB,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,qBAAqB,CAAI,EAAE,KAAK,EAAE,SAAU,EAAE,CAAC,CAAC;IAChG,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAE5D,MAAM,QAAQ,GAAG,MAAM,sBAAsB,iCAAM,IAAI,KAAE,MAAM,EAAE,eAAe,IAAG,CAAC;IACpF,IAAI,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IACD,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC;IAElC,OAAO,QAAQ;SACZ,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;SAC3B,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,2BAA2B,GAAG,EAAE,CAAC;SAC1D,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,CAAC,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;AAC7F,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 * `generateJsonCompletion<T>` — request a JSON-shaped completion from any\n * provider supported by AiAssist and validate it against a caller-supplied\n * `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +\n * validation into a single call so consumers don't reinvent the pipeline.\n *\n * @packageDocumentation\n */\n\nimport { type Converter, fail, Result, succeed, type Validator } from '@fgv/ts-utils';\n\nimport { callProviderCompletion, type IProviderCompletionParams } from './completionClient';\nimport { fencedStringifiedJson } from './jsonResponse';\nimport { type IAiCompletionResponse } from './model';\n\n/**\n * Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}\n * is `'smart'` (the default). Designed to discourage code fences and prose in\n * the model's response while still tolerating them via the read-side extractor.\n * @public\n */\nexport const SMART_JSON_PROMPT_HINT: string =\n 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +\n 'no preamble or trailing commentary. The response must parse with JSON.parse.';\n\n/**\n * Controls the optional system-prompt augmentation applied by\n * {@link AiAssist.generateJsonCompletion}.\n *\n * - `'smart'` (default): append {@link AiAssist.SMART_JSON_PROMPT_HINT}.\n * - `'none'`: do not modify the prompt.\n * - A string: append the supplied text verbatim.\n *\n * @remarks\n * The `string & {}` branch is the standard TypeScript trick that prevents\n * the literal members from being widened away — callers still get\n * autocomplete for `'smart'` and `'none'` while accepting any string.\n *\n * @public\n */\nexport type JsonPromptHint = 'smart' | 'none' | (string & {});\n\n/**\n * Parameters for {@link AiAssist.generateJsonCompletion}. Extends\n * {@link AiAssist.IProviderCompletionParams} with JSON-validation knobs.\n * @public\n */\nexport interface IGenerateJsonCompletionParams<T> extends IProviderCompletionParams {\n /**\n * Caller-supplied `Converter<T>` or `Validator<T>` applied to the parsed\n * JSON value. Wrapped internally in {@link AiAssist.fencedStringifiedJson}\n * unless {@link AiAssist.IGenerateJsonCompletionParams.jsonConverter} is\n * provided.\n */\n readonly converter?: Converter<T> | Validator<T>;\n\n /**\n * Full string-to-`T` pipeline override. When supplied, takes precedence over\n * {@link AiAssist.IGenerateJsonCompletionParams.converter} and lets the\n * caller plug in a custom extractor or skip the default fence tolerance\n * entirely.\n */\n readonly jsonConverter?: Converter<T>;\n\n /**\n * Controls the optional system-prompt augmentation. Defaults to `'smart'`.\n * Pass `'none'` to disable, or a string to append custom guidance.\n */\n readonly promptHint?: JsonPromptHint;\n}\n\n/**\n * Successful result of {@link AiAssist.generateJsonCompletion}.\n * @public\n */\nexport interface IGenerateJsonCompletionResult<T> {\n /** The validated JSON value. */\n readonly value: T;\n /** The raw response text returned by the provider. */\n readonly raw: string;\n /** The full underlying completion response. */\n readonly response: IAiCompletionResponse;\n}\n\nfunction applyPromptHint(system: string | undefined, hint: JsonPromptHint): string | undefined {\n if (hint === 'none') {\n return system;\n }\n const suffix = hint === 'smart' ? SMART_JSON_PROMPT_HINT : hint;\n return system !== undefined && system.length > 0 ? `${system}\\n\\n${suffix}` : suffix;\n}\n\n/**\n * Calls {@link AiAssist.callProviderCompletion}, then runs the response text\n * through a tolerant JSON converter (default:\n * {@link AiAssist.fencedStringifiedJson}) and the caller's\n * `converter`/`validator`. Returns the validated value plus the raw text and\n * underlying completion response for diagnostics.\n *\n * @remarks\n * The default smart prompt hint asks the model to emit raw JSON. The read-side\n * extractor still tolerates fences and prose, so models that ignore the hint\n * are still handled.\n *\n * Either `converter` or `jsonConverter` must be provided; passing both lets\n * `jsonConverter` win.\n *\n * @param params - Provider parameters plus JSON validation options.\n * @returns The validated value, the raw text, and the underlying response.\n * @public\n */\nexport async function generateJsonCompletion<T>(\n params: IGenerateJsonCompletionParams<T>\n): Promise<Result<IGenerateJsonCompletionResult<T>>> {\n const { converter, jsonConverter, promptHint = 'smart', system, ...rest } = params;\n\n if (jsonConverter === undefined && converter === undefined) {\n return fail('generateJsonCompletion: either converter or jsonConverter must be provided.');\n }\n\n const pipeline: Converter<T> = jsonConverter ?? fencedStringifiedJson<T>({ inner: converter! });\n const augmentedSystem = applyPromptHint(system, promptHint);\n\n const response = await callProviderCompletion({ ...rest, system: augmentedSystem });\n if (response.isFailure()) {\n return fail(response.message);\n }\n const completion = response.value;\n\n return pipeline\n .convert(completion.content)\n .withErrorFormat((msg) => `generateJsonCompletion: ${msg}`)\n .onSuccess((value) => succeed({ value, raw: completion.content, response: completion }));\n}\n"]}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
/**
|
|
21
|
+
* Model-listing clients for AI assist. One provider dispatcher over
|
|
22
|
+
* `IAiProviderDescriptor.apiFormat`, its adapters and response validators, the
|
|
23
|
+
* capability-resolution helpers that turn a raw model id into an
|
|
24
|
+
* `IAiModelInfo`, and the proxied variant.
|
|
25
|
+
*
|
|
26
|
+
* @packageDocumentation
|
|
27
|
+
*/
|
|
28
|
+
import { fail, succeed, Validators } from '@fgv/ts-utils';
|
|
29
|
+
import { allModelCapabilities } from './model';
|
|
30
|
+
import { anthropicAuthHeaders, bearerAuthHeader, geminiAuthHeader, resolveEffectiveBaseUrl } from './endpoint';
|
|
31
|
+
import { fetchGetJson, fetchJson } from './http';
|
|
32
|
+
import { DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';
|
|
33
|
+
const proxiedListModelsEntry = Validators.object({
|
|
34
|
+
id: Validators.string,
|
|
35
|
+
capabilities: Validators.arrayOf(Validators.enumeratedValue(allModelCapabilities)),
|
|
36
|
+
displayName: Validators.string.optional()
|
|
37
|
+
});
|
|
38
|
+
const proxiedListModelsResponse = Validators.object({
|
|
39
|
+
models: Validators.arrayOf(proxiedListModelsEntry)
|
|
40
|
+
});
|
|
41
|
+
const openAiListEntry = Validators.object({
|
|
42
|
+
id: Validators.string
|
|
43
|
+
});
|
|
44
|
+
const openAiListResponse = Validators.object({
|
|
45
|
+
data: Validators.arrayOf(openAiListEntry)
|
|
46
|
+
});
|
|
47
|
+
const anthropicListEntry = Validators.object({
|
|
48
|
+
id: Validators.string,
|
|
49
|
+
display_name: Validators.string.optional()
|
|
50
|
+
});
|
|
51
|
+
const anthropicListResponse = Validators.object({
|
|
52
|
+
data: Validators.arrayOf(anthropicListEntry)
|
|
53
|
+
});
|
|
54
|
+
const geminiListEntry = Validators.object({
|
|
55
|
+
name: Validators.string,
|
|
56
|
+
displayName: Validators.string.optional(),
|
|
57
|
+
supportedGenerationMethods: Validators.arrayOf(Validators.string).optional()
|
|
58
|
+
});
|
|
59
|
+
const geminiListResponse = Validators.object({
|
|
60
|
+
models: Validators.arrayOf(geminiListEntry)
|
|
61
|
+
});
|
|
62
|
+
// ============================================================================
|
|
63
|
+
// List models — capability resolution
|
|
64
|
+
// ============================================================================
|
|
65
|
+
/**
|
|
66
|
+
* Translates Gemini's `supportedGenerationMethods` strings into our abstract
|
|
67
|
+
* capability vocabulary. Methods without a mapping are ignored.
|
|
68
|
+
* @internal
|
|
69
|
+
*/
|
|
70
|
+
function geminiMethodsToCapabilities(methods) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const m of methods) {
|
|
73
|
+
if (m === 'generateContent') {
|
|
74
|
+
out.push('chat');
|
|
75
|
+
}
|
|
76
|
+
else if (m === 'predict') {
|
|
77
|
+
out.push('image-generation');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Strips the `models/` prefix Gemini includes on listed model names.
|
|
84
|
+
* @internal
|
|
85
|
+
*/
|
|
86
|
+
function geminiBareId(name) {
|
|
87
|
+
/* c8 ignore next 1 - defensive: Gemini API always returns names prefixed with 'models/' */
|
|
88
|
+
return name.startsWith('models/') ? name.substring('models/'.length) : name;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Applies a capability config to a model id. Walks per-provider rules then
|
|
92
|
+
* global rules; unions all matching rules' capabilities. Returns the union
|
|
93
|
+
* and the first matching `displayName` (if any).
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
function applyCapabilityConfig(config, providerId, modelId) {
|
|
97
|
+
var _a, _b, _c;
|
|
98
|
+
const caps = new Set();
|
|
99
|
+
let displayName;
|
|
100
|
+
const rulesets = [
|
|
101
|
+
(_b = (_a = config.perProvider) === null || _a === void 0 ? void 0 : _a[providerId]) !== null && _b !== void 0 ? _b : [],
|
|
102
|
+
(_c = config.global) !== null && _c !== void 0 ? _c : []
|
|
103
|
+
];
|
|
104
|
+
for (const rules of rulesets) {
|
|
105
|
+
for (const rule of rules) {
|
|
106
|
+
rule.idPattern.lastIndex = 0;
|
|
107
|
+
if (rule.idPattern.test(modelId)) {
|
|
108
|
+
for (const cap of rule.capabilities) {
|
|
109
|
+
caps.add(cap);
|
|
110
|
+
}
|
|
111
|
+
if (displayName === undefined && rule.displayName !== undefined) {
|
|
112
|
+
displayName = typeof rule.displayName === 'function' ? rule.displayName(modelId) : rule.displayName;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { capabilities: Array.from(caps), displayName };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Combines provider-native capability info (when supplied) and config-derived
|
|
121
|
+
* capability info into a final {@link IAiModelInfo}.
|
|
122
|
+
* @internal
|
|
123
|
+
*/
|
|
124
|
+
function buildModelInfo(providerId, id, nativeCapabilities, nativeDisplayName, config) {
|
|
125
|
+
const fromConfig = applyCapabilityConfig(config, providerId, id);
|
|
126
|
+
const all = new Set([...nativeCapabilities, ...fromConfig.capabilities]);
|
|
127
|
+
return Object.assign({ id, capabilities: all }, (nativeDisplayName !== undefined
|
|
128
|
+
? { displayName: nativeDisplayName }
|
|
129
|
+
: fromConfig.displayName !== undefined
|
|
130
|
+
? { displayName: fromConfig.displayName }
|
|
131
|
+
: {}));
|
|
132
|
+
}
|
|
133
|
+
// ============================================================================
|
|
134
|
+
// List models — adapters
|
|
135
|
+
// ============================================================================
|
|
136
|
+
/**
|
|
137
|
+
* Calls the OpenAI-style `GET /models` endpoint. Used by openai, xai-grok,
|
|
138
|
+
* groq, and mistral. Provider supplies no capability info — capabilities are
|
|
139
|
+
* derived entirely from the config.
|
|
140
|
+
* @internal
|
|
141
|
+
*/
|
|
142
|
+
async function callOpenAiListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
143
|
+
const url = `${config.baseUrl}/models`;
|
|
144
|
+
const headers = bearerAuthHeader(config.apiKey);
|
|
145
|
+
/* c8 ignore next 1 - optional logger */
|
|
146
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=openai`);
|
|
147
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
148
|
+
if (jsonResult.isFailure()) {
|
|
149
|
+
return fail(jsonResult.message);
|
|
150
|
+
}
|
|
151
|
+
return openAiListResponse
|
|
152
|
+
.validate(jsonResult.value)
|
|
153
|
+
.withErrorFormat((msg) => `OpenAI models API response: ${msg}`)
|
|
154
|
+
.onSuccess((response) => {
|
|
155
|
+
const models = response.data.map((entry) => buildModelInfo(providerId, entry.id, [], undefined, capabilityConfig));
|
|
156
|
+
return succeed(models);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Calls the Anthropic `GET /models` endpoint. Provider supplies a
|
|
161
|
+
* `display_name` but no native capability info.
|
|
162
|
+
* @internal
|
|
163
|
+
*/
|
|
164
|
+
async function callAnthropicListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
165
|
+
const url = `${config.baseUrl}/models`;
|
|
166
|
+
const headers = anthropicAuthHeaders(config.apiKey);
|
|
167
|
+
/* c8 ignore next 1 - optional logger */
|
|
168
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=anthropic`);
|
|
169
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
170
|
+
if (jsonResult.isFailure()) {
|
|
171
|
+
return fail(jsonResult.message);
|
|
172
|
+
}
|
|
173
|
+
return anthropicListResponse
|
|
174
|
+
.validate(jsonResult.value)
|
|
175
|
+
.withErrorFormat((msg) => `Anthropic models API response: ${msg}`)
|
|
176
|
+
.onSuccess((response) => {
|
|
177
|
+
const models = response.data.map((entry) => buildModelInfo(providerId, entry.id, [], entry.display_name, capabilityConfig));
|
|
178
|
+
return succeed(models);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Calls the Gemini `GET /models` endpoint. Provider supplies both a
|
|
183
|
+
* `displayName` and `supportedGenerationMethods` — translated to native
|
|
184
|
+
* capabilities and unioned with config-derived capabilities.
|
|
185
|
+
* @internal
|
|
186
|
+
*/
|
|
187
|
+
async function callGeminiListModels(config, providerId, capabilityConfig, logger, signal) {
|
|
188
|
+
const url = `${config.baseUrl}/models`;
|
|
189
|
+
const headers = geminiAuthHeader(config.apiKey);
|
|
190
|
+
/* c8 ignore next 1 - optional logger */
|
|
191
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`List models: provider=${providerId}, format=gemini`);
|
|
192
|
+
const jsonResult = await fetchGetJson(url, headers, logger, signal);
|
|
193
|
+
if (jsonResult.isFailure()) {
|
|
194
|
+
return fail(jsonResult.message);
|
|
195
|
+
}
|
|
196
|
+
return geminiListResponse
|
|
197
|
+
.validate(jsonResult.value)
|
|
198
|
+
.withErrorFormat((msg) => `Gemini models API response: ${msg}`)
|
|
199
|
+
.onSuccess((response) => {
|
|
200
|
+
const models = response.models.map((entry) => {
|
|
201
|
+
const id = geminiBareId(entry.name);
|
|
202
|
+
const native = entry.supportedGenerationMethods
|
|
203
|
+
? geminiMethodsToCapabilities(entry.supportedGenerationMethods)
|
|
204
|
+
: [];
|
|
205
|
+
return buildModelInfo(providerId, id, native, entry.displayName, capabilityConfig);
|
|
206
|
+
});
|
|
207
|
+
return succeed(models);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
// ============================================================================
|
|
211
|
+
// List models — dispatcher
|
|
212
|
+
// ============================================================================
|
|
213
|
+
/**
|
|
214
|
+
* Lists models available from a provider, routing by `descriptor.apiFormat`.
|
|
215
|
+
* Capabilities are resolved from native provider info and a configurable rule set.
|
|
216
|
+
* @param params - Request parameters (descriptor, API key, optional capability filter)
|
|
217
|
+
* @public
|
|
218
|
+
*/
|
|
219
|
+
export async function callProviderListModels(params) {
|
|
220
|
+
const { descriptor, apiKey, capability, capabilityConfig, logger, signal, endpoint } = params;
|
|
221
|
+
const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);
|
|
222
|
+
if (baseUrlResult.isFailure()) {
|
|
223
|
+
return fail(baseUrlResult.message);
|
|
224
|
+
}
|
|
225
|
+
const config = {
|
|
226
|
+
baseUrl: baseUrlResult.value,
|
|
227
|
+
apiKey,
|
|
228
|
+
model: '' // unused by listing
|
|
229
|
+
};
|
|
230
|
+
const effectiveConfig = capabilityConfig !== null && capabilityConfig !== void 0 ? capabilityConfig : DEFAULT_MODEL_CAPABILITY_CONFIG;
|
|
231
|
+
let listResult;
|
|
232
|
+
switch (descriptor.apiFormat) {
|
|
233
|
+
case 'openai':
|
|
234
|
+
listResult = await callOpenAiListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
235
|
+
break;
|
|
236
|
+
case 'anthropic':
|
|
237
|
+
listResult = await callAnthropicListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
238
|
+
break;
|
|
239
|
+
case 'gemini':
|
|
240
|
+
listResult = await callGeminiListModels(config, descriptor.id, effectiveConfig, logger, signal);
|
|
241
|
+
break;
|
|
242
|
+
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
243
|
+
default: {
|
|
244
|
+
const _exhaustive = descriptor.apiFormat;
|
|
245
|
+
return fail(`unsupported API format: ${String(_exhaustive)}`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (listResult.isFailure()) {
|
|
249
|
+
return listResult;
|
|
250
|
+
}
|
|
251
|
+
if (capability === undefined) {
|
|
252
|
+
return listResult;
|
|
253
|
+
}
|
|
254
|
+
return succeed(listResult.value.filter((m) => m.capabilities.has(capability)));
|
|
255
|
+
}
|
|
256
|
+
// ============================================================================
|
|
257
|
+
// Proxied list models
|
|
258
|
+
// ============================================================================
|
|
259
|
+
/**
|
|
260
|
+
* Calls the model-listing endpoint on a proxy server. Endpoint:
|
|
261
|
+
* `POST ${proxyUrl}/api/ai/list-models`. Capability config is not forwarded;
|
|
262
|
+
* `capabilities` is serialized as a string array. Error body `{error: string}`
|
|
263
|
+
* is surfaced as `proxy: ${error}`.
|
|
264
|
+
* @public
|
|
265
|
+
*/
|
|
266
|
+
export async function callProxiedListModels(proxyUrl, params) {
|
|
267
|
+
const { descriptor, apiKey, capability, logger, signal } = params;
|
|
268
|
+
const body = {
|
|
269
|
+
providerId: descriptor.id,
|
|
270
|
+
apiKey
|
|
271
|
+
};
|
|
272
|
+
if (capability !== undefined) {
|
|
273
|
+
body.capability = capability;
|
|
274
|
+
}
|
|
275
|
+
/* c8 ignore next 1 - optional logger */
|
|
276
|
+
logger === null || logger === void 0 ? void 0 : logger.info(`AI list-models proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
277
|
+
const url = `${proxyUrl}/api/ai/list-models`;
|
|
278
|
+
const jsonResult = await fetchJson(url, {}, body, logger, signal);
|
|
279
|
+
if (jsonResult.isFailure()) {
|
|
280
|
+
return fail(jsonResult.message);
|
|
281
|
+
}
|
|
282
|
+
const response = jsonResult.value;
|
|
283
|
+
if (typeof response.error === 'string') {
|
|
284
|
+
return fail(`proxy: ${response.error}`);
|
|
285
|
+
}
|
|
286
|
+
return proxiedListModelsResponse
|
|
287
|
+
.validate(response)
|
|
288
|
+
.withErrorFormat((msg) => `proxy returned invalid response: ${msg}`)
|
|
289
|
+
.onSuccess((parsed) => {
|
|
290
|
+
const models = parsed.models.map((m) => (Object.assign({ id: m.id, capabilities: new Set(m.capabilities) }, (m.displayName !== undefined ? { displayName: m.displayName } : {}))));
|
|
291
|
+
return succeed(models);
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
//# sourceMappingURL=listModelsClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"listModel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MAAM,CAAC,CAAC;IAClE,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAED,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAgC,CAAC;IAC7D,IAAI,OAAO,QAAQ,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,yBAAyB;SAC7B,QAAQ,CAAC,QAAQ,CAAC;SAClB,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oCAAoC,GAAG,EAAE,CAAC;SACnE,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;QACpB,MAAM,MAAM,GAAmB,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBACtD,EAAE,EAAE,CAAC,CAAC,EAAE,EACR,YAAY,EAAE,IAAI,GAAG,CAAoB,CAAC,CAAC,YAAY,CAAC,IACrD,CAAC,CAAC,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EACtE,CAAC,CAAC;QACJ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACP,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 * Model-listing clients for AI assist. One provider dispatcher over\n * `IAiProviderDescriptor.apiFormat`, its adapters and response validators, the\n * capability-resolution helpers that turn a raw model id into an\n * `IAiModelInfo`, and the proxied variant.\n *\n * @packageDocumentation\n */\n\nimport { fail, type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport {\n type AiModelCapability,\n allModelCapabilities,\n type IAiModelCapabilityConfig,\n type IAiModelCapabilityRule,\n type IAiModelInfo,\n type IAiProviderDescriptor\n} from './model';\nimport {\n anthropicAuthHeaders,\n bearerAuthHeader,\n geminiAuthHeader,\n resolveEffectiveBaseUrl\n} from './endpoint';\nimport { type IAiApiConfig, fetchGetJson, fetchJson } from './http';\nimport { DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';\n\n// ---- Proxied list-models response ----\n\n/**\n * Wire shape for proxy list-models responses. `capabilities` arrives as an\n * array (Sets don't survive JSON), then gets reassembled into a `Set` in\n * {@link callProxiedListModels}.\n * @internal\n */\ninterface IProxiedListModelsEntry {\n id: string;\n capabilities: AiModelCapability[];\n displayName?: string;\n}\n/** @internal */\ninterface IProxiedListModelsBody {\n models: IProxiedListModelsEntry[];\n}\n\nconst proxiedListModelsEntry: Validator<IProxiedListModelsEntry> = Validators.object<IProxiedListModelsEntry>(\n {\n id: Validators.string,\n capabilities: Validators.arrayOf(Validators.enumeratedValue<AiModelCapability>(allModelCapabilities)),\n displayName: Validators.string.optional()\n }\n);\nconst proxiedListModelsResponse: Validator<IProxiedListModelsBody> =\n Validators.object<IProxiedListModelsBody>({\n models: Validators.arrayOf(proxiedListModelsEntry)\n });\n\n// ============================================================================\n// List models — request types\n// ============================================================================\n\n/**\n * Parameters for a list-models request.\n * @public\n */\nexport interface IProviderListModelsParams {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /** Optional capability filter; when set, only models declaring this capability are returned. */\n readonly capability?: AiModelCapability;\n /** Optional capability config override (defaults to {@link DEFAULT_MODEL_CAPABILITY_CONFIG}). */\n readonly capabilityConfig?: IAiModelCapabilityConfig;\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /** Optional override of the descriptor's base URL; per-format `/models` route is appended unchanged. */\n readonly endpoint?: string;\n}\n\n// ============================================================================\n// List models — response validators\n// ============================================================================\n\n// ---- OpenAI / xAI / Groq / Mistral list format ----\n\n/** @internal */\ninterface IOpenAiListEntry {\n id: string;\n}\n/** @internal */\ninterface IOpenAiListResponse {\n data: IOpenAiListEntry[];\n}\n\nconst openAiListEntry: Validator<IOpenAiListEntry> = Validators.object<IOpenAiListEntry>({\n id: Validators.string\n});\nconst openAiListResponse: Validator<IOpenAiListResponse> = Validators.object<IOpenAiListResponse>({\n data: Validators.arrayOf(openAiListEntry)\n});\n\n// ---- Anthropic list format ----\n\n/** @internal */\ninterface IAnthropicListEntry {\n id: string;\n display_name?: string;\n}\n/** @internal */\ninterface IAnthropicListResponse {\n data: IAnthropicListEntry[];\n}\n\nconst anthropicListEntry: Validator<IAnthropicListEntry> = Validators.object<IAnthropicListEntry>({\n id: Validators.string,\n display_name: Validators.string.optional()\n});\nconst anthropicListResponse: Validator<IAnthropicListResponse> = Validators.object<IAnthropicListResponse>({\n data: Validators.arrayOf(anthropicListEntry)\n});\n\n// ---- Gemini list format ----\n\n/** @internal */\ninterface IGeminiListEntry {\n name: string;\n displayName?: string;\n supportedGenerationMethods?: string[];\n}\n/** @internal */\ninterface IGeminiListResponse {\n models: IGeminiListEntry[];\n}\n\nconst geminiListEntry: Validator<IGeminiListEntry> = Validators.object<IGeminiListEntry>({\n name: Validators.string,\n displayName: Validators.string.optional(),\n supportedGenerationMethods: Validators.arrayOf(Validators.string).optional()\n});\nconst geminiListResponse: Validator<IGeminiListResponse> = Validators.object<IGeminiListResponse>({\n models: Validators.arrayOf(geminiListEntry)\n});\n\n// ============================================================================\n// List models — capability resolution\n// ============================================================================\n\n/**\n * Translates Gemini's `supportedGenerationMethods` strings into our abstract\n * capability vocabulary. Methods without a mapping are ignored.\n * @internal\n */\nfunction geminiMethodsToCapabilities(methods: ReadonlyArray<string>): ReadonlyArray<AiModelCapability> {\n const out: AiModelCapability[] = [];\n for (const m of methods) {\n if (m === 'generateContent') {\n out.push('chat');\n } else if (m === 'predict') {\n out.push('image-generation');\n }\n }\n return out;\n}\n\n/**\n * Strips the `models/` prefix Gemini includes on listed model names.\n * @internal\n */\nfunction geminiBareId(name: string): string {\n /* c8 ignore next 1 - defensive: Gemini API always returns names prefixed with 'models/' */\n return name.startsWith('models/') ? name.substring('models/'.length) : name;\n}\n\n/**\n * Applies a capability config to a model id. Walks per-provider rules then\n * global rules; unions all matching rules' capabilities. Returns the union\n * and the first matching `displayName` (if any).\n * @internal\n */\nfunction applyCapabilityConfig(\n config: IAiModelCapabilityConfig,\n providerId: string,\n modelId: string\n): { capabilities: AiModelCapability[]; displayName: string | undefined } {\n const caps = new Set<AiModelCapability>();\n let displayName: string | undefined;\n\n const rulesets: ReadonlyArray<ReadonlyArray<IAiModelCapabilityRule>> = [\n config.perProvider?.[providerId as keyof typeof config.perProvider] ?? [],\n config.global ?? []\n ];\n\n for (const rules of rulesets) {\n for (const rule of rules) {\n rule.idPattern.lastIndex = 0;\n if (rule.idPattern.test(modelId)) {\n for (const cap of rule.capabilities) {\n caps.add(cap);\n }\n if (displayName === undefined && rule.displayName !== undefined) {\n displayName = typeof rule.displayName === 'function' ? rule.displayName(modelId) : rule.displayName;\n }\n }\n }\n }\n return { capabilities: Array.from(caps), displayName };\n}\n\n/**\n * Combines provider-native capability info (when supplied) and config-derived\n * capability info into a final {@link IAiModelInfo}.\n * @internal\n */\nfunction buildModelInfo(\n providerId: string,\n id: string,\n nativeCapabilities: ReadonlyArray<AiModelCapability>,\n nativeDisplayName: string | undefined,\n config: IAiModelCapabilityConfig\n): IAiModelInfo {\n const fromConfig = applyCapabilityConfig(config, providerId, id);\n const all = new Set<AiModelCapability>([...nativeCapabilities, ...fromConfig.capabilities]);\n return {\n id,\n capabilities: all,\n ...(nativeDisplayName !== undefined\n ? { displayName: nativeDisplayName }\n : fromConfig.displayName !== undefined\n ? { displayName: fromConfig.displayName }\n : {})\n };\n}\n\n// ============================================================================\n// List models — adapters\n// ============================================================================\n\n/**\n * Calls the OpenAI-style `GET /models` endpoint. Used by openai, xai-grok,\n * groq, and mistral. Provider supplies no capability info — capabilities are\n * derived entirely from the config.\n * @internal\n */\nasync function callOpenAiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=openai`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], undefined, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Anthropic `GET /models` endpoint. Provider supplies a\n * `display_name` but no native capability info.\n * @internal\n */\nasync function callAnthropicListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=anthropic`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return anthropicListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Anthropic models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], entry.display_name, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Gemini `GET /models` endpoint. Provider supplies both a\n * `displayName` and `supportedGenerationMethods` — translated to native\n * capabilities and unioned with config-derived capabilities.\n * @internal\n */\nasync function callGeminiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=gemini`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.models.map((entry) => {\n const id = geminiBareId(entry.name);\n const native = entry.supportedGenerationMethods\n ? geminiMethodsToCapabilities(entry.supportedGenerationMethods)\n : [];\n return buildModelInfo(providerId, id, native, entry.displayName, capabilityConfig);\n });\n return succeed(models);\n });\n}\n\n// ============================================================================\n// List models — dispatcher\n// ============================================================================\n\n/**\n * Lists models available from a provider, routing by `descriptor.apiFormat`.\n * Capabilities are resolved from native provider info and a configurable rule set.\n * @param params - Request parameters (descriptor, API key, optional capability filter)\n * @public\n */\nexport async function callProviderListModels(\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, capabilityConfig, logger, signal, endpoint } = params;\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n\n const config: IAiApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model: '' // unused by listing\n };\n const effectiveConfig = capabilityConfig ?? DEFAULT_MODEL_CAPABILITY_CONFIG;\n\n let listResult: Result<ReadonlyArray<IAiModelInfo>>;\n switch (descriptor.apiFormat) {\n case 'openai':\n listResult = await callOpenAiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'anthropic':\n listResult = await callAnthropicListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'gemini':\n listResult = await callGeminiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\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 if (listResult.isFailure()) {\n return listResult;\n }\n if (capability === undefined) {\n return listResult;\n }\n return succeed(listResult.value.filter((m) => m.capabilities.has(capability)));\n}\n\n// ============================================================================\n// Proxied list models\n// ============================================================================\n\n/**\n * Calls the model-listing endpoint on a proxy server. Endpoint:\n * `POST ${proxyUrl}/api/ai/list-models`. Capability config is not forwarded;\n * `capabilities` is serialized as a string array. Error body `{error: string}`\n * is surfaced as `proxy: ${error}`.\n * @public\n */\nexport async function callProxiedListModels(\n proxyUrl: string,\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, logger, signal } = params;\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey\n };\n if (capability !== undefined) {\n body.capability = capability;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI list-models proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n\n const url = `${proxyUrl}/api/ai/list-models`;\n const jsonResult = await fetchJson(url, {}, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const response = jsonResult.value as Record<string, unknown>;\n if (typeof response.error === 'string') {\n return fail(`proxy: ${response.error}`);\n }\n\n return proxiedListModelsResponse\n .validate(response)\n .withErrorFormat((msg) => `proxy returned invalid response: ${msg}`)\n .onSuccess((parsed) => {\n const models: IAiModelInfo[] = parsed.models.map((m) => ({\n id: m.id,\n capabilities: new Set<AiModelCapability>(m.capabilities),\n ...(m.displayName !== undefined ? { displayName: m.displayName } : {})\n }));\n return succeed(models);\n });\n}\n"]}
|
|
@@ -51,6 +51,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
|
|
|
51
51
|
*/
|
|
52
52
|
import { succeed, Validators } from '@fgv/ts-utils';
|
|
53
53
|
import { buildAnthropicMessages } from '../chatRequestBuilders';
|
|
54
|
+
import { anthropicAuthHeaders } from '../endpoint';
|
|
54
55
|
import { DEFAULT_ANTHROPIC_MAX_TOKENS } from '../model';
|
|
55
56
|
import { parseSseEventJson, readSseEvents } from '../sseParser';
|
|
56
57
|
import { toAnthropicTools } from '../toolFormats';
|
|
@@ -362,11 +363,7 @@ export async function callAnthropicStream(config, prompt, messagesBefore, temper
|
|
|
362
363
|
if (tools && tools.length > 0) {
|
|
363
364
|
body.tools = toAnthropicTools(tools);
|
|
364
365
|
}
|
|
365
|
-
const headers =
|
|
366
|
-
'x-api-key': config.apiKey,
|
|
367
|
-
'anthropic-version': '2023-06-01',
|
|
368
|
-
'anthropic-dangerous-direct-browser-access': 'true'
|
|
369
|
-
};
|
|
366
|
+
const headers = anthropicAuthHeaders(config.apiKey);
|
|
370
367
|
/* c8 ignore next 4 - optional logger diagnostic output */
|
|
371
368
|
if (logger) {
|
|
372
369
|
const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;;;;;;;;;;;;;;;;;;;AAEZ;;;;;;;;;;;GAWG;AAEH,OAAO,EAAwB,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAG1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EAEL,4BAA4B,EAI7B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,6BAA6B,EAAgC,MAAM,4BAA4B,CAAC;AACzG,OAAO,EAEL,2BAA2B,EAC3B,2BAA2B,EAC3B,qCAAqC,EACrC,iBAAiB,EACjB,oBAAoB,EACrB,MAAM,UAAU,CAAC;AAiIlB,MAAM,0BAA0B,GAK3B,UAAU,CAAC,MAAM,CACpB;IACE,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,EAAE,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,E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ourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for the Anthropic Messages API. Handles server tool\n * use (e.g. `web_search`) as unified `tool-event` markers and client-defined\n * tool calls (type `tool_use`) with B4 thinking-block accumulation.\n *\n * The ordered accumulation buffer preserves all content blocks from the\n * assistant turn in their original stream positions. The C3 continuation\n * builder reads this buffer to reconstruct the assistant turn for the\n * follow-up request.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport {\n AiPrompt,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type AiToolConfig,\n type IAiStreamEvent,\n type IChatMessage\n} from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport {\n IStreamApiConfig,\n MALFORMED_TOOL_USE_WARN_TAG,\n UNRECOGNIZED_EVENT_WARN_TAG,\n formatUnrecognizedEventPayloadPreview,\n openSseConnection,\n validateEventPayload\n} from './common';\n\n// ============================================================================\n// Accumulated block types (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated `thinking` block from the assistant turn. The `thinking` text\n * and `signature` are both concatenated across their respective delta events.\n * The full block is passed to the C3 continuation builder for round-trip preservation.\n * @internal\n */\nexport interface IAccumulatedThinkingBlock {\n readonly type: 'thinking';\n thinking: string;\n signature: string;\n}\n\n/**\n * An accumulated `redacted_thinking` block from the assistant turn. The `data`\n * field is opaque and arrives complete in the `content_block_start` event — no\n * delta events follow. Passed through unmodified to the C3 continuation builder.\n * @internal\n */\nexport interface IAccumulatedRedactedThinkingBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\n/**\n * An accumulated `text` block from the assistant turn.\n * @internal\n */\nexport interface IAccumulatedTextBlock {\n readonly type: 'text';\n text: string;\n}\n\n/**\n * An accumulated `tool_use` block from the assistant turn (client-defined tool call).\n * The `argsBuffer` is the concatenation of all `input_json_delta` chunks.\n * @internal\n */\nexport interface IAccumulatedToolUseBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n argsBuffer: string;\n}\n\n/**\n * Discriminated union of all accumulated Anthropic content block types.\n * The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed\n * by the SSE `index` field from `content_block_start` events.\n * @internal\n */\nexport type IAccumulatedBlock =\n | IAccumulatedThinkingBlock\n | IAccumulatedRedactedThinkingBlock\n | IAccumulatedTextBlock\n | IAccumulatedToolUseBlock;\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event with the `index` field.\n * The `index` field is optional for backward compatibility with providers that\n * omit it; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly index?: number;\n readonly content_block: {\n readonly type?: string;\n readonly name?: string;\n readonly id?: string;\n readonly data?: string;\n };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. Various delta types are\n * discriminated on `delta.type`:\n * - `text_delta`: text content\n * - `input_json_delta`: tool argument accumulation\n * - `thinking_delta`: thinking text accumulation\n * - `signature_delta`: thinking signature accumulation (MUST be appended, not overwritten)\n *\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly index?: number;\n readonly delta: {\n readonly type?: string;\n readonly text?: string;\n readonly partial_json?: string;\n readonly thinking?: string;\n readonly signature?: string;\n };\n}\n\n/**\n * Payload of a `content_block_stop` SSE event.\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStopPayload {\n readonly index?: number;\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{\n type?: string;\n name?: string;\n id?: string;\n data?: string;\n}> = Validators.object<{ type?: string; name?: string; id?: string; data?: string }>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional(),\n id: Validators.string.optional(),\n data: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name', 'id', 'data'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>(\n {\n index: Validators.number.optional(),\n content_block: anthropicContentBlockInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockDeltaInner: Validator<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}> = Validators.object<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional(),\n partial_json: Validators.string.optional(),\n thinking: Validators.string.optional(),\n signature: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>(\n {\n index: Validators.number.optional(),\n delta: anthropicContentBlockDeltaInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockStopPayload: Validator<IAnthropicContentBlockStopPayload> =\n Validators.object<IAnthropicContentBlockStopPayload>(\n { index: Validators.number.optional() },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a\n * one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's\n * `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set\n * when a new event type is observed and confirmed safe to ignore.\n *\n * @internal\n */\nconst RECOGNIZED_ANTHROPIC_EVENTS: ReadonlySet<string> = new Set<string>([\n // ---- handled by the translator ----\n 'content_block_start',\n 'content_block_delta',\n 'content_block_stop',\n 'message_delta',\n 'message_stop',\n 'error',\n // ---- lifecycle / heartbeats: intentionally silent ----\n 'message_start',\n 'ping'\n]);\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * Maintains an ordered accumulation buffer (keyed by SSE `index`) for all\n * content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.\n * The buffer is available on the returned generator via `.accumulationBuffer`.\n *\n * Unrecognized event names are reported once per stream via `logger?.warn` —\n * see {@link RECOGNIZED_ANTHROPIC_EVENTS}.\n *\n * @internal\n */\nasync function* translateAnthropicStream(\n response: Response,\n accumulationBuffer: Map<number, IAccumulatedBlock>,\n logger?: Logging.ILogger\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n // Track unrecognized event names we have already warned about, so a hot stream of\n // an unknown event type produces exactly one log line per name per stream.\n const warnedEvents = new Set<string>();\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawIndex, content_block: block } = payload;\n const index = rawIndex ?? 0;\n\n if (block.type === 'thinking') {\n accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });\n } else if (block.type === 'redacted_thinking') {\n accumulationBuffer.set(index, {\n type: 'redacted_thinking',\n /* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */\n data: block.data ?? ''\n });\n } else if (block.type === 'text') {\n accumulationBuffer.set(index, { type: 'text', text: '' });\n } else if (block.type === 'tool_use') {\n // A tool_use block_start MUST carry a non-empty id and name: the id is the\n // sole correlation key for the follow-up tool_result, and dropping the block\n // silently (then ignoring its input_json_delta chunks at the delta handler\n // below) is exactly how an orphaned block leaves the harness without a clean\n // id and corrupts the continuation. Surface it loudly instead of dropping it.\n if (block.id && block.name) {\n accumulationBuffer.set(index, {\n type: 'tool_use',\n id: block.id,\n name: block.name,\n argsBuffer: ''\n });\n yield { type: 'client-tool-call-start', toolName: block.name, callId: block.id };\n } else {\n logger?.warn(\n `${MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +\n `at index ${index} is missing a usable id and/or name ` +\n `(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +\n `No client tool call will be issued for this block; its argument deltas are dropped. ` +\n `This usually indicates provider drift or a truncated stream.`\n );\n }\n } else if (block.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawDeltaIndex, delta } = payload;\n const index = rawDeltaIndex ?? 0;\n const block = accumulationBuffer.get(index);\n\n if (delta.type === 'text_delta' && typeof delta.text === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'text') {\n block.text += delta.text;\n }\n if (delta.text.length > 0) {\n fullText += delta.text;\n yield { type: 'text-delta', delta: delta.text };\n }\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'tool_use') {\n block.argsBuffer += delta.partial_json;\n }\n } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.thinking += delta.thinking;\n }\n } else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {\n // CRITICAL (E5): signature must be APPENDED, not overwritten.\n // The signature is base64 arriving in multiple chunks.\n // Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.signature += delta.signature;\n }\n }\n } else if (eventName === 'content_block_stop') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStopPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n /* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */\n const block = accumulationBuffer.get(payload.index ?? 0);\n /* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */\n if (block?.type === 'tool_use') {\n let args: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */\n const parsed = JSON.parse(block.argsBuffer || '{}') as unknown;\n /* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */\n args =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : {};\n } catch {\n args = {};\n }\n /* c8 ignore stop */\n yield { type: 'client-tool-call-done', toolName: block.name, callId: block.id, args };\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n } else if (\n typeof eventName === 'string' &&\n !RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&\n !warnedEvents.has(eventName)\n ) {\n // Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time\n // warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either\n // handled or confirmed safe to ignore.\n warnedEvents.add(eventName);\n logger?.warn(\n `${UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +\n `'${eventName}'. ` +\n `payload preview: ${formatUnrecognizedEventPayloadPreview(message.data)}. ` +\n `This may indicate provider drift — if the new event carries data the adapter ` +\n `should surface, add a handler; otherwise add the name to ` +\n `RECOGNIZED_ANTHROPIC_EVENTS.`\n );\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n accumulationBuffer?: Map<number, IAccumulatedBlock>,\n continuationMessages?: ReadonlyArray<JsonObject>,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n // Anthropic's Messages API requires max_tokens on every request — see\n // AiAssist.DEFAULT_ANTHROPIC_MAX_TOKENS for why only this provider defaults it.\n max_tokens: maxTokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS,\n stream: true\n };\n // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When\n // thinking is active it is also rejected — the completion/streaming paths validate this upstream,\n // and the effort gate here is the safety net for the (unguarded) client-tool path.\n if (resolvedThinking?.anthropicEffort === undefined) {\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n }\n if (resolvedThinking?.anthropicEffort !== undefined) {\n if (useAdaptiveThinking) {\n // Claude 5 family: adaptive thinking — no budget_tokens; effort moves to the\n // top-level output_config block. See AiAssist.isAdaptiveThinkingModel.\n body.thinking = { type: 'adaptive' };\n body.output_config = { effort: resolvedThinking.anthropicEffort };\n } else {\n body.thinking = {\n type: 'enabled',\n budget_tokens: anthropicEffortToBudgetTokens(resolvedThinking.anthropicEffort)\n };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = {\n 'x-api-key': config.apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true'\n };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const buffer = accumulationBuffer ?? new Map<number, IAccumulatedBlock>();\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response, buffer, logger)));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AA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,CAAC,MAAM,CAAC,CAAC;IAC5E,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,8BAA8B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,MAAM,GAAG,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,IAAI,GAAG,EAA6B,CAAC;IAC1E,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;AACnG,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for the Anthropic Messages API. Handles server tool\n * use (e.g. `web_search`) as unified `tool-event` markers and client-defined\n * tool calls (type `tool_use`) with B4 thinking-block accumulation.\n *\n * The ordered accumulation buffer preserves all content blocks from the\n * assistant turn in their original stream positions. The C3 continuation\n * builder reads this buffer to reconstruct the assistant turn for the\n * follow-up request.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport { anthropicAuthHeaders } from '../endpoint';\nimport {\n AiPrompt,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type AiToolConfig,\n type IAiStreamEvent,\n type IChatMessage\n} from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport {\n IStreamApiConfig,\n MALFORMED_TOOL_USE_WARN_TAG,\n UNRECOGNIZED_EVENT_WARN_TAG,\n formatUnrecognizedEventPayloadPreview,\n openSseConnection,\n validateEventPayload\n} from './common';\n\n// ============================================================================\n// Accumulated block types (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated `thinking` block from the assistant turn. The `thinking` text\n * and `signature` are both concatenated across their respective delta events.\n * The full block is passed to the C3 continuation builder for round-trip preservation.\n * @internal\n */\nexport interface IAccumulatedThinkingBlock {\n readonly type: 'thinking';\n thinking: string;\n signature: string;\n}\n\n/**\n * An accumulated `redacted_thinking` block from the assistant turn. The `data`\n * field is opaque and arrives complete in the `content_block_start` event — no\n * delta events follow. Passed through unmodified to the C3 continuation builder.\n * @internal\n */\nexport interface IAccumulatedRedactedThinkingBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\n/**\n * An accumulated `text` block from the assistant turn.\n * @internal\n */\nexport interface IAccumulatedTextBlock {\n readonly type: 'text';\n text: string;\n}\n\n/**\n * An accumulated `tool_use` block from the assistant turn (client-defined tool call).\n * The `argsBuffer` is the concatenation of all `input_json_delta` chunks.\n * @internal\n */\nexport interface IAccumulatedToolUseBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n argsBuffer: string;\n}\n\n/**\n * Discriminated union of all accumulated Anthropic content block types.\n * The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed\n * by the SSE `index` field from `content_block_start` events.\n * @internal\n */\nexport type IAccumulatedBlock =\n | IAccumulatedThinkingBlock\n | IAccumulatedRedactedThinkingBlock\n | IAccumulatedTextBlock\n | IAccumulatedToolUseBlock;\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event with the `index` field.\n * The `index` field is optional for backward compatibility with providers that\n * omit it; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly index?: number;\n readonly content_block: {\n readonly type?: string;\n readonly name?: string;\n readonly id?: string;\n readonly data?: string;\n };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. Various delta types are\n * discriminated on `delta.type`:\n * - `text_delta`: text content\n * - `input_json_delta`: tool argument accumulation\n * - `thinking_delta`: thinking text accumulation\n * - `signature_delta`: thinking signature accumulation (MUST be appended, not overwritten)\n *\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly index?: number;\n readonly delta: {\n readonly type?: string;\n readonly text?: string;\n readonly partial_json?: string;\n readonly thinking?: string;\n readonly signature?: string;\n };\n}\n\n/**\n * Payload of a `content_block_stop` SSE event.\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStopPayload {\n readonly index?: number;\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{\n type?: string;\n name?: string;\n id?: string;\n data?: string;\n}> = Validators.object<{ type?: string; name?: string; id?: string; data?: string }>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional(),\n id: Validators.string.optional(),\n data: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name', 'id', 'data'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>(\n {\n index: Validators.number.optional(),\n content_block: anthropicContentBlockInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockDeltaInner: Validator<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}> = Validators.object<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional(),\n partial_json: Validators.string.optional(),\n thinking: Validators.string.optional(),\n signature: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>(\n {\n index: Validators.number.optional(),\n delta: anthropicContentBlockDeltaInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockStopPayload: Validator<IAnthropicContentBlockStopPayload> =\n Validators.object<IAnthropicContentBlockStopPayload>(\n { index: Validators.number.optional() },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a\n * one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's\n * `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set\n * when a new event type is observed and confirmed safe to ignore.\n *\n * @internal\n */\nconst RECOGNIZED_ANTHROPIC_EVENTS: ReadonlySet<string> = new Set<string>([\n // ---- handled by the translator ----\n 'content_block_start',\n 'content_block_delta',\n 'content_block_stop',\n 'message_delta',\n 'message_stop',\n 'error',\n // ---- lifecycle / heartbeats: intentionally silent ----\n 'message_start',\n 'ping'\n]);\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * Maintains an ordered accumulation buffer (keyed by SSE `index`) for all\n * content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.\n * The buffer is available on the returned generator via `.accumulationBuffer`.\n *\n * Unrecognized event names are reported once per stream via `logger?.warn` —\n * see {@link RECOGNIZED_ANTHROPIC_EVENTS}.\n *\n * @internal\n */\nasync function* translateAnthropicStream(\n response: Response,\n accumulationBuffer: Map<number, IAccumulatedBlock>,\n logger?: Logging.ILogger\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n // Track unrecognized event names we have already warned about, so a hot stream of\n // an unknown event type produces exactly one log line per name per stream.\n const warnedEvents = new Set<string>();\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawIndex, content_block: block } = payload;\n const index = rawIndex ?? 0;\n\n if (block.type === 'thinking') {\n accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });\n } else if (block.type === 'redacted_thinking') {\n accumulationBuffer.set(index, {\n type: 'redacted_thinking',\n /* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */\n data: block.data ?? ''\n });\n } else if (block.type === 'text') {\n accumulationBuffer.set(index, { type: 'text', text: '' });\n } else if (block.type === 'tool_use') {\n // A tool_use block_start MUST carry a non-empty id and name: the id is the\n // sole correlation key for the follow-up tool_result, and dropping the block\n // silently (then ignoring its input_json_delta chunks at the delta handler\n // below) is exactly how an orphaned block leaves the harness without a clean\n // id and corrupts the continuation. Surface it loudly instead of dropping it.\n if (block.id && block.name) {\n accumulationBuffer.set(index, {\n type: 'tool_use',\n id: block.id,\n name: block.name,\n argsBuffer: ''\n });\n yield { type: 'client-tool-call-start', toolName: block.name, callId: block.id };\n } else {\n logger?.warn(\n `${MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +\n `at index ${index} is missing a usable id and/or name ` +\n `(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +\n `No client tool call will be issued for this block; its argument deltas are dropped. ` +\n `This usually indicates provider drift or a truncated stream.`\n );\n }\n } else if (block.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawDeltaIndex, delta } = payload;\n const index = rawDeltaIndex ?? 0;\n const block = accumulationBuffer.get(index);\n\n if (delta.type === 'text_delta' && typeof delta.text === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'text') {\n block.text += delta.text;\n }\n if (delta.text.length > 0) {\n fullText += delta.text;\n yield { type: 'text-delta', delta: delta.text };\n }\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'tool_use') {\n block.argsBuffer += delta.partial_json;\n }\n } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.thinking += delta.thinking;\n }\n } else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {\n // CRITICAL (E5): signature must be APPENDED, not overwritten.\n // The signature is base64 arriving in multiple chunks.\n // Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.signature += delta.signature;\n }\n }\n } else if (eventName === 'content_block_stop') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStopPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n /* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */\n const block = accumulationBuffer.get(payload.index ?? 0);\n /* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */\n if (block?.type === 'tool_use') {\n let args: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */\n const parsed = JSON.parse(block.argsBuffer || '{}') as unknown;\n /* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */\n args =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : {};\n } catch {\n args = {};\n }\n /* c8 ignore stop */\n yield { type: 'client-tool-call-done', toolName: block.name, callId: block.id, args };\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n } else if (\n typeof eventName === 'string' &&\n !RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&\n !warnedEvents.has(eventName)\n ) {\n // Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time\n // warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either\n // handled or confirmed safe to ignore.\n warnedEvents.add(eventName);\n logger?.warn(\n `${UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +\n `'${eventName}'. ` +\n `payload preview: ${formatUnrecognizedEventPayloadPreview(message.data)}. ` +\n `This may indicate provider drift — if the new event carries data the adapter ` +\n `should surface, add a handler; otherwise add the name to ` +\n `RECOGNIZED_ANTHROPIC_EVENTS.`\n );\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n accumulationBuffer?: Map<number, IAccumulatedBlock>,\n continuationMessages?: ReadonlyArray<JsonObject>,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n // Anthropic's Messages API requires max_tokens on every request — see\n // AiAssist.DEFAULT_ANTHROPIC_MAX_TOKENS for why only this provider defaults it.\n max_tokens: maxTokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS,\n stream: true\n };\n // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When\n // thinking is active it is also rejected — the completion/streaming paths validate this upstream,\n // and the effort gate here is the safety net for the (unguarded) client-tool path.\n if (resolvedThinking?.anthropicEffort === undefined) {\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n }\n if (resolvedThinking?.anthropicEffort !== undefined) {\n if (useAdaptiveThinking) {\n // Claude 5 family: adaptive thinking — no budget_tokens; effort moves to the\n // top-level output_config block. See AiAssist.isAdaptiveThinkingModel.\n body.thinking = { type: 'adaptive' };\n body.output_config = { effort: resolvedThinking.anthropicEffort };\n } else {\n body.thinking = {\n type: 'enabled',\n budget_tokens: anthropicEffortToBudgetTokens(resolvedThinking.anthropicEffort)\n };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const buffer = accumulationBuffer ?? new Map<number, IAccumulatedBlock>();\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response, buffer, logger)));\n}\n"]}
|
|
@@ -51,6 +51,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
|
|
|
51
51
|
import { succeed, Validators } from '@fgv/ts-utils';
|
|
52
52
|
import { isJsonObject } from '@fgv/ts-json-base';
|
|
53
53
|
import { buildGeminiContents } from '../chatRequestBuilders';
|
|
54
|
+
import { geminiAuthHeader } from '../endpoint';
|
|
54
55
|
import { parseSseEventJson, readSseEvents } from '../sseParser';
|
|
55
56
|
import { toGeminiTools } from '../toolFormats';
|
|
56
57
|
import { openSseConnection, validateEventPayload } from './common';
|
|
@@ -194,7 +195,7 @@ export async function callGeminiStream(config, prompt, messagesBefore, temperatu
|
|
|
194
195
|
if (tools && tools.length > 0) {
|
|
195
196
|
body.tools = toGeminiTools(tools);
|
|
196
197
|
}
|
|
197
|
-
const headers =
|
|
198
|
+
const headers = geminiAuthHeader(config.apiKey);
|
|
198
199
|
/* c8 ignore next 4 - optional logger diagnostic output */
|
|
199
200
|
if (logger) {
|
|
200
201
|
const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';
|