@fgv/ts-extras 5.1.0-52 → 5.1.0-53
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 +147 -19
- package/dist/packlets/ai-assist/completionClient.js.map +1 -1
- package/dist/packlets/ai-assist/index.js +2 -1
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +20 -2
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/dist/packlets/ai-assist/model.js.map +1 -1
- package/dist/packlets/ai-assist/registry.js +39 -1
- package/dist/packlets/ai-assist/registry.js.map +1 -1
- package/dist/packlets/ai-assist/structuredOutput.js +315 -0
- package/dist/packlets/ai-assist/structuredOutput.js.map +1 -0
- package/dist/packlets/ai-assist/structuredOutputTypes.js +21 -0
- package/dist/packlets/ai-assist/structuredOutputTypes.js.map +1 -0
- package/dist/ts-extras.d.ts +229 -2
- package/lib/packlets/ai-assist/completionClient.d.ts +13 -0
- package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/completionClient.js +146 -18
- package/lib/packlets/ai-assist/completionClient.js.map +1 -1
- 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 +6 -2
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.js +20 -2
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/lib/packlets/ai-assist/model.d.ts +38 -2
- package/lib/packlets/ai-assist/model.d.ts.map +1 -1
- package/lib/packlets/ai-assist/model.js.map +1 -1
- package/lib/packlets/ai-assist/registry.d.ts +20 -0
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
- package/lib/packlets/ai-assist/registry.js +41 -1
- package/lib/packlets/ai-assist/registry.js.map +1 -1
- package/lib/packlets/ai-assist/structuredOutput.d.ts +88 -0
- package/lib/packlets/ai-assist/structuredOutput.d.ts.map +1 -0
- package/lib/packlets/ai-assist/structuredOutput.js +321 -0
- package/lib/packlets/ai-assist/structuredOutput.js.map +1 -0
- package/lib/packlets/ai-assist/structuredOutputTypes.d.ts +142 -0
- package/lib/packlets/ai-assist/structuredOutputTypes.d.ts.map +1 -0
- package/lib/packlets/ai-assist/structuredOutputTypes.js +22 -0
- package/lib/packlets/ai-assist/structuredOutputTypes.js.map +1 -0
- package/package.json +7 -7
|
@@ -17,13 +17,15 @@
|
|
|
17
17
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
18
|
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
19
|
// SOFTWARE.
|
|
20
|
-
import { fail, succeed, Validators } from '@fgv/ts-utils';
|
|
20
|
+
import { captureResult, fail, succeed, Validators } from '@fgv/ts-utils';
|
|
21
21
|
import { DEFAULT_ANTHROPIC_MAX_TOKENS, isAdaptiveThinkingModel, isResponsesOnlyModel, resolveProviderModel, usesMaxCompletionTokensField } from './model';
|
|
22
22
|
import { anthropicEffortToBudgetTokens, checkTemperatureConflict, mergeThinkingConfig, providerDiscriminatorForId } from './thinkingOptionsResolver';
|
|
23
23
|
import { buildAnthropicMessages, buildGeminiContents, buildMessages, buildOpenAiChatUserContent, buildOpenAiResponsesUserContent, normalizeOutboundMessages, splitChatRequest } from './chatRequestBuilders';
|
|
24
24
|
import { anthropicAuthHeaders, bearerAuthHeader, geminiAuthHeader, resolveEffectiveBaseUrl } from './endpoint';
|
|
25
25
|
import { fetchJson } from './http';
|
|
26
26
|
import { toAnthropicTools, toGeminiTools, toResponsesApiTools } from './toolFormats';
|
|
27
|
+
import { ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME, NO_STRUCTURED_OUTPUT, isStructuredOutputEnforcement, resolveStructuredOutput } from './structuredOutput';
|
|
28
|
+
import { resolveStructuredOutputCapability } from './registry';
|
|
27
29
|
const openAiMessage = Validators.object({
|
|
28
30
|
content: Validators.string
|
|
29
31
|
});
|
|
@@ -69,7 +71,7 @@ const geminiResponse = Validators.object({
|
|
|
69
71
|
* Works for xAI Grok, OpenAI, Groq, and Mistral.
|
|
70
72
|
* @internal
|
|
71
73
|
*/
|
|
72
|
-
async function callOpenAiCompletion(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, useMaxCompletionTokensField = false) {
|
|
74
|
+
async function callOpenAiCompletion(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, useMaxCompletionTokensField = false, structured = NO_STRUCTURED_OUTPUT) {
|
|
73
75
|
var _a;
|
|
74
76
|
const url = `${config.baseUrl}/chat/completions`;
|
|
75
77
|
const messages = buildMessages(prompt.system, buildOpenAiChatUserContent(prompt), {
|
|
@@ -81,6 +83,7 @@ async function callOpenAiCompletion(config, prompt, head, temperature, logger, s
|
|
|
81
83
|
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
|
|
82
84
|
Object.assign(body, resolvedThinking.otherParams);
|
|
83
85
|
}
|
|
86
|
+
Object.assign(body, structured.wire);
|
|
84
87
|
const headers = bearerAuthHeader(config.apiKey);
|
|
85
88
|
/* c8 ignore next 1 - optional logger */
|
|
86
89
|
logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI completion: model=${config.model}`);
|
|
@@ -95,7 +98,8 @@ async function callOpenAiCompletion(config, prompt, head, temperature, logger, s
|
|
|
95
98
|
const choice = response.choices[0];
|
|
96
99
|
return succeed({
|
|
97
100
|
content: choice.message.content,
|
|
98
|
-
truncated: choice.finish_reason === 'length'
|
|
101
|
+
truncated: choice.finish_reason === 'length',
|
|
102
|
+
structuredOutput: structured.enforcement
|
|
99
103
|
});
|
|
100
104
|
});
|
|
101
105
|
}
|
|
@@ -123,7 +127,7 @@ function extractResponsesApiText(output) {
|
|
|
123
127
|
* Used when tools are configured for an openai-format provider.
|
|
124
128
|
* @internal
|
|
125
129
|
*/
|
|
126
|
-
async function callOpenAiResponsesCompletion(config, prompt, tools = [], head, temperature, logger, signal, resolvedThinking, maxTokens) {
|
|
130
|
+
async function callOpenAiResponsesCompletion(config, prompt, tools = [], head, temperature, logger, signal, resolvedThinking, maxTokens, structured = NO_STRUCTURED_OUTPUT) {
|
|
127
131
|
var _a;
|
|
128
132
|
const url = `${config.baseUrl}/responses`;
|
|
129
133
|
const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {
|
|
@@ -138,6 +142,7 @@ async function callOpenAiResponsesCompletion(config, prompt, tools = [], head, t
|
|
|
138
142
|
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
|
|
139
143
|
Object.assign(body, resolvedThinking.otherParams);
|
|
140
144
|
}
|
|
145
|
+
Object.assign(body, structured.wire);
|
|
141
146
|
const headers = bearerAuthHeader(config.apiKey);
|
|
142
147
|
/* c8 ignore next 1 - optional logger */
|
|
143
148
|
logger === null || logger === void 0 ? void 0 : logger.info(`OpenAI Responses API: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);
|
|
@@ -151,7 +156,8 @@ async function callOpenAiResponsesCompletion(config, prompt, tools = [], head, t
|
|
|
151
156
|
.onSuccess((response) => {
|
|
152
157
|
return extractResponsesApiText(response.output).onSuccess((text) => succeed({
|
|
153
158
|
content: text,
|
|
154
|
-
truncated: response.status === 'incomplete'
|
|
159
|
+
truncated: response.status === 'incomplete',
|
|
160
|
+
structuredOutput: structured.enforcement
|
|
155
161
|
}));
|
|
156
162
|
});
|
|
157
163
|
}
|
|
@@ -180,8 +186,45 @@ function extractAnthropicText(content) {
|
|
|
180
186
|
}
|
|
181
187
|
return succeed(textParts.join(''));
|
|
182
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Extracts the forced structured-output tool's input from Anthropic response
|
|
191
|
+
* content blocks and re-serializes it.
|
|
192
|
+
*
|
|
193
|
+
* @remarks
|
|
194
|
+
* Under `'tool-forced'` enforcement the model's answer arrives as a `tool_use`
|
|
195
|
+
* block's `input` — a parsed object — rather than as text. Re-serializing it here
|
|
196
|
+
* keeps `IAiCompletionResponse.content` a JSON **string** on every provider, so a
|
|
197
|
+
* caller's converter is written once and does not branch on which enforcement it
|
|
198
|
+
* got. A useful side effect: the string is produced by `JSON.stringify` rather
|
|
199
|
+
* than by the model, so under this enforcement it is syntactically valid by
|
|
200
|
+
* construction.
|
|
201
|
+
* @internal
|
|
202
|
+
*/
|
|
203
|
+
function extractAnthropicStructuredOutput(content) {
|
|
204
|
+
for (const block of content) {
|
|
205
|
+
if (typeof block === 'object' && block !== null && 'type' in block) {
|
|
206
|
+
const typed = block;
|
|
207
|
+
if (typed.type === 'tool_use' && typed.name === ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME) {
|
|
208
|
+
// `JSON.stringify` returns `undefined` — not a string, and not a throw —
|
|
209
|
+
// for `undefined` and for a function or symbol. `captureResult` would wrap
|
|
210
|
+
// that as a Success, putting `undefined` behind a `content: string`
|
|
211
|
+
// contract with nothing to catch it downstream. A `tool_use` block with no
|
|
212
|
+
// `input` is exactly that case.
|
|
213
|
+
return captureResult(() => JSON.stringify(typed.input))
|
|
214
|
+
.withErrorFormat((msg) => `Anthropic API response: structured output could not be serialized: ${msg}`)
|
|
215
|
+
.onSuccess((json) => typeof json === 'string'
|
|
216
|
+
? succeed(json)
|
|
217
|
+
: fail(`Anthropic API response: forced tool '${ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME}' returned no serializable input`));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// Loud rather than a silent fall back to text: we forced the tool, so its
|
|
222
|
+
// absence means the request did not do what the response is about to claim it
|
|
223
|
+
// did — and `structuredOutput: 'tool-forced'` would then be a lie.
|
|
224
|
+
return fail(`Anthropic API response: structured output was forced but no '${ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME}' tool_use block was returned`);
|
|
225
|
+
}
|
|
183
226
|
/** Calls the Anthropic Messages API with optional tool support. @internal */
|
|
184
|
-
async function callAnthropicCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, useAdaptiveThinking = false, maxTokens) {
|
|
227
|
+
async function callAnthropicCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, useAdaptiveThinking = false, maxTokens, structured = NO_STRUCTURED_OUTPUT) {
|
|
185
228
|
const url = `${config.baseUrl}/messages`;
|
|
186
229
|
const messages = buildAnthropicMessages(prompt, { head });
|
|
187
230
|
const body = Object.assign({ model: config.model, system: prompt.system, messages,
|
|
@@ -203,6 +246,22 @@ async function callAnthropicCompletion(config, prompt, head, temperature, logger
|
|
|
203
246
|
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
|
|
204
247
|
Object.assign(body, resolvedThinking.otherParams);
|
|
205
248
|
}
|
|
249
|
+
// The structured-output wire carries `tools` + `tool_choice` of its own, so the
|
|
250
|
+
// server-tool assignment below would clobber it. `resolveStructuredOutput`
|
|
251
|
+
// refuses that combination up front, which is what makes the two mutually
|
|
252
|
+
// exclusive — but that is an invariant held in a DIFFERENT FILE, and a future
|
|
253
|
+
// second Anthropic capability entry (or a relaxed conflict guard) would
|
|
254
|
+
// reintroduce silent clobbering with nothing failing at this line. So assert it
|
|
255
|
+
// here rather than trusting a comment across a file boundary.
|
|
256
|
+
// Unreachable through the public API — resolveStructuredOutput refuses this
|
|
257
|
+
// combination before dispatch — and unreachable BY DESIGN: it cannot be
|
|
258
|
+
// exercised without first breaking the very thing it guards against.
|
|
259
|
+
/* c8 ignore next 6 - defensive: internal consistency check, see above */
|
|
260
|
+
if (structured.enforcement === 'tool-forced' && tools !== undefined && tools.length > 0) {
|
|
261
|
+
return fail(`Anthropic completion: structured output and server-side tools both claim the tools channel; ` +
|
|
262
|
+
`this combination must be refused before reaching the adapter`);
|
|
263
|
+
}
|
|
264
|
+
Object.assign(body, structured.wire);
|
|
206
265
|
if (tools && tools.length > 0) {
|
|
207
266
|
body.tools = toAnthropicTools(tools);
|
|
208
267
|
/* c8 ignore next 3 - optional logger diagnostic output */
|
|
@@ -225,9 +284,13 @@ async function callAnthropicCompletion(config, prompt, head, temperature, logger
|
|
|
225
284
|
if (typeof stopReason !== 'string') {
|
|
226
285
|
return fail('Anthropic API response: stop_reason is missing or not a string');
|
|
227
286
|
}
|
|
228
|
-
|
|
287
|
+
const extracted = structured.enforcement === 'tool-forced'
|
|
288
|
+
? extractAnthropicStructuredOutput(rawContent)
|
|
289
|
+
: extractAnthropicText(rawContent);
|
|
290
|
+
return extracted.onSuccess((text) => succeed({
|
|
229
291
|
content: text,
|
|
230
|
-
truncated: stopReason === 'max_tokens'
|
|
292
|
+
truncated: stopReason === 'max_tokens',
|
|
293
|
+
structuredOutput: structured.enforcement
|
|
231
294
|
}));
|
|
232
295
|
}
|
|
233
296
|
// ============================================================================
|
|
@@ -238,7 +301,7 @@ async function callAnthropicCompletion(config, prompt, head, temperature, logger
|
|
|
238
301
|
* When tools are configured, includes Google Search grounding.
|
|
239
302
|
* @internal
|
|
240
303
|
*/
|
|
241
|
-
async function callGeminiCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, maxTokens) {
|
|
304
|
+
async function callGeminiCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, maxTokens, structured = NO_STRUCTURED_OUTPUT) {
|
|
242
305
|
const url = `${config.baseUrl}/models/${config.model}:generateContent`;
|
|
243
306
|
const contents = buildGeminiContents(prompt, { head });
|
|
244
307
|
// Temperature is sent only when explicitly provided; otherwise Gemini's default applies.
|
|
@@ -255,6 +318,8 @@ async function callGeminiCompletion(config, prompt, head, temperature, logger, t
|
|
|
255
318
|
if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
|
|
256
319
|
Object.assign(generationConfig, resolvedThinking.otherParams);
|
|
257
320
|
}
|
|
321
|
+
// Gemini nests the constraint INSIDE generationConfig, not on the body.
|
|
322
|
+
Object.assign(generationConfig, structured.wire);
|
|
258
323
|
const body = {
|
|
259
324
|
systemInstruction: { parts: [{ text: prompt.system }] },
|
|
260
325
|
contents,
|
|
@@ -280,8 +345,15 @@ async function callGeminiCompletion(config, prompt, head, temperature, logger, t
|
|
|
280
345
|
.onSuccess((response) => {
|
|
281
346
|
const candidate = response.candidates[0];
|
|
282
347
|
return succeed({
|
|
283
|
-
|
|
284
|
-
|
|
348
|
+
// ALL parts, not `parts[0]`. Gemini may split one reply across several
|
|
349
|
+
// text parts, and reading only the first silently discards the rest —
|
|
350
|
+
// yielding a truncated document that often still parses, which is the
|
|
351
|
+
// worst way to be wrong. The streaming adapter has always concatenated
|
|
352
|
+
// (`fullText += part.text`); this path did not, so the same response gave
|
|
353
|
+
// different text depending on which one you called.
|
|
354
|
+
content: candidate.content.parts.map((part) => part.text).join(''),
|
|
355
|
+
truncated: candidate.finishReason === 'MAX_TOKENS',
|
|
356
|
+
structuredOutput: structured.enforcement
|
|
285
357
|
});
|
|
286
358
|
});
|
|
287
359
|
}
|
|
@@ -295,7 +367,7 @@ async function callGeminiCompletion(config, prompt, head, temperature, logger, t
|
|
|
295
367
|
* @public
|
|
296
368
|
*/
|
|
297
369
|
export async function callProviderCompletion(params) {
|
|
298
|
-
const { descriptor, apiKey, system, messages, temperature, modelOverride, tier, logger, tools, signal, endpoint, thinking, maxTokens } = params;
|
|
370
|
+
const { descriptor, apiKey, system, messages, temperature, modelOverride, tier, logger, tools, signal, endpoint, thinking, maxTokens, structuredOutput } = params;
|
|
299
371
|
const splitResult = splitChatRequest(system, messages);
|
|
300
372
|
if (splitResult.isFailure()) {
|
|
301
373
|
return fail(splitResult.message);
|
|
@@ -333,6 +405,32 @@ export async function callProviderCompletion(params) {
|
|
|
333
405
|
}
|
|
334
406
|
}
|
|
335
407
|
}
|
|
408
|
+
// Resolved against the CONCRETE model, after resolveProviderModel — passing an
|
|
409
|
+
// alias here is the defect resolveImageCapability once had.
|
|
410
|
+
// The OpenAI route depends on tools AND the model, so it is computed here (once,
|
|
411
|
+
// beside the switch that uses it) and handed to the resolver — a capability keyed
|
|
412
|
+
// on the model alone cannot know which of the two OpenAI wire shapes applies.
|
|
413
|
+
const usesResponsesApi = descriptor.apiFormat === 'openai' && (hasTools || isResponsesOnlyModel(descriptor, model));
|
|
414
|
+
const structuredResult = resolveStructuredOutput(descriptor, model, structuredOutput, tools, usesResponsesApi, resolveStructuredOutputCapability);
|
|
415
|
+
if (structuredResult.isFailure()) {
|
|
416
|
+
return fail(structuredResult.message);
|
|
417
|
+
}
|
|
418
|
+
const resolvedStructured = structuredResult.value;
|
|
419
|
+
// OpenAI rejects `response_format: { type: 'json_object' }` with a 400 unless the
|
|
420
|
+
// conversation mentions JSON somewhere — a documented API rule, and one a caller
|
|
421
|
+
// has no way to discover from a schema-mode request that worked. Pre-empted with a
|
|
422
|
+
// named failure before the wire call, the same treatment the Gemini
|
|
423
|
+
// grounding-plus-function-calling conflict already gets. `generateJsonCompletion`
|
|
424
|
+
// satisfies it for free via its prompt hint; a direct caller may not.
|
|
425
|
+
if (resolvedStructured.enforcement === 'json-mode' && descriptor.apiFormat === 'openai') {
|
|
426
|
+
const mentionsJson = (system !== null && system !== void 0 ? system : '').toLowerCase().includes('json') ||
|
|
427
|
+
messages.some((m) => m.content.toLowerCase().includes('json'));
|
|
428
|
+
if (!mentionsJson) {
|
|
429
|
+
return fail(`provider '${descriptor.id}': json-object structured output requires the word 'json' to ` +
|
|
430
|
+
`appear in the system prompt or a message — OpenAI rejects the request otherwise. Mention ` +
|
|
431
|
+
`it, or use structuredOutput: { mode: 'schema', schema } which carries no such rule`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
336
434
|
const config = {
|
|
337
435
|
baseUrl: baseUrlResult.value,
|
|
338
436
|
apiKey,
|
|
@@ -349,14 +447,14 @@ export async function callProviderCompletion(params) {
|
|
|
349
447
|
case 'openai':
|
|
350
448
|
// Responses-API-only models (e.g. gpt-5.5-pro) 400 on /chat/completions, so they route
|
|
351
449
|
// to the Responses path even with no tools requested — same path the tools case uses.
|
|
352
|
-
if (
|
|
353
|
-
return callOpenAiResponsesCompletion(config, prompt, tools, head, temperature, logger, signal, resolvedThinking, maxTokens);
|
|
450
|
+
if (usesResponsesApi) {
|
|
451
|
+
return callOpenAiResponsesCompletion(config, prompt, tools, head, temperature, logger, signal, resolvedThinking, maxTokens, resolvedStructured);
|
|
354
452
|
}
|
|
355
|
-
return callOpenAiCompletion(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, usesMaxCompletionTokensField(descriptor));
|
|
453
|
+
return callOpenAiCompletion(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, usesMaxCompletionTokensField(descriptor), resolvedStructured);
|
|
356
454
|
case 'anthropic':
|
|
357
|
-
return callAnthropicCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, isAdaptiveThinkingModel(descriptor, config.model), maxTokens);
|
|
455
|
+
return callAnthropicCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, isAdaptiveThinkingModel(descriptor, config.model), maxTokens, resolvedStructured);
|
|
358
456
|
case 'gemini':
|
|
359
|
-
return callGeminiCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, maxTokens);
|
|
457
|
+
return callGeminiCompletion(config, prompt, head, temperature, logger, tools, signal, resolvedThinking, maxTokens, resolvedStructured);
|
|
360
458
|
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
361
459
|
default: {
|
|
362
460
|
const _exhaustive = descriptor.apiFormat;
|
|
@@ -378,7 +476,7 @@ export async function callProviderCompletion(params) {
|
|
|
378
476
|
* @public
|
|
379
477
|
*/
|
|
380
478
|
export async function callProxiedCompletion(proxyUrl, params) {
|
|
381
|
-
const { descriptor, apiKey, system, messages, temperature, modelOverride, logger, tools, signal, thinking, maxTokens } = params;
|
|
479
|
+
const { descriptor, apiKey, system, messages, temperature, modelOverride, logger, tools, signal, thinking, maxTokens, structuredOutput } = params;
|
|
382
480
|
const splitResult = splitChatRequest(system, messages);
|
|
383
481
|
if (splitResult.isFailure()) {
|
|
384
482
|
return fail(splitResult.message);
|
|
@@ -413,6 +511,18 @@ export async function callProxiedCompletion(proxyUrl, params) {
|
|
|
413
511
|
if (maxTokens !== undefined) {
|
|
414
512
|
body.maxTokens = maxTokens;
|
|
415
513
|
}
|
|
514
|
+
if (structuredOutput !== undefined) {
|
|
515
|
+
// The schema travels as its draft-07 wire form, not as the validator object —
|
|
516
|
+
// an `ISchemaValidator` is not JSON-serializable. A proxy reconstitutes it with
|
|
517
|
+
// `JsonSchema.fromJson(raw)` before calling `callProviderCompletion`.
|
|
518
|
+
body.structuredOutput =
|
|
519
|
+
structuredOutput.mode === 'schema'
|
|
520
|
+
? Object.assign({ mode: 'schema', schema: structuredOutput.schema.toJson() }, (structuredOutput.onUnsupported !== undefined
|
|
521
|
+
? { onUnsupported: structuredOutput.onUnsupported }
|
|
522
|
+
: {})) : Object.assign({ mode: 'json-object' }, (structuredOutput.onUnsupported !== undefined
|
|
523
|
+
? { onUnsupported: structuredOutput.onUnsupported }
|
|
524
|
+
: {}));
|
|
525
|
+
}
|
|
416
526
|
/* c8 ignore next 1 - optional logger */
|
|
417
527
|
logger === null || logger === void 0 ? void 0 : logger.info(`AI proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);
|
|
418
528
|
const url = `${proxyUrl}/api/ai/completion`;
|
|
@@ -427,9 +537,27 @@ export async function callProxiedCompletion(proxyUrl, params) {
|
|
|
427
537
|
if (typeof response.content !== 'string') {
|
|
428
538
|
return fail('proxy returned invalid response: missing content');
|
|
429
539
|
}
|
|
540
|
+
// A caller who asked for nothing gets `'none'` without the proxy having to say
|
|
541
|
+
// so. A caller who DID ask gets a loud failure when the proxy cannot report,
|
|
542
|
+
// rather than a response claiming an enforcement nobody verified — a proxy
|
|
543
|
+
// predating this feature drops the constraint silently, which is the exact
|
|
544
|
+
// failure this surface exists to remove.
|
|
545
|
+
if (structuredOutput === undefined) {
|
|
546
|
+
return succeed({
|
|
547
|
+
content: response.content,
|
|
548
|
+
truncated: response.truncated === true,
|
|
549
|
+
structuredOutput: 'none'
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
if (!isStructuredOutputEnforcement(response.structuredOutput)) {
|
|
553
|
+
return fail(`proxy did not report which structured-output constraint it applied ` +
|
|
554
|
+
`(got ${JSON.stringify(response.structuredOutput)}); it may predate the feature and have ` +
|
|
555
|
+
`dropped the request silently`);
|
|
556
|
+
}
|
|
430
557
|
return succeed({
|
|
431
558
|
content: response.content,
|
|
432
|
-
truncated: response.truncated === true
|
|
559
|
+
truncated: response.truncated === true,
|
|
560
|
+
structuredOutput: response.structuredOutput
|
|
433
561
|
});
|
|
434
562
|
}
|
|
435
563
|
//# sourceMappingURL=completionClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"completionClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/completionClient.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;AAYZ,OAAO,EAAE,IAAI,EAAwB,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAEhG,OAAO,EAGL,4BAA4B,EAQ5B,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,4BAA4B,EAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,6BAA6B,EAC7B,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,2BAA2B,CAAC;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AU,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,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACzC,OAAO,IAAI,CAAC,kDAAkD,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,OAAO,CAAC;QACb,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,SAAS,EAAE,QAAQ,CAAC,SAAS,KAAK,IAAI;KACvC,CAAC,CAAC;AACL,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 * Chat completion clients for AI assist. One provider dispatcher over\n * `IAiProviderDescriptor.apiFormat`, the four adapters it routes to (OpenAI Chat\n * Completions, OpenAI/xAI Responses, Anthropic, Google Gemini), the response\n * validators those adapters use, and the proxied variant of the same modality.\n *\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { fail, type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport {\n AiPrompt,\n type AiServerToolConfig,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type IAiCompletionResponse,\n type IAiProviderDescriptor,\n type IChatMessage,\n type IChatRequest,\n type IThinkingConfig,\n type ModelSpec,\n type ModelSpecKey,\n isAdaptiveThinkingModel,\n isResponsesOnlyModel,\n resolveProviderModel,\n usesMaxCompletionTokensField\n} from './model';\nimport {\n anthropicEffortToBudgetTokens,\n checkTemperatureConflict,\n mergeThinkingConfig,\n providerDiscriminatorForId,\n type IResolvedThinkingConfig\n} from './thinkingOptionsResolver';\nimport {\n buildAnthropicMessages,\n buildGeminiContents,\n buildMessages,\n buildOpenAiChatUserContent,\n buildOpenAiResponsesUserContent,\n normalizeOutboundMessages,\n splitChatRequest\n} from './chatRequestBuilders';\nimport {\n anthropicAuthHeaders,\n bearerAuthHeader,\n geminiAuthHeader,\n resolveEffectiveBaseUrl\n} from './endpoint';\nimport { type IAiApiConfig, fetchJson } from './http';\nimport { toAnthropicTools, toGeminiTools, toResponsesApiTools } from './toolFormats';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parameters for a provider completion request. Carries the unified\n * {@link AiAssist.IChatRequest} shape (`system?` + ordered `messages`, last =\n * current user turn); history is linearized before the current turn.\n * @public\n */\nexport interface IProviderCompletionParams extends IChatRequest {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /**\n * Sampling temperature. Sent to the provider only when explicitly provided; omitted otherwise\n * so the provider's own default applies (current-gen models reject a caller-supplied default).\n */\n readonly temperature?: number;\n /** Optional model override — string or context-aware map (uses descriptor.defaultModel otherwise) */\n readonly modelOverride?: ModelSpec;\n /**\n * Optional quality tier selecting which completion model to use. `undefined`\n * selects the `base` tier; `'frontier'` cascades to `advanced` then `base`\n * when a tier is unset for a provider. Orthogonal to `thinking` and `tools`,\n * which never select a model.\n */\n readonly tier?: 'advanced' | 'frontier';\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Server-side tools to include in the request. Overrides settings-level tool config when provided. */\n readonly tools?: ReadonlyArray<AiServerToolConfig>;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /**\n * Optional override of the descriptor's default base URL (scheme + host +\n * optional port + path prefix). The per-route suffix (e.g. `/chat/completions`)\n * is appended unchanged. Must be a well-formed `http`/`https` URL. Auth shape\n * is unchanged: `needsSecret` providers still require an API key.\n */\n readonly endpoint?: string;\n /**\n * Optional thinking/reasoning config. Anthropic, OpenAI, and xAI reject `temperature` when\n * the effective merged effort is non-`'none'`; Gemini always accepts both.\n */\n readonly thinking?: IThinkingConfig;\n /**\n * Optional cap on generated output tokens, mapped to each provider's native field:\n * Anthropic `max_tokens`, OpenAI Chat Completions `max_completion_tokens`, OpenAI/xAI\n * Responses `max_output_tokens`, Gemini `generationConfig.maxOutputTokens`, and the\n * xAI/Groq/Mistral/Ollama/`openai-compat` chat-completions path `max_tokens`. When unset,\n * every provider except Anthropic omits the field and applies its own default; Anthropic's\n * Messages API requires the field, so it falls back to `DEFAULT_ANTHROPIC_MAX_TOKENS`.\n */\n readonly maxTokens?: number;\n}\n\n// ============================================================================\n// Response validators (non-strict — extra API fields preserved for debugging)\n// ============================================================================\n\n// ---- OpenAI Chat Completions format ----\n\n/** @internal */\ninterface IOpenAiMessage {\n content: string;\n}\n/** @internal */\ninterface IOpenAiChoice {\n message: IOpenAiMessage;\n finish_reason: string;\n}\n/** @internal */\ninterface IOpenAiResponse {\n choices: IOpenAiChoice[];\n}\n\nconst openAiMessage: Validator<IOpenAiMessage> = Validators.object<IOpenAiMessage>({\n content: Validators.string\n});\nconst openAiChoice: Validator<IOpenAiChoice> = Validators.object<IOpenAiChoice>({\n message: openAiMessage,\n finish_reason: Validators.string\n});\nconst openAiResponse: Validator<IOpenAiResponse> = Validators.object<IOpenAiResponse>({\n choices: Validators.arrayOf(openAiChoice).withConstraint((arr) => arr.length > 0)\n});\n\n// ---- OpenAI/xAI Responses API format ----\n\n/** @internal */\ninterface IResponsesApiOutputText {\n type: 'output_text';\n text: string;\n}\n/** @internal */\ninterface IResponsesApiMessage {\n type: 'message';\n role: string;\n content: IResponsesApiOutputText[];\n}\n/** @internal */\ninterface IResponsesApiResponse {\n output: Array<Record<string, unknown>>;\n status: string;\n}\n\nconst responsesApiOutputText: Validator<IResponsesApiOutputText> = Validators.object<IResponsesApiOutputText>(\n {\n type: Validators.literal('output_text'),\n text: Validators.string\n }\n);\nconst responsesApiMessage: Validator<IResponsesApiMessage> = Validators.object<IResponsesApiMessage>({\n type: Validators.literal('message'),\n role: Validators.string,\n content: Validators.arrayOf(responsesApiOutputText).withConstraint((arr) => arr.length > 0)\n});\nconst responsesApiOutputItem: Validator<Record<string, unknown>> = Validators.isA(\n 'object',\n (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null\n);\nconst responsesApiResponse: Validator<IResponsesApiResponse> = Validators.object<IResponsesApiResponse>({\n output: Validators.arrayOf(responsesApiOutputItem).withConstraint((arr) => arr.length > 0),\n status: Validators.string\n});\n\n// ---- Gemini format ----\n\n/** @internal */\ninterface IGeminiPart {\n text: string;\n}\n/** @internal */\ninterface IGeminiContent {\n parts: IGeminiPart[];\n}\n/** @internal */\ninterface IGeminiCandidate {\n content: IGeminiContent;\n finishReason: string;\n}\n/** @internal */\ninterface IGeminiResponse {\n candidates: IGeminiCandidate[];\n}\n\nconst geminiPart: Validator<IGeminiPart> = Validators.object<IGeminiPart>({\n text: Validators.string\n});\nconst geminiContent: Validator<IGeminiContent> = Validators.object<IGeminiContent>({\n parts: Validators.arrayOf(geminiPart).withConstraint((arr) => arr.length > 0)\n});\nconst geminiCandidate: Validator<IGeminiCandidate> = Validators.object<IGeminiCandidate>({\n content: geminiContent,\n finishReason: Validators.string\n});\nconst geminiResponse: Validator<IGeminiResponse> = Validators.object<IGeminiResponse>({\n candidates: Validators.arrayOf(geminiCandidate).withConstraint((arr) => arr.length > 0)\n});\n\n// ============================================================================\n// OpenAI-compatible client (Chat Completions — no tools)\n// ============================================================================\n\n/**\n * Calls an OpenAI-compatible chat completion endpoint.\n * Works for xAI Grok, OpenAI, Groq, and Mistral.\n * @internal\n */\nasync function callOpenAiCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number,\n useMaxCompletionTokensField: boolean = false\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/chat/completions`;\n const messages = buildMessages(prompt.system, buildOpenAiChatUserContent(prompt), {\n head\n });\n const effort = resolvedThinking?.openAiEffort ?? resolvedThinking?.xaiEffort;\n const maxTokensField = useMaxCompletionTokensField ? 'max_completion_tokens' : 'max_tokens';\n const body: Record<string, unknown> = {\n model: config.model,\n messages,\n // Temperature is sent only when the caller explicitly provided one — omitting it lets each\n // provider apply its own default (current-gen models reject a non-default temperature). The\n // completion path already rejects temperature + non-'none' thinking upstream\n // (checkTemperatureConflict), so no effort gate is needed here.\n ...(temperature !== undefined ? { temperature } : {}),\n ...(effort !== undefined && config.model !== 'grok-4' ? { reasoning_effort: effort } : {}),\n // Omitted when the caller doesn't set maxTokens — every non-Anthropic provider applies its\n // own default. See AiAssist.usesMaxCompletionTokensField for the field-name split.\n ...(maxTokens !== undefined ? { [maxTokensField]: maxTokens } : {})\n };\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`OpenAI completion: model=${config.model}`);\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI API response: ${msg}`)\n .onSuccess((response) => {\n const choice = response.choices[0];\n return succeed({\n content: choice.message.content,\n truncated: choice.finish_reason === 'length'\n });\n });\n}\n\n// ============================================================================\n// OpenAI/xAI Responses API (with tools)\n// ============================================================================\n\n/**\n * Extracts text content from a Responses API output array.\n * Finds the first message-type output item and concatenates its text content blocks.\n * @internal\n */\nfunction extractResponsesApiText(output: Array<Record<string, unknown>>): Result<string> {\n for (const item of output) {\n if (item.type === 'message') {\n const messageResult = responsesApiMessage.validate(item as JsonObject);\n if (messageResult.isSuccess()) {\n return succeed(messageResult.value.content.map((c) => c.text).join(''));\n }\n }\n }\n return fail('Responses API output contained no message with text content');\n}\n\n/**\n * Calls the xAI/OpenAI Responses API with server-side tools.\n * Used when tools are configured for an openai-format provider.\n * @internal\n */\nasync function callOpenAiResponsesCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n tools: ReadonlyArray<AiServerToolConfig> = [],\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/responses`;\n const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {\n head\n });\n const effort = resolvedThinking?.openAiEffort ?? resolvedThinking?.xaiEffort;\n const body: Record<string, unknown> = {\n model: config.model,\n input,\n // `tools` is omitted entirely when none are requested — a Responses-only model routed\n // here for tier/model reasons (not tools) must not send an empty tools array.\n ...(tools.length > 0 ? { tools: toResponsesApiTools(tools) } : {}),\n // Temperature is sent only when the caller explicitly provided one (see callOpenAiCompletion).\n ...(temperature !== undefined ? { temperature } : {}),\n ...(effort !== undefined && config.model !== 'grok-4' ? { reasoning: { effort } } : {})\n };\n // Shared by OpenAI and xAI — both route through the Responses API with the same field name.\n if (maxTokens !== undefined) {\n body.max_output_tokens = maxTokens;\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`OpenAI Responses API: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return responsesApiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Responses API response: ${msg}`)\n .onSuccess((response) => {\n return extractResponsesApiText(response.output).onSuccess((text) =>\n succeed({\n content: text,\n truncated: response.status === 'incomplete'\n })\n );\n });\n}\n\n// ============================================================================\n// Anthropic adapter\n// ============================================================================\n\n/**\n * Extracts text content from Anthropic response content blocks.\n * When tools are used, the content array contains mixed block types\n * (text, server_tool_use, web_search_tool_result). We extract and\n * concatenate only the text blocks.\n * @internal\n */\nfunction extractAnthropicText(content: unknown[]): Result<string> {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'object' && block !== null && 'type' in block) {\n const typed = block as Record<string, unknown>;\n if (typed.type === 'text' && typeof typed.text === 'string') {\n textParts.push(typed.text);\n }\n }\n }\n if (textParts.length === 0) {\n return fail('Anthropic response contained no text content blocks');\n }\n return succeed(textParts.join(''));\n}\n\n/** Calls the Anthropic Messages API with optional tool support. @internal */\nasync function callAnthropicCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n tools?: ReadonlyArray<AiServerToolConfig>,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, { head });\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 // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). The\n // completion path rejects temperature + thinking upstream (checkTemperatureConflict), so no\n // effort gate is needed here.\n ...(temperature !== undefined ? { temperature } : {})\n };\n\n const effort = resolvedThinking?.anthropicEffort;\n if (effort !== 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 };\n } else {\n body.thinking = { type: 'enabled', budget_tokens: anthropicEffortToBudgetTokens(effort) };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n /* c8 ignore next 3 - optional logger diagnostic output */\n logger?.info(`Anthropic completion: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n } else {\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Anthropic completion: model=${config.model}`);\n }\n\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const rawContent = (jsonResult.value as Record<string, unknown>).content;\n const stopReason = (jsonResult.value as Record<string, unknown>).stop_reason;\n if (!Array.isArray(rawContent)) {\n return fail('Anthropic API response: content is not an array');\n }\n if (typeof stopReason !== 'string') {\n return fail('Anthropic API response: stop_reason is missing or not a string');\n }\n return extractAnthropicText(rawContent).onSuccess((text) =>\n succeed({\n content: text,\n truncated: stopReason === 'max_tokens'\n })\n );\n}\n\n// ============================================================================\n// Google Gemini adapter\n// ============================================================================\n\n/**\n * Calls the Google Gemini generateContent API.\n * When tools are configured, includes Google Search grounding.\n * @internal\n */\nasync function callGeminiCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n tools?: ReadonlyArray<AiServerToolConfig>,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/models/${config.model}:generateContent`;\n const contents = buildGeminiContents(prompt, { head });\n\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Gemini completion: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n } else {\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Gemini completion: model=${config.model}`);\n }\n\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini API response: ${msg}`)\n .onSuccess((response) => {\n const candidate = response.candidates[0];\n return succeed({\n content: candidate.content.parts[0].text,\n truncated: candidate.finishReason === 'MAX_TOKENS'\n });\n });\n}\n\n// ============================================================================\n// Provider dispatcher\n// ============================================================================\n\n/**\n * Calls the appropriate chat completion API for a given provider. Routes by\n * `apiFormat`: `'openai'` (xAI/OpenAI/Groq/Mistral — switches to Responses API\n * when tools are set), `'anthropic'`, or `'gemini'`.\n * @public\n */\nexport async function callProviderCompletion(\n params: IProviderCompletionParams\n): Promise<Result<IAiCompletionResponse>> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n temperature,\n modelOverride,\n tier,\n logger,\n tools,\n signal,\n endpoint,\n thinking,\n maxTokens\n } = params;\n\n const splitResult = splitChatRequest(system, messages);\n if (splitResult.isFailure()) {\n return fail(splitResult.message);\n }\n const { prompt, head } = splitResult.value;\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const hasTools = tools !== undefined && tools.length > 0;\n const discriminator = providerDiscriminatorForId(descriptor.id);\n // The quality tier is the only completion-model selector; thinking and tools\n // are orthogonal request params/capabilities and never pick a model.\n const modelContext: ModelSpecKey | undefined = tier;\n\n const modelResult = resolveProviderModel(descriptor, modelOverride, modelContext);\n if (modelResult.isFailure()) {\n return fail(modelResult.message);\n }\n const model = modelResult.value;\n\n let resolvedThinking: IResolvedThinkingConfig | undefined;\n if (thinking !== undefined) {\n if (discriminator !== undefined) {\n const mergeResult = mergeThinkingConfig(thinking, model, discriminator);\n /* c8 ignore next 3 - mergeThinkingConfig always succeeds; defensive guard */\n if (mergeResult.isFailure()) {\n return fail(mergeResult.message);\n }\n resolvedThinking = mergeResult.value;\n const conflictResult = checkTemperatureConflict(resolvedThinking, discriminator, temperature);\n if (conflictResult.isFailure()) {\n return fail(conflictResult.message);\n }\n }\n }\n\n const config: IAiApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model\n };\n /* c8 ignore next 8 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = hasTools ? tools.map((t) => t.type).join(',') : 'none';\n const supported = descriptor.supportedTools.length > 0 ? descriptor.supportedTools.join(',') : 'none';\n logger.info(\n `AI completion: provider=${descriptor.id}, format=${descriptor.apiFormat}, model=${config.model}, ` +\n `tools=${toolTypes}, supported=${supported}`\n );\n }\n\n switch (descriptor.apiFormat) {\n case 'openai':\n // Responses-API-only models (e.g. gpt-5.5-pro) 400 on /chat/completions, so they route\n // to the Responses path even with no tools requested — same path the tools case uses.\n if (hasTools || isResponsesOnlyModel(descriptor, config.model)) {\n return callOpenAiResponsesCompletion(\n config,\n prompt,\n tools,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens\n );\n }\n return callOpenAiCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens,\n usesMaxCompletionTokensField(descriptor)\n );\n case 'anthropic':\n return callAnthropicCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n tools,\n signal,\n resolvedThinking,\n isAdaptiveThinkingModel(descriptor, config.model),\n maxTokens\n );\n case 'gemini':\n return callGeminiCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n tools,\n signal,\n resolvedThinking,\n maxTokens\n );\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\n// ============================================================================\n// Proxied completion (routes through a backend server)\n// ============================================================================\n\n/**\n * Calls the AI completion endpoint on a proxy server instead of calling the\n * provider API directly from the browser. The proxy handles provider dispatch,\n * CORS, and API key forwarding. The request body serializes the unified\n * {@link AiAssist.IChatRequest} shape (`system?` + `messages`). Enforces the same\n * non-empty / trailing-user-turn and image-input invariants as the direct path.\n * @param proxyUrl - Base URL of the proxy server\n * @param params - Same parameters as {@link callProviderCompletion}\n * @public\n */\nexport async function callProxiedCompletion(\n proxyUrl: string,\n params: IProviderCompletionParams\n): Promise<Result<IAiCompletionResponse>> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n temperature,\n modelOverride,\n logger,\n tools,\n signal,\n thinking,\n maxTokens\n } = params;\n\n const splitResult = splitChatRequest(system, messages);\n if (splitResult.isFailure()) {\n return fail(splitResult.message);\n }\n if (splitResult.value.prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey,\n messages: normalizeOutboundMessages(splitResult.value)\n };\n // Temperature is forwarded only when explicitly provided, matching the direct path — the proxy\n // omits it from the upstream request so the provider default applies.\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n if (system !== undefined) {\n body.system = system;\n }\n if (modelOverride !== undefined) {\n body.modelOverride = modelOverride;\n }\n if (tools && tools.length > 0) {\n body.tools = tools;\n }\n if (thinking !== undefined) {\n body.thinking = thinking;\n }\n // Forwarded only when explicitly provided; the proxy is responsible for mapping it to the\n // correct upstream provider field (see AiAssist.usesMaxCompletionTokensField).\n if (maxTokens !== undefined) {\n body.maxTokens = maxTokens;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n const url = `${proxyUrl}/api/ai/completion`;\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 if (typeof response.content !== 'string') {\n return fail('proxy returned invalid response: missing content');\n }\n\n return succeed({\n content: response.content,\n truncated: response.truncated === true\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"completionClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/completionClient.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;A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gB,KAAK,SAAS,EAAE,CAAC;QACnC,OAAO,OAAO,CAAC;YACb,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,SAAS,EAAE,QAAQ,CAAC,SAAS,KAAK,IAAI;YACtC,gBAAgB,EAAE,MAAM;SACzB,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,6BAA6B,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC;QAC9D,OAAO,IAAI,CACT,qEAAqE;YACnE,QAAQ,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,yCAAyC;YAC1F,8BAA8B,CACjC,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;QACb,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,SAAS,EAAE,QAAQ,CAAC,SAAS,KAAK,IAAI;QACtC,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;KAC5C,CAAC,CAAC;AACL,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 * Chat completion clients for AI assist. One provider dispatcher over\n * `IAiProviderDescriptor.apiFormat`, the four adapters it routes to (OpenAI Chat\n * Completions, OpenAI/xAI Responses, Anthropic, Google Gemini), the response\n * validators those adapters use, and the proxied variant of the same modality.\n *\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport {\n captureResult,\n fail,\n type Logging,\n Result,\n succeed,\n type Validator,\n Validators\n} from '@fgv/ts-utils';\n\nimport {\n AiPrompt,\n type AiServerToolConfig,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type IAiCompletionResponse,\n type IAiProviderDescriptor,\n type IChatMessage,\n type IChatRequest,\n type IThinkingConfig,\n type ModelSpec,\n type ModelSpecKey,\n isAdaptiveThinkingModel,\n isResponsesOnlyModel,\n resolveProviderModel,\n usesMaxCompletionTokensField\n} from './model';\nimport {\n anthropicEffortToBudgetTokens,\n checkTemperatureConflict,\n mergeThinkingConfig,\n providerDiscriminatorForId,\n type IResolvedThinkingConfig\n} from './thinkingOptionsResolver';\nimport {\n buildAnthropicMessages,\n buildGeminiContents,\n buildMessages,\n buildOpenAiChatUserContent,\n buildOpenAiResponsesUserContent,\n normalizeOutboundMessages,\n splitChatRequest\n} from './chatRequestBuilders';\nimport {\n anthropicAuthHeaders,\n bearerAuthHeader,\n geminiAuthHeader,\n resolveEffectiveBaseUrl\n} from './endpoint';\nimport { type IAiApiConfig, fetchJson } from './http';\nimport { toAnthropicTools, toGeminiTools, toResponsesApiTools } from './toolFormats';\nimport {\n ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME,\n type IResolvedStructuredOutput,\n NO_STRUCTURED_OUTPUT,\n isStructuredOutputEnforcement,\n resolveStructuredOutput\n} from './structuredOutput';\nimport { resolveStructuredOutputCapability } from './registry';\nimport type { StructuredOutputRequest } from './structuredOutputTypes';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parameters for a provider completion request. Carries the unified\n * {@link AiAssist.IChatRequest} shape (`system?` + ordered `messages`, last =\n * current user turn); history is linearized before the current turn.\n * @public\n */\nexport interface IProviderCompletionParams extends IChatRequest {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /**\n * Sampling temperature. Sent to the provider only when explicitly provided; omitted otherwise\n * so the provider's own default applies (current-gen models reject a caller-supplied default).\n */\n readonly temperature?: number;\n /** Optional model override — string or context-aware map (uses descriptor.defaultModel otherwise) */\n readonly modelOverride?: ModelSpec;\n /**\n * Optional quality tier selecting which completion model to use. `undefined`\n * selects the `base` tier; `'frontier'` cascades to `advanced` then `base`\n * when a tier is unset for a provider. Orthogonal to `thinking` and `tools`,\n * which never select a model.\n */\n readonly tier?: 'advanced' | 'frontier';\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Server-side tools to include in the request. Overrides settings-level tool config when provided. */\n readonly tools?: ReadonlyArray<AiServerToolConfig>;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /**\n * Optional override of the descriptor's default base URL (scheme + host +\n * optional port + path prefix). The per-route suffix (e.g. `/chat/completions`)\n * is appended unchanged. Must be a well-formed `http`/`https` URL. Auth shape\n * is unchanged: `needsSecret` providers still require an API key.\n */\n readonly endpoint?: string;\n /**\n * Optional thinking/reasoning config. Anthropic, OpenAI, and xAI reject `temperature` when\n * the effective merged effort is non-`'none'`; Gemini always accepts both.\n */\n readonly thinking?: IThinkingConfig;\n /**\n * Optional cap on generated output tokens, mapped to each provider's native field:\n * Anthropic `max_tokens`, OpenAI Chat Completions `max_completion_tokens`, OpenAI/xAI\n * Responses `max_output_tokens`, Gemini `generationConfig.maxOutputTokens`, and the\n * xAI/Groq/Mistral/Ollama/`openai-compat` chat-completions path `max_tokens`. When unset,\n * every provider except Anthropic omits the field and applies its own default; Anthropic's\n * Messages API requires the field, so it falls back to `DEFAULT_ANTHROPIC_MAX_TOKENS`.\n */\n readonly maxTokens?: number;\n /**\n * Ask the provider to constrain its output — to a schema, or to syntactically\n * valid JSON of arbitrary shape.\n *\n * @remarks\n * **The caller supplies intent; the response reports outcome.** A caller cannot\n * know up front which concrete model will serve the request (a `tier` request\n * cascades, and aliases resolve at call time), so it never has to: whatever was\n * actually enforced comes back on\n * `IAiCompletionResponse.structuredOutput`.\n */\n readonly structuredOutput?: StructuredOutputRequest;\n}\n\n// ============================================================================\n// Response validators (non-strict — extra API fields preserved for debugging)\n// ============================================================================\n\n// ---- OpenAI Chat Completions format ----\n\n/** @internal */\ninterface IOpenAiMessage {\n content: string;\n}\n/** @internal */\ninterface IOpenAiChoice {\n message: IOpenAiMessage;\n finish_reason: string;\n}\n/** @internal */\ninterface IOpenAiResponse {\n choices: IOpenAiChoice[];\n}\n\nconst openAiMessage: Validator<IOpenAiMessage> = Validators.object<IOpenAiMessage>({\n content: Validators.string\n});\nconst openAiChoice: Validator<IOpenAiChoice> = Validators.object<IOpenAiChoice>({\n message: openAiMessage,\n finish_reason: Validators.string\n});\nconst openAiResponse: Validator<IOpenAiResponse> = Validators.object<IOpenAiResponse>({\n choices: Validators.arrayOf(openAiChoice).withConstraint((arr) => arr.length > 0)\n});\n\n// ---- OpenAI/xAI Responses API format ----\n\n/** @internal */\ninterface IResponsesApiOutputText {\n type: 'output_text';\n text: string;\n}\n/** @internal */\ninterface IResponsesApiMessage {\n type: 'message';\n role: string;\n content: IResponsesApiOutputText[];\n}\n/** @internal */\ninterface IResponsesApiResponse {\n output: Array<Record<string, unknown>>;\n status: string;\n}\n\nconst responsesApiOutputText: Validator<IResponsesApiOutputText> = Validators.object<IResponsesApiOutputText>(\n {\n type: Validators.literal('output_text'),\n text: Validators.string\n }\n);\nconst responsesApiMessage: Validator<IResponsesApiMessage> = Validators.object<IResponsesApiMessage>({\n type: Validators.literal('message'),\n role: Validators.string,\n content: Validators.arrayOf(responsesApiOutputText).withConstraint((arr) => arr.length > 0)\n});\nconst responsesApiOutputItem: Validator<Record<string, unknown>> = Validators.isA(\n 'object',\n (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null\n);\nconst responsesApiResponse: Validator<IResponsesApiResponse> = Validators.object<IResponsesApiResponse>({\n output: Validators.arrayOf(responsesApiOutputItem).withConstraint((arr) => arr.length > 0),\n status: Validators.string\n});\n\n// ---- Gemini format ----\n\n/** @internal */\ninterface IGeminiPart {\n text: string;\n}\n/** @internal */\ninterface IGeminiContent {\n parts: IGeminiPart[];\n}\n/** @internal */\ninterface IGeminiCandidate {\n content: IGeminiContent;\n finishReason: string;\n}\n/** @internal */\ninterface IGeminiResponse {\n candidates: IGeminiCandidate[];\n}\n\nconst geminiPart: Validator<IGeminiPart> = Validators.object<IGeminiPart>({\n text: Validators.string\n});\nconst geminiContent: Validator<IGeminiContent> = Validators.object<IGeminiContent>({\n parts: Validators.arrayOf(geminiPart).withConstraint((arr) => arr.length > 0)\n});\nconst geminiCandidate: Validator<IGeminiCandidate> = Validators.object<IGeminiCandidate>({\n content: geminiContent,\n finishReason: Validators.string\n});\nconst geminiResponse: Validator<IGeminiResponse> = Validators.object<IGeminiResponse>({\n candidates: Validators.arrayOf(geminiCandidate).withConstraint((arr) => arr.length > 0)\n});\n\n// ============================================================================\n// OpenAI-compatible client (Chat Completions — no tools)\n// ============================================================================\n\n/**\n * Calls an OpenAI-compatible chat completion endpoint.\n * Works for xAI Grok, OpenAI, Groq, and Mistral.\n * @internal\n */\nasync function callOpenAiCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number,\n useMaxCompletionTokensField: boolean = false,\n structured: IResolvedStructuredOutput = NO_STRUCTURED_OUTPUT\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/chat/completions`;\n const messages = buildMessages(prompt.system, buildOpenAiChatUserContent(prompt), {\n head\n });\n const effort = resolvedThinking?.openAiEffort ?? resolvedThinking?.xaiEffort;\n const maxTokensField = useMaxCompletionTokensField ? 'max_completion_tokens' : 'max_tokens';\n const body: Record<string, unknown> = {\n model: config.model,\n messages,\n // Temperature is sent only when the caller explicitly provided one — omitting it lets each\n // provider apply its own default (current-gen models reject a non-default temperature). The\n // completion path already rejects temperature + non-'none' thinking upstream\n // (checkTemperatureConflict), so no effort gate is needed here.\n ...(temperature !== undefined ? { temperature } : {}),\n ...(effort !== undefined && config.model !== 'grok-4' ? { reasoning_effort: effort } : {}),\n // Omitted when the caller doesn't set maxTokens — every non-Anthropic provider applies its\n // own default. See AiAssist.usesMaxCompletionTokensField for the field-name split.\n ...(maxTokens !== undefined ? { [maxTokensField]: maxTokens } : {})\n };\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n Object.assign(body, structured.wire);\n\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`OpenAI completion: model=${config.model}`);\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI API response: ${msg}`)\n .onSuccess((response) => {\n const choice = response.choices[0];\n return succeed({\n content: choice.message.content,\n truncated: choice.finish_reason === 'length',\n structuredOutput: structured.enforcement\n });\n });\n}\n\n// ============================================================================\n// OpenAI/xAI Responses API (with tools)\n// ============================================================================\n\n/**\n * Extracts text content from a Responses API output array.\n * Finds the first message-type output item and concatenates its text content blocks.\n * @internal\n */\nfunction extractResponsesApiText(output: Array<Record<string, unknown>>): Result<string> {\n for (const item of output) {\n if (item.type === 'message') {\n const messageResult = responsesApiMessage.validate(item as JsonObject);\n if (messageResult.isSuccess()) {\n return succeed(messageResult.value.content.map((c) => c.text).join(''));\n }\n }\n }\n return fail('Responses API output contained no message with text content');\n}\n\n/**\n * Calls the xAI/OpenAI Responses API with server-side tools.\n * Used when tools are configured for an openai-format provider.\n * @internal\n */\nasync function callOpenAiResponsesCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n tools: ReadonlyArray<AiServerToolConfig> = [],\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number,\n structured: IResolvedStructuredOutput = NO_STRUCTURED_OUTPUT\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/responses`;\n const input = buildMessages(prompt.system, buildOpenAiResponsesUserContent(prompt), {\n head\n });\n const effort = resolvedThinking?.openAiEffort ?? resolvedThinking?.xaiEffort;\n const body: Record<string, unknown> = {\n model: config.model,\n input,\n // `tools` is omitted entirely when none are requested — a Responses-only model routed\n // here for tier/model reasons (not tools) must not send an empty tools array.\n ...(tools.length > 0 ? { tools: toResponsesApiTools(tools) } : {}),\n // Temperature is sent only when the caller explicitly provided one (see callOpenAiCompletion).\n ...(temperature !== undefined ? { temperature } : {}),\n ...(effort !== undefined && config.model !== 'grok-4' ? { reasoning: { effort } } : {})\n };\n // Shared by OpenAI and xAI — both route through the Responses API with the same field name.\n if (maxTokens !== undefined) {\n body.max_output_tokens = maxTokens;\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n Object.assign(body, structured.wire);\n\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`OpenAI Responses API: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return responsesApiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Responses API response: ${msg}`)\n .onSuccess((response) => {\n return extractResponsesApiText(response.output).onSuccess((text) =>\n succeed({\n content: text,\n truncated: response.status === 'incomplete',\n structuredOutput: structured.enforcement\n })\n );\n });\n}\n\n// ============================================================================\n// Anthropic adapter\n// ============================================================================\n\n/**\n * Extracts text content from Anthropic response content blocks.\n * When tools are used, the content array contains mixed block types\n * (text, server_tool_use, web_search_tool_result). We extract and\n * concatenate only the text blocks.\n * @internal\n */\nfunction extractAnthropicText(content: unknown[]): Result<string> {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'object' && block !== null && 'type' in block) {\n const typed = block as Record<string, unknown>;\n if (typed.type === 'text' && typeof typed.text === 'string') {\n textParts.push(typed.text);\n }\n }\n }\n if (textParts.length === 0) {\n return fail('Anthropic response contained no text content blocks');\n }\n return succeed(textParts.join(''));\n}\n\n/**\n * Extracts the forced structured-output tool's input from Anthropic response\n * content blocks and re-serializes it.\n *\n * @remarks\n * Under `'tool-forced'` enforcement the model's answer arrives as a `tool_use`\n * block's `input` — a parsed object — rather than as text. Re-serializing it here\n * keeps `IAiCompletionResponse.content` a JSON **string** on every provider, so a\n * caller's converter is written once and does not branch on which enforcement it\n * got. A useful side effect: the string is produced by `JSON.stringify` rather\n * than by the model, so under this enforcement it is syntactically valid by\n * construction.\n * @internal\n */\nfunction extractAnthropicStructuredOutput(content: unknown[]): Result<string> {\n for (const block of content) {\n if (typeof block === 'object' && block !== null && 'type' in block) {\n const typed = block as Record<string, unknown>;\n if (typed.type === 'tool_use' && typed.name === ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME) {\n // `JSON.stringify` returns `undefined` — not a string, and not a throw —\n // for `undefined` and for a function or symbol. `captureResult` would wrap\n // that as a Success, putting `undefined` behind a `content: string`\n // contract with nothing to catch it downstream. A `tool_use` block with no\n // `input` is exactly that case.\n return captureResult(() => JSON.stringify(typed.input))\n .withErrorFormat(\n (msg) => `Anthropic API response: structured output could not be serialized: ${msg}`\n )\n .onSuccess((json) =>\n typeof json === 'string'\n ? succeed(json)\n : fail(\n `Anthropic API response: forced tool '${ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME}' returned no serializable input`\n )\n );\n }\n }\n }\n // Loud rather than a silent fall back to text: we forced the tool, so its\n // absence means the request did not do what the response is about to claim it\n // did — and `structuredOutput: 'tool-forced'` would then be a lie.\n return fail(\n `Anthropic API response: structured output was forced but no '${ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME}' tool_use block was returned`\n );\n}\n\n/** Calls the Anthropic Messages API with optional tool support. @internal */\nasync function callAnthropicCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n tools?: ReadonlyArray<AiServerToolConfig>,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number,\n structured: IResolvedStructuredOutput = NO_STRUCTURED_OUTPUT\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, { head });\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 // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). The\n // completion path rejects temperature + thinking upstream (checkTemperatureConflict), so no\n // effort gate is needed here.\n ...(temperature !== undefined ? { temperature } : {})\n };\n\n const effort = resolvedThinking?.anthropicEffort;\n if (effort !== 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 };\n } else {\n body.thinking = { type: 'enabled', budget_tokens: anthropicEffortToBudgetTokens(effort) };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n\n // The structured-output wire carries `tools` + `tool_choice` of its own, so the\n // server-tool assignment below would clobber it. `resolveStructuredOutput`\n // refuses that combination up front, which is what makes the two mutually\n // exclusive — but that is an invariant held in a DIFFERENT FILE, and a future\n // second Anthropic capability entry (or a relaxed conflict guard) would\n // reintroduce silent clobbering with nothing failing at this line. So assert it\n // here rather than trusting a comment across a file boundary.\n // Unreachable through the public API — resolveStructuredOutput refuses this\n // combination before dispatch — and unreachable BY DESIGN: it cannot be\n // exercised without first breaking the very thing it guards against.\n /* c8 ignore next 6 - defensive: internal consistency check, see above */\n if (structured.enforcement === 'tool-forced' && tools !== undefined && tools.length > 0) {\n return fail(\n `Anthropic completion: structured output and server-side tools both claim the tools channel; ` +\n `this combination must be refused before reaching the adapter`\n );\n }\n Object.assign(body, structured.wire);\n\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n /* c8 ignore next 3 - optional logger diagnostic output */\n logger?.info(`Anthropic completion: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n } else {\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Anthropic completion: model=${config.model}`);\n }\n\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const rawContent = (jsonResult.value as Record<string, unknown>).content;\n const stopReason = (jsonResult.value as Record<string, unknown>).stop_reason;\n if (!Array.isArray(rawContent)) {\n return fail('Anthropic API response: content is not an array');\n }\n if (typeof stopReason !== 'string') {\n return fail('Anthropic API response: stop_reason is missing or not a string');\n }\n const extracted =\n structured.enforcement === 'tool-forced'\n ? extractAnthropicStructuredOutput(rawContent)\n : extractAnthropicText(rawContent);\n return extracted.onSuccess((text) =>\n succeed({\n content: text,\n truncated: stopReason === 'max_tokens',\n structuredOutput: structured.enforcement\n })\n );\n}\n\n// ============================================================================\n// Google Gemini adapter\n// ============================================================================\n\n/**\n * Calls the Google Gemini generateContent API.\n * When tools are configured, includes Google Search grounding.\n * @internal\n */\nasync function callGeminiCompletion(\n config: IAiApiConfig,\n prompt: AiPrompt,\n head?: ReadonlyArray<IChatMessage>,\n temperature?: number,\n logger?: Logging.ILogger,\n tools?: ReadonlyArray<AiServerToolConfig>,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n maxTokens?: number,\n structured: IResolvedStructuredOutput = NO_STRUCTURED_OUTPUT\n): Promise<Result<IAiCompletionResponse>> {\n const url = `${config.baseUrl}/models/${config.model}:generateContent`;\n const contents = buildGeminiContents(prompt, { head });\n\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n // Gemini nests the constraint INSIDE generationConfig, not on the body.\n Object.assign(generationConfig, structured.wire);\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Gemini completion: model=${config.model}, tools=${tools.map((t) => t.type).join(',')}`);\n } else {\n /* c8 ignore next 1 - optional logger */\n logger?.info(`Gemini completion: model=${config.model}`);\n }\n\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini API response: ${msg}`)\n .onSuccess((response) => {\n const candidate = response.candidates[0];\n return succeed({\n // ALL parts, not `parts[0]`. Gemini may split one reply across several\n // text parts, and reading only the first silently discards the rest —\n // yielding a truncated document that often still parses, which is the\n // worst way to be wrong. The streaming adapter has always concatenated\n // (`fullText += part.text`); this path did not, so the same response gave\n // different text depending on which one you called.\n content: candidate.content.parts.map((part) => part.text).join(''),\n truncated: candidate.finishReason === 'MAX_TOKENS',\n structuredOutput: structured.enforcement\n });\n });\n}\n\n// ============================================================================\n// Provider dispatcher\n// ============================================================================\n\n/**\n * Calls the appropriate chat completion API for a given provider. Routes by\n * `apiFormat`: `'openai'` (xAI/OpenAI/Groq/Mistral — switches to Responses API\n * when tools are set), `'anthropic'`, or `'gemini'`.\n * @public\n */\nexport async function callProviderCompletion(\n params: IProviderCompletionParams\n): Promise<Result<IAiCompletionResponse>> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n temperature,\n modelOverride,\n tier,\n logger,\n tools,\n signal,\n endpoint,\n thinking,\n maxTokens,\n structuredOutput\n } = params;\n\n const splitResult = splitChatRequest(system, messages);\n if (splitResult.isFailure()) {\n return fail(splitResult.message);\n }\n const { prompt, head } = splitResult.value;\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const hasTools = tools !== undefined && tools.length > 0;\n const discriminator = providerDiscriminatorForId(descriptor.id);\n // The quality tier is the only completion-model selector; thinking and tools\n // are orthogonal request params/capabilities and never pick a model.\n const modelContext: ModelSpecKey | undefined = tier;\n\n const modelResult = resolveProviderModel(descriptor, modelOverride, modelContext);\n if (modelResult.isFailure()) {\n return fail(modelResult.message);\n }\n const model = modelResult.value;\n\n let resolvedThinking: IResolvedThinkingConfig | undefined;\n if (thinking !== undefined) {\n if (discriminator !== undefined) {\n const mergeResult = mergeThinkingConfig(thinking, model, discriminator);\n /* c8 ignore next 3 - mergeThinkingConfig always succeeds; defensive guard */\n if (mergeResult.isFailure()) {\n return fail(mergeResult.message);\n }\n resolvedThinking = mergeResult.value;\n const conflictResult = checkTemperatureConflict(resolvedThinking, discriminator, temperature);\n if (conflictResult.isFailure()) {\n return fail(conflictResult.message);\n }\n }\n }\n\n // Resolved against the CONCRETE model, after resolveProviderModel — passing an\n // alias here is the defect resolveImageCapability once had.\n // The OpenAI route depends on tools AND the model, so it is computed here (once,\n // beside the switch that uses it) and handed to the resolver — a capability keyed\n // on the model alone cannot know which of the two OpenAI wire shapes applies.\n const usesResponsesApi: boolean =\n descriptor.apiFormat === 'openai' && (hasTools || isResponsesOnlyModel(descriptor, model));\n const structuredResult = resolveStructuredOutput(\n descriptor,\n model,\n structuredOutput,\n tools,\n usesResponsesApi,\n resolveStructuredOutputCapability\n );\n if (structuredResult.isFailure()) {\n return fail(structuredResult.message);\n }\n const resolvedStructured = structuredResult.value;\n\n // OpenAI rejects `response_format: { type: 'json_object' }` with a 400 unless the\n // conversation mentions JSON somewhere — a documented API rule, and one a caller\n // has no way to discover from a schema-mode request that worked. Pre-empted with a\n // named failure before the wire call, the same treatment the Gemini\n // grounding-plus-function-calling conflict already gets. `generateJsonCompletion`\n // satisfies it for free via its prompt hint; a direct caller may not.\n if (resolvedStructured.enforcement === 'json-mode' && descriptor.apiFormat === 'openai') {\n const mentionsJson: boolean =\n (system ?? '').toLowerCase().includes('json') ||\n messages.some((m) => m.content.toLowerCase().includes('json'));\n if (!mentionsJson) {\n return fail(\n `provider '${descriptor.id}': json-object structured output requires the word 'json' to ` +\n `appear in the system prompt or a message — OpenAI rejects the request otherwise. Mention ` +\n `it, or use structuredOutput: { mode: 'schema', schema } which carries no such rule`\n );\n }\n }\n\n const config: IAiApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model\n };\n /* c8 ignore next 8 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = hasTools ? tools.map((t) => t.type).join(',') : 'none';\n const supported = descriptor.supportedTools.length > 0 ? descriptor.supportedTools.join(',') : 'none';\n logger.info(\n `AI completion: provider=${descriptor.id}, format=${descriptor.apiFormat}, model=${config.model}, ` +\n `tools=${toolTypes}, supported=${supported}`\n );\n }\n\n switch (descriptor.apiFormat) {\n case 'openai':\n // Responses-API-only models (e.g. gpt-5.5-pro) 400 on /chat/completions, so they route\n // to the Responses path even with no tools requested — same path the tools case uses.\n if (usesResponsesApi) {\n return callOpenAiResponsesCompletion(\n config,\n prompt,\n tools,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens,\n resolvedStructured\n );\n }\n return callOpenAiCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens,\n usesMaxCompletionTokensField(descriptor),\n resolvedStructured\n );\n case 'anthropic':\n return callAnthropicCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n tools,\n signal,\n resolvedThinking,\n isAdaptiveThinkingModel(descriptor, config.model),\n maxTokens,\n resolvedStructured\n );\n case 'gemini':\n return callGeminiCompletion(\n config,\n prompt,\n head,\n temperature,\n logger,\n tools,\n signal,\n resolvedThinking,\n maxTokens,\n resolvedStructured\n );\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\n// ============================================================================\n// Proxied completion (routes through a backend server)\n// ============================================================================\n\n/**\n * Calls the AI completion endpoint on a proxy server instead of calling the\n * provider API directly from the browser. The proxy handles provider dispatch,\n * CORS, and API key forwarding. The request body serializes the unified\n * {@link AiAssist.IChatRequest} shape (`system?` + `messages`). Enforces the same\n * non-empty / trailing-user-turn and image-input invariants as the direct path.\n * @param proxyUrl - Base URL of the proxy server\n * @param params - Same parameters as {@link callProviderCompletion}\n * @public\n */\nexport async function callProxiedCompletion(\n proxyUrl: string,\n params: IProviderCompletionParams\n): Promise<Result<IAiCompletionResponse>> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n temperature,\n modelOverride,\n logger,\n tools,\n signal,\n thinking,\n maxTokens,\n structuredOutput\n } = params;\n\n const splitResult = splitChatRequest(system, messages);\n if (splitResult.isFailure()) {\n return fail(splitResult.message);\n }\n if (splitResult.value.prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey,\n messages: normalizeOutboundMessages(splitResult.value)\n };\n // Temperature is forwarded only when explicitly provided, matching the direct path — the proxy\n // omits it from the upstream request so the provider default applies.\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n if (system !== undefined) {\n body.system = system;\n }\n if (modelOverride !== undefined) {\n body.modelOverride = modelOverride;\n }\n if (tools && tools.length > 0) {\n body.tools = tools;\n }\n if (thinking !== undefined) {\n body.thinking = thinking;\n }\n // Forwarded only when explicitly provided; the proxy is responsible for mapping it to the\n // correct upstream provider field (see AiAssist.usesMaxCompletionTokensField).\n if (maxTokens !== undefined) {\n body.maxTokens = maxTokens;\n }\n if (structuredOutput !== undefined) {\n // The schema travels as its draft-07 wire form, not as the validator object —\n // an `ISchemaValidator` is not JSON-serializable. A proxy reconstitutes it with\n // `JsonSchema.fromJson(raw)` before calling `callProviderCompletion`.\n body.structuredOutput =\n structuredOutput.mode === 'schema'\n ? {\n mode: 'schema',\n schema: structuredOutput.schema.toJson(),\n ...(structuredOutput.onUnsupported !== undefined\n ? { onUnsupported: structuredOutput.onUnsupported }\n : {})\n }\n : {\n mode: 'json-object',\n ...(structuredOutput.onUnsupported !== undefined\n ? { onUnsupported: structuredOutput.onUnsupported }\n : {})\n };\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n const url = `${proxyUrl}/api/ai/completion`;\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 if (typeof response.content !== 'string') {\n return fail('proxy returned invalid response: missing content');\n }\n\n // A caller who asked for nothing gets `'none'` without the proxy having to say\n // so. A caller who DID ask gets a loud failure when the proxy cannot report,\n // rather than a response claiming an enforcement nobody verified — a proxy\n // predating this feature drops the constraint silently, which is the exact\n // failure this surface exists to remove.\n if (structuredOutput === undefined) {\n return succeed({\n content: response.content,\n truncated: response.truncated === true,\n structuredOutput: 'none'\n });\n }\n if (!isStructuredOutputEnforcement(response.structuredOutput)) {\n return fail(\n `proxy did not report which structured-output constraint it applied ` +\n `(got ${JSON.stringify(response.structuredOutput)}); it may predate the feature and have ` +\n `dropped the request silently`\n );\n }\n return succeed({\n content: response.content,\n truncated: response.truncated === true,\n structuredOutput: response.structuredOutput\n });\n}\n"]}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export { AiPrompt, allModelCapabilities, DEFAULT_ANTHROPIC_MAX_TOKENS, DEFAULT_AI_ASSIST, providerApiKeySecretName, allModelSpecKeys, MODEL_SPEC_BASE_KEY, resolveModel, MODEL_ALIAS_SIGIL, resolveModelAlias, resolveProviderModel, isResponsesOnlyModel, isAdaptiveThinkingModel, usesMaxCompletionTokensField, toDataUrl } from './model';
|
|
6
6
|
export { resolveImageOptions, validateResolvedOptions } from './imageOptionsResolver';
|
|
7
|
-
export { allProviderIds, getProviderDescriptors, getProviderDescriptor, resolveImageCapability, supportsImageGeneration, resolveEmbeddingCapability, supportsEmbedding, DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';
|
|
7
|
+
export { allProviderIds, getProviderDescriptors, getProviderDescriptor, resolveImageCapability, supportsImageGeneration, resolveEmbeddingCapability, supportsEmbedding, resolveStructuredOutputCapability, supportsStructuredOutput, DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';
|
|
8
8
|
export { callProviderCompletion, callProxiedCompletion } from './completionClient';
|
|
9
9
|
export { callProviderImageGeneration, callProxiedImageGeneration } from './imageGenerationClient';
|
|
10
10
|
export { callProviderListModels, callProxiedListModels } from './listModelsClient';
|
|
@@ -12,6 +12,7 @@ export { callProviderEmbedding, callProxiedEmbedding } from './embeddingClient';
|
|
|
12
12
|
export { callProviderCompletionStream, callProxiedCompletionStream, executeClientToolTurn } from './streamingClient';
|
|
13
13
|
export { aiProviderId, aiServerToolType, aiWebSearchToolConfig, aiServerToolConfig, aiToolAnnotations, aiClientToolConfig, aiToolEnablement, aiAssistProviderConfig, aiAssistSettings, modelSpecKey, modelSpec } from './converters';
|
|
14
14
|
export { resolveEffectiveTools } from './toolFormats';
|
|
15
|
+
export { ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME } from './structuredOutput';
|
|
15
16
|
export { classifyJsonParseFailure, extractJsonText, fencedStringifiedJson } from './jsonResponse';
|
|
16
17
|
export { generateJsonCompletion, SMART_JSON_PROMPT_HINT } from './jsonCompletion';
|
|
17
18
|
export { anthropicEffortToBudgetTokens } from './thinkingOptionsResolver';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,QAAQ,EAER,oBAAoB,EAcpB,4BAA4B,EAe5B,iBAAiB,EAEjB,wBAAwB,EAoCxB,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,EAEZ,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,4BAA4B,EAC5B,SAAS,EAiBV,MAAM,SAAS,CAAC;AAEjB,OAAO,EAEL,mBAAmB,EACnB,uBAAuB,EACxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,0BAA0B,EAC1B,iBAAiB,EACjB,+BAA+B,EAChC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EAEtB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,EAE3B,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EAEtB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EAErB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAE3B,qBAAqB,EAItB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,qBAAqB,EAKtB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EAIvB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,6BAA6B,EAAgC,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * AI assist packlet - provider registry, prompt class, settings, and API client.\n * @packageDocumentation\n */\n\nexport {\n AiPrompt,\n type AiModelCapability,\n allModelCapabilities,\n type AiProviderId,\n type AiServerToolType,\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiWebSearchToolConfig,\n type IAiClientToolConfig,\n type IAiToolAnnotations,\n type IAiClientTool,\n type IAiClientToolCallSummary,\n type IAiClientToolContinuation,\n type IAiClientToolTurnResult,\n type IAiToolEnablement,\n type IAiCompletionResponse,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type IChatMessage,\n type IChatRequest,\n type AiApiFormat,\n type AiImageApiFormat,\n type AiEmbeddingApiFormat,\n type AiEmbeddingTaskType,\n type IAiEmbeddingModelCapability,\n type IAiEmbeddingParams,\n type IAiEmbeddingUsage,\n type IAiEmbeddingResult,\n type IAiImageModelCapability,\n type IAiProviderDescriptor,\n type IAiAssistProviderConfig,\n type IAiAssistSettings,\n DEFAULT_AI_ASSIST,\n type IAiAssistKeyStore,\n providerApiKeySecretName,\n type IAiImageAttachment,\n type IAiImageData,\n type AiImageSize,\n type AiImageQuality,\n type GptImageSize,\n type GptImageQuality,\n type GptImageModelNames,\n type GrokImagineModelNames,\n type GeminiFlashImageModelNames,\n type IGptImageGenerationConfig,\n type IGrokImagineImageGenerationConfig,\n type IGeminiFlashImageGenerationConfig,\n type IGptImageModelOptions,\n type IGrokImagineModelOptions,\n type IGeminiFlashImageModelOptions,\n type IOtherModelOptions,\n type IModelFamilyConfig,\n type IAiImageGenerationOptions,\n type IAiImageGenerationParams,\n type IAiGeneratedImage,\n type IAiImageGenerationResponse,\n type IAiModelCapabilityRule,\n type IAiModelCapabilityConfig,\n type IAiModelInfo,\n type IAiStreamEvent,\n type IAiStreamTextDelta,\n type IAiStreamToolEvent,\n type IAiStreamToolUseStart,\n type IAiStreamToolUseDelta,\n type IAiStreamToolUseComplete,\n type IAiStreamDone,\n type IAiStreamError,\n type ModelSpec,\n type ModelSpecKey,\n type IModelSpecMap,\n allModelSpecKeys,\n MODEL_SPEC_BASE_KEY,\n resolveModel,\n type IModelAliasMap,\n MODEL_ALIAS_SIGIL,\n resolveModelAlias,\n resolveProviderModel,\n isResponsesOnlyModel,\n isAdaptiveThinkingModel,\n usesMaxCompletionTokensField,\n toDataUrl,\n type AiThinkingMode,\n type IThinkingConfig,\n type IThinkingProviderConfig,\n type IAnthropicThinkingOptions,\n type IOpenAiThinkingOptions,\n type IGeminiThinkingOptions,\n type IXAiThinkingOptions,\n type IOtherThinkingOptions,\n type IAnthropicThinkingConfig,\n type IOpenAiThinkingConfig,\n type IGeminiThinkingConfig,\n type IXAiThinkingConfig,\n type AnthropicThinkingModelNames,\n type OpenAiThinkingModelNames,\n type GeminiThinkingModelNames,\n type XAiThinkingModelNames\n} from './model';\n\nexport {\n type IResolvedImageOptions,\n resolveImageOptions,\n validateResolvedOptions\n} from './imageOptionsResolver';\n\nexport {\n allProviderIds,\n getProviderDescriptors,\n getProviderDescriptor,\n resolveImageCapability,\n supportsImageGeneration,\n resolveEmbeddingCapability,\n supportsEmbedding,\n DEFAULT_MODEL_CAPABILITY_CONFIG\n} from './registry';\n\nexport {\n callProviderCompletion,\n callProxiedCompletion,\n type IProviderCompletionParams\n} from './completionClient';\n\nexport {\n callProviderImageGeneration,\n callProxiedImageGeneration,\n type IProviderImageGenerationParams\n} from './imageGenerationClient';\n\nexport {\n callProviderListModels,\n callProxiedListModels,\n type IProviderListModelsParams\n} from './listModelsClient';\n\nexport {\n callProviderEmbedding,\n callProxiedEmbedding,\n type IProviderEmbeddingParams\n} from './embeddingClient';\n\nexport {\n callProviderCompletionStream,\n callProxiedCompletionStream,\n type IProviderCompletionStreamParams,\n executeClientToolTurn,\n type IExecuteClientToolTurnParams,\n type IExecuteClientToolTurnResult,\n type IToolExecutionDecision\n} from './streamingClient';\n\nexport {\n aiProviderId,\n aiServerToolType,\n aiWebSearchToolConfig,\n aiServerToolConfig,\n aiToolAnnotations,\n aiClientToolConfig,\n aiToolEnablement,\n aiAssistProviderConfig,\n aiAssistSettings,\n modelSpecKey,\n modelSpec\n} from './converters';\n\nexport { resolveEffectiveTools } from './toolFormats';\n\nexport {\n classifyJsonParseFailure,\n extractJsonText,\n fencedStringifiedJson,\n type IFencedStringifiedJsonExtractorOptions,\n type IFencedStringifiedJsonOptions,\n type JsonParseFailureReason,\n type JsonTextExtractor\n} from './jsonResponse';\n\nexport {\n generateJsonCompletion,\n SMART_JSON_PROMPT_HINT,\n type IGenerateJsonCompletionParams,\n type IGenerateJsonCompletionResult,\n type JsonPromptHint\n} from './jsonCompletion';\n\nexport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from './thinkingOptionsResolver';\n"]}
|
|
1
|
+
{"version":3,"file":"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OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,qBAAqB,EAKtB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EAIvB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,6BAA6B,EAAgC,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * AI assist packlet - provider registry, prompt class, settings, and API client.\n * @packageDocumentation\n */\n\nexport {\n AiPrompt,\n type AiModelCapability,\n allModelCapabilities,\n type AiProviderId,\n type AiServerToolType,\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiWebSearchToolConfig,\n type IAiClientToolConfig,\n type IAiToolAnnotations,\n type IAiClientTool,\n type IAiClientToolCallSummary,\n type IAiClientToolContinuation,\n type IAiClientToolTurnResult,\n type IAiToolEnablement,\n type IAiCompletionResponse,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type IChatMessage,\n type IChatRequest,\n type AiApiFormat,\n type AiImageApiFormat,\n type AiEmbeddingApiFormat,\n type AiEmbeddingTaskType,\n type IAiEmbeddingModelCapability,\n type IAiEmbeddingParams,\n type IAiEmbeddingUsage,\n type IAiEmbeddingResult,\n type IAiImageModelCapability,\n type IAiProviderDescriptor,\n type IAiAssistProviderConfig,\n type IAiAssistSettings,\n DEFAULT_AI_ASSIST,\n type IAiAssistKeyStore,\n providerApiKeySecretName,\n type IAiImageAttachment,\n type IAiImageData,\n type AiImageSize,\n type AiImageQuality,\n type GptImageSize,\n type GptImageQuality,\n type GptImageModelNames,\n type GrokImagineModelNames,\n type GeminiFlashImageModelNames,\n type IGptImageGenerationConfig,\n type IGrokImagineImageGenerationConfig,\n type IGeminiFlashImageGenerationConfig,\n type IGptImageModelOptions,\n type IGrokImagineModelOptions,\n type IGeminiFlashImageModelOptions,\n type IOtherModelOptions,\n type IModelFamilyConfig,\n type IAiImageGenerationOptions,\n type IAiImageGenerationParams,\n type IAiGeneratedImage,\n type IAiImageGenerationResponse,\n type IAiModelCapabilityRule,\n type IAiModelCapabilityConfig,\n type IAiModelInfo,\n type IAiStreamEvent,\n type IAiStreamTextDelta,\n type IAiStreamToolEvent,\n type IAiStreamToolUseStart,\n type IAiStreamToolUseDelta,\n type IAiStreamToolUseComplete,\n type IAiStreamDone,\n type IAiStreamError,\n type ModelSpec,\n type ModelSpecKey,\n type IModelSpecMap,\n allModelSpecKeys,\n MODEL_SPEC_BASE_KEY,\n resolveModel,\n type IModelAliasMap,\n MODEL_ALIAS_SIGIL,\n resolveModelAlias,\n resolveProviderModel,\n isResponsesOnlyModel,\n isAdaptiveThinkingModel,\n usesMaxCompletionTokensField,\n toDataUrl,\n type AiThinkingMode,\n type IThinkingConfig,\n type IThinkingProviderConfig,\n type IAnthropicThinkingOptions,\n type IOpenAiThinkingOptions,\n type IGeminiThinkingOptions,\n type IXAiThinkingOptions,\n type IOtherThinkingOptions,\n type IAnthropicThinkingConfig,\n type IOpenAiThinkingConfig,\n type IGeminiThinkingConfig,\n type IXAiThinkingConfig,\n type AnthropicThinkingModelNames,\n type OpenAiThinkingModelNames,\n type GeminiThinkingModelNames,\n type XAiThinkingModelNames\n} from './model';\n\nexport {\n type IResolvedImageOptions,\n resolveImageOptions,\n validateResolvedOptions\n} from './imageOptionsResolver';\n\nexport {\n allProviderIds,\n getProviderDescriptors,\n getProviderDescriptor,\n resolveImageCapability,\n supportsImageGeneration,\n resolveEmbeddingCapability,\n supportsEmbedding,\n resolveStructuredOutputCapability,\n supportsStructuredOutput,\n DEFAULT_MODEL_CAPABILITY_CONFIG\n} from './registry';\n\nexport {\n callProviderCompletion,\n callProxiedCompletion,\n type IProviderCompletionParams\n} from './completionClient';\n\nexport {\n callProviderImageGeneration,\n callProxiedImageGeneration,\n type IProviderImageGenerationParams\n} from './imageGenerationClient';\n\nexport {\n callProviderListModels,\n callProxiedListModels,\n type IProviderListModelsParams\n} from './listModelsClient';\n\nexport {\n callProviderEmbedding,\n callProxiedEmbedding,\n type IProviderEmbeddingParams\n} from './embeddingClient';\n\nexport {\n callProviderCompletionStream,\n callProxiedCompletionStream,\n type IProviderCompletionStreamParams,\n executeClientToolTurn,\n type IExecuteClientToolTurnParams,\n type IExecuteClientToolTurnResult,\n type IToolExecutionDecision\n} from './streamingClient';\n\nexport {\n aiProviderId,\n aiServerToolType,\n aiWebSearchToolConfig,\n aiServerToolConfig,\n aiToolAnnotations,\n aiClientToolConfig,\n aiToolEnablement,\n aiAssistProviderConfig,\n aiAssistSettings,\n modelSpecKey,\n modelSpec\n} from './converters';\n\nexport { resolveEffectiveTools } from './toolFormats';\n\nexport { ANTHROPIC_STRUCTURED_OUTPUT_TOOL_NAME } from './structuredOutput';\n\nexport type {\n AiStructuredOutputFormat,\n IAiStructuredOutputCapability,\n IJsonObjectStructuredOutputRequest,\n ISchemaStructuredOutputRequest,\n StructuredOutputEnforcement,\n StructuredOutputFallback,\n StructuredOutputRequest\n} from './structuredOutputTypes';\n\nexport {\n classifyJsonParseFailure,\n extractJsonText,\n fencedStringifiedJson,\n type IFencedStringifiedJsonExtractorOptions,\n type IFencedStringifiedJsonOptions,\n type JsonParseFailureReason,\n type JsonTextExtractor\n} from './jsonResponse';\n\nexport {\n generateJsonCompletion,\n SMART_JSON_PROMPT_HINT,\n type IGenerateJsonCompletionParams,\n type IGenerateJsonCompletionResult,\n type JsonPromptHint\n} from './jsonCompletion';\n\nexport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from './thinkingOptionsResolver';\n"]}
|