@fgv/ts-extras 5.1.0-56 → 5.1.0-57
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/CAPABILITIES.md +3 -2
- package/dist/packlets/ai-assist/chatRequestBuilders.js +2 -2
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- package/dist/packlets/ai-assist/completionClient.js +74 -14
- package/dist/packlets/ai-assist/completionClient.js.map +1 -1
- package/dist/packlets/ai-assist/converters.js +54 -0
- package/dist/packlets/ai-assist/converters.js.map +1 -1
- package/dist/packlets/ai-assist/embeddingClient.js +16 -1
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js +16 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
- package/dist/packlets/ai-assist/listModelsClient.js +19 -1
- package/dist/packlets/ai-assist/listModelsClient.js.map +1 -1
- package/dist/packlets/ai-assist/model.js.map +1 -1
- package/dist/packlets/ai-assist/streamUsageCapability.js +16 -6
- package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +8 -4
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +22 -7
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +17 -9
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +12 -9
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/dist/packlets/ai-assist/streamingClient.js +20 -6
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js +5 -2
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
- package/dist/packlets/ai-assist/toolTypes.js.map +1 -1
- package/dist/ts-extras.d.ts +223 -24
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +2 -2
- package/lib/packlets/ai-assist/chatRequestBuilders.js +2 -2
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- 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 +74 -14
- package/lib/packlets/ai-assist/completionClient.js.map +1 -1
- package/lib/packlets/ai-assist/converters.d.ts +46 -0
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -1
- package/lib/packlets/ai-assist/converters.js +55 -1
- package/lib/packlets/ai-assist/converters.js.map +1 -1
- package/lib/packlets/ai-assist/embeddingClient.d.ts +9 -0
- package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/embeddingClient.js +16 -1
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts +9 -0
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.js +16 -1
- package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.d.ts +12 -0
- package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.js +19 -1
- package/lib/packlets/ai-assist/listModelsClient.js.map +1 -1
- package/lib/packlets/ai-assist/model.d.ts +22 -7
- 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/streamUsageCapability.d.ts +16 -6
- package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamUsageCapability.js +16 -6
- package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +6 -2
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +37 -2
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +21 -6
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +17 -3
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +15 -7
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +10 -7
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +22 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.d.ts +5 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.js +19 -5
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +11 -3
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js +5 -2
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
- package/lib/packlets/ai-assist/toolTypes.d.ts +61 -3
- package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -1
- package/lib/packlets/ai-assist/toolTypes.js.map +1 -1
- package/package.json +7 -7
|
@@ -69,6 +69,11 @@ Object.defineProperty(exports, "executeClientToolTurn", { enumerable: true, get:
|
|
|
69
69
|
* `Result.fail` before fetch is invoked. Callers should route through
|
|
70
70
|
* {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.
|
|
71
71
|
*
|
|
72
|
+
* This guard is applied **here only**. `executeClientToolTurn` is also a
|
|
73
|
+
* streaming entry point and does not pre-flight the flag, so a browser
|
|
74
|
+
* client-tool turn against a `streamingCorsRestricted` provider fails at the
|
|
75
|
+
* fetch with a CORS error rather than with this legible refusal.
|
|
76
|
+
*
|
|
72
77
|
* Connection-time failures (auth, network, non-2xx) surface as the outer
|
|
73
78
|
* `Result.fail`. Once iteration begins, errors mid-stream surface as a
|
|
74
79
|
* terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable
|
|
@@ -79,7 +84,7 @@ Object.defineProperty(exports, "executeClientToolTurn", { enumerable: true, get:
|
|
|
79
84
|
* @public
|
|
80
85
|
*/
|
|
81
86
|
async function callProviderCompletionStream(params) {
|
|
82
|
-
const { descriptor, apiKey, system, messages, temperature, modelOverride, tier, logger, tools, signal, endpoint, thinking, maxTokens } = params;
|
|
87
|
+
const { descriptor, apiKey, system, messages, temperature, modelOverride, tier, logger, tools, signal, endpoint, thinking, maxTokens, cache } = params;
|
|
83
88
|
const splitResult = (0, chatRequestBuilders_1.splitChatRequest)(system, messages);
|
|
84
89
|
if (splitResult.isFailure()) {
|
|
85
90
|
return (0, ts_utils_1.fail)(splitResult.message);
|
|
@@ -126,15 +131,24 @@ async function callProviderCompletionStream(params) {
|
|
|
126
131
|
model
|
|
127
132
|
};
|
|
128
133
|
switch (descriptor.apiFormat) {
|
|
129
|
-
case 'openai':
|
|
134
|
+
case 'openai': {
|
|
135
|
+
// Same gating as callProviderCompletion's 'openai' case in completionClient.ts — see the
|
|
136
|
+
// comment there for why breakpoints and the routing key are gated independently.
|
|
137
|
+
const routing = (0, streamUsageCapability_1.supportsPromptCacheRouting)(descriptor);
|
|
138
|
+
const breakpoints = (0, streamUsageCapability_1.supportsPromptCacheBreakpoints)(descriptor) ? cache === null || cache === void 0 ? void 0 : cache.systemBreakpoints : undefined;
|
|
139
|
+
const routedKey = routing !== undefined ? cache === null || cache === void 0 ? void 0 : cache.cacheKey : undefined;
|
|
140
|
+
const gatedCache = breakpoints !== undefined || routedKey !== undefined
|
|
141
|
+
? { systemBreakpoints: breakpoints, cacheKey: routedKey }
|
|
142
|
+
: undefined;
|
|
130
143
|
// Responses-API-only models (e.g. gpt-5.5-pro) 400 on /chat/completions, so they route
|
|
131
144
|
// to the Responses stream even with no tools requested — same path the tools case uses.
|
|
132
145
|
if (hasTools || (0, model_1.isResponsesOnlyModel)(descriptor, config.model)) {
|
|
133
|
-
return (0, openaiResponses_1.callOpenAiResponsesStream)(config, prompt, tools, head, temperature, logger, signal, resolvedThinking, undefined, undefined, maxTokens, (0, streamUsageCapability_1.supportsCacheUsageReporting)(descriptor));
|
|
146
|
+
return (0, openaiResponses_1.callOpenAiResponsesStream)(config, prompt, tools, head, temperature, logger, signal, resolvedThinking, undefined, undefined, maxTokens, (0, streamUsageCapability_1.supportsCacheUsageReporting)(descriptor), gatedCache);
|
|
134
147
|
}
|
|
135
|
-
return (0, openaiChat_1.callOpenAiChatStream)(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, (0, model_1.usesMaxCompletionTokensField)(descriptor), (0, streamUsageCapability_1.supportsStreamUsageOption)(descriptor));
|
|
148
|
+
return (0, openaiChat_1.callOpenAiChatStream)(config, prompt, head, temperature, logger, signal, resolvedThinking, maxTokens, (0, model_1.usesMaxCompletionTokensField)(descriptor), (0, streamUsageCapability_1.supportsStreamUsageOption)(descriptor), gatedCache, routing === null || routing === void 0 ? void 0 : routing.chatCompletionsHeader);
|
|
149
|
+
}
|
|
136
150
|
case 'anthropic':
|
|
137
|
-
return (0, anthropic_1.callAnthropicStream)(config, prompt, head, temperature, tools, logger, signal, resolvedThinking, undefined, undefined, (0, model_1.isAdaptiveThinkingModel)(descriptor, config.model), maxTokens);
|
|
151
|
+
return (0, anthropic_1.callAnthropicStream)(config, prompt, head, temperature, tools, logger, signal, resolvedThinking, undefined, undefined, (0, model_1.isAdaptiveThinkingModel)(descriptor, config.model), maxTokens, cache);
|
|
138
152
|
case 'gemini':
|
|
139
153
|
return (0, gemini_1.callGeminiStream)(config, prompt, head, temperature, tools, logger, signal, resolvedThinking, undefined, undefined, maxTokens);
|
|
140
154
|
/* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamingClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/streamingClient.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AAiFZ,oEAyIC;AAxND;;;;;;;GAOG;AAEH,4CAA6C;AAE7C,+DA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CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming chat completion client. Public façade over the per-format\n * adapters under `streamingAdapters/`: provider dispatch and pre-flight\n * validation live here; format-specific request/translation logic and the\n * typed event-payload validators live with each adapter.\n *\n * @packageDocumentation\n */\n\nimport { fail, Result } from '@fgv/ts-utils';\n\nimport { splitChatRequest } from './chatRequestBuilders';\nimport { resolveEffectiveBaseUrl } from './endpoint';\nimport {\n type IAiStreamEvent,\n type ModelSpecKey,\n isAdaptiveThinkingModel,\n isResponsesOnlyModel,\n resolveProviderModel,\n usesMaxCompletionTokensField\n} from './model';\nimport { supportsCacheUsageReporting, supportsStreamUsageOption } from './streamUsageCapability';\nimport { callAnthropicStream } from './streamingAdapters/anthropic';\nimport { type IProviderCompletionStreamParams, type IStreamApiConfig } from './streamingAdapters/common';\nimport { callGeminiStream } from './streamingAdapters/gemini';\nimport { callOpenAiChatStream } from './streamingAdapters/openaiChat';\nimport { callOpenAiResponsesStream } from './streamingAdapters/openaiResponses';\nimport {\n checkTemperatureConflict,\n mergeThinkingConfig,\n providerDiscriminatorForId,\n type IResolvedThinkingConfig\n} from './thinkingOptionsResolver';\n\nexport { callProxiedCompletionStream } from './streamingAdapters/proxy';\nexport type { IProviderCompletionStreamParams } from './streamingAdapters/common';\n\n/**\n * Re-export `executeClientToolTurn` from the continuation builder so callers\n * can import it directly from the streaming-client surface.\n *\n * @remarks\n * **Why `clientTools` does not flow through `callProviderCompletionStream`:**\n * Client tools require a stateful per-stream accumulation buffer (for thinking\n * blocks, tool-use args, Gemini functionCall accumulation) that is owned by the\n * continuation builder's execution context. Passing `clientTools` through the\n * generic `callProviderCompletionStream` entry would require the caller to manage\n * the accumulation buffer externally. `executeClientToolTurn` is therefore the\n * canonical (and only) call path for client tools in Phase C. Callers that need\n * both server tools and client tools in the same request should use\n * `executeClientToolTurn` with both `tools` (server) and `clientTools` present;\n * `callProviderCompletionStream` is for server-tools-only or no-tools requests.\n */\n/* c8 ignore next 5 - barrel re-export; function is covered by clientToolContinuationBuilder tests */\nexport {\n executeClientToolTurn,\n type IExecuteClientToolTurnParams,\n type IExecuteClientToolTurnResult,\n type IToolExecutionDecision\n} from './streamingAdapters/clientToolContinuationBuilder';\n\n/**\n * Calls the appropriate streaming chat completion API for a given provider.\n *\n * @remarks\n * Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`\n * and the call isn't being routed through a proxy, this returns\n * `Result.fail` before fetch is invoked. Callers should route through\n * {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.\n *\n * Connection-time failures (auth, network, non-2xx) surface as the outer\n * `Result.fail`. Once iteration begins, errors mid-stream surface as a\n * terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable\n * ending. The final successful event is {@link AiAssist.IAiStreamDone}.\n *\n * @param params - Request parameters including descriptor, API key, prompt, and optional tools\n * @returns A streaming iterable of unified events, or a Result.fail\n * @public\n */\nexport async function callProviderCompletionStream(\n params: IProviderCompletionStreamParams\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const {\n descriptor,\n apiKey,\n 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 (descriptor.streamingCorsRestricted) {\n return fail(`provider \"${descriptor.id}\" requires a proxy for streaming; none is configured`);\n }\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const hasTools = tools !== undefined && tools.length > 0;\n const 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: IStreamApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model\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 stream even with no tools requested — same path the tools case uses.\n if (hasTools || isResponsesOnlyModel(descriptor, config.model)) {\n return callOpenAiResponsesStream(\n config,\n prompt,\n tools,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\n maxTokens,\n supportsCacheUsageReporting(descriptor)\n );\n }\n return callOpenAiChatStream(\n config,\n prompt,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens,\n usesMaxCompletionTokensField(descriptor),\n supportsStreamUsageOption(descriptor)\n );\n case 'anthropic':\n return callAnthropicStream(\n config,\n prompt,\n head,\n temperature,\n tools,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\n isAdaptiveThinkingModel(descriptor, config.model),\n maxTokens\n );\n case 'gemini':\n return callGeminiStream(\n config,\n prompt,\n head,\n temperature,\n tools,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\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"]}
|
|
1
|
+
{"version":3,"file":"streamingClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/streamingClient.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AA4FZ,oEAwJC;AAlPD;;;;;;;GAOG;AAEH,4CAA6C;AAG7C,+DAAyD;AACzD,yCAAqD;AACrD,mCAOiB;AACjB,mEAKiC;AACjC,6DAAoE;AAEpE,uDAA8D;AAC9D,+DAAsE;AACtE,yEAAgF;AAChF,uEAKmC;AAEnC,mDAAwE;AA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IAAI,EACJ,WAAW,EACX,KAAK,EACL,MAAM,EACN,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,IAAA,+BAAuB,EAAC,UAAU,EAAE,MAAM,CAAC,KAAK,CAAC,EACjD,SAAS,EACT,KAAK,CACN,CAAC;QACJ,KAAK,QAAQ;YACX,OAAO,IAAA,yBAAgB,EACrB,MAAM,EACN,MAAM,EACN,IAAI,EACJ,WAAW,EACX,KAAK,EACL,MAAM,EACN,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,SAAS,CACV,CAAC;QACJ,qFAAqF;QACrF,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,WAAW,GAAU,UAAU,CAAC,SAAS,CAAC;YAChD,OAAO,IAAA,eAAI,EAAC,2BAA2B,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming chat completion client. Public façade over the per-format\n * adapters under `streamingAdapters/`: provider dispatch and pre-flight\n * validation live here; format-specific request/translation logic and the\n * typed event-payload validators live with each adapter.\n *\n * @packageDocumentation\n */\n\nimport { fail, Result } from '@fgv/ts-utils';\n\nimport { type IAiCacheRequest } from './cacheRequest';\nimport { splitChatRequest } from './chatRequestBuilders';\nimport { resolveEffectiveBaseUrl } from './endpoint';\nimport {\n type IAiStreamEvent,\n type ModelSpecKey,\n isAdaptiveThinkingModel,\n isResponsesOnlyModel,\n resolveProviderModel,\n usesMaxCompletionTokensField\n} from './model';\nimport {\n supportsCacheUsageReporting,\n supportsPromptCacheBreakpoints,\n supportsPromptCacheRouting,\n supportsStreamUsageOption\n} from './streamUsageCapability';\nimport { callAnthropicStream } from './streamingAdapters/anthropic';\nimport { type IProviderCompletionStreamParams, type IStreamApiConfig } from './streamingAdapters/common';\nimport { callGeminiStream } from './streamingAdapters/gemini';\nimport { callOpenAiChatStream } from './streamingAdapters/openaiChat';\nimport { callOpenAiResponsesStream } from './streamingAdapters/openaiResponses';\nimport {\n checkTemperatureConflict,\n mergeThinkingConfig,\n providerDiscriminatorForId,\n type IResolvedThinkingConfig\n} from './thinkingOptionsResolver';\n\nexport { callProxiedCompletionStream } from './streamingAdapters/proxy';\nexport type { IProviderCompletionStreamParams } from './streamingAdapters/common';\n\n/**\n * Re-export `executeClientToolTurn` from the continuation builder so callers\n * can import it directly from the streaming-client surface.\n *\n * @remarks\n * **Why `clientTools` does not flow through `callProviderCompletionStream`:**\n * Client tools require a stateful per-stream accumulation buffer (for thinking\n * blocks, tool-use args, Gemini functionCall accumulation) that is owned by the\n * continuation builder's execution context. Passing `clientTools` through the\n * generic `callProviderCompletionStream` entry would require the caller to manage\n * the accumulation buffer externally. `executeClientToolTurn` is therefore the\n * canonical (and only) call path for client tools in Phase C. Callers that need\n * both server tools and client tools in the same request should use\n * `executeClientToolTurn` with both `tools` (server) and `clientTools` present;\n * `callProviderCompletionStream` is for server-tools-only or no-tools requests.\n */\n/* c8 ignore next 5 - barrel re-export; function is covered by clientToolContinuationBuilder tests */\nexport {\n executeClientToolTurn,\n type IExecuteClientToolTurnParams,\n type IExecuteClientToolTurnResult,\n type IToolExecutionDecision\n} from './streamingAdapters/clientToolContinuationBuilder';\n\n/**\n * Calls the appropriate streaming chat completion API for a given provider.\n *\n * @remarks\n * Pre-flight rejection: when `descriptor.streamingCorsRestricted === true`\n * and the call isn't being routed through a proxy, this returns\n * `Result.fail` before fetch is invoked. Callers should route through\n * {@link AiAssist.callProxiedCompletionStream} or surface the failure to the user.\n *\n * This guard is applied **here only**. `executeClientToolTurn` is also a\n * streaming entry point and does not pre-flight the flag, so a browser\n * client-tool turn against a `streamingCorsRestricted` provider fails at the\n * fetch with a CORS error rather than with this legible refusal.\n *\n * Connection-time failures (auth, network, non-2xx) surface as the outer\n * `Result.fail`. Once iteration begins, errors mid-stream surface as a\n * terminal error event ({@link AiAssist.IAiStreamError}) followed by the iterable\n * ending. The final successful event is {@link AiAssist.IAiStreamDone}.\n *\n * @param params - Request parameters including descriptor, API key, prompt, and optional tools\n * @returns A streaming iterable of unified events, or a Result.fail\n * @public\n */\nexport async function callProviderCompletionStream(\n params: IProviderCompletionStreamParams\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n temperature,\n modelOverride,\n tier,\n logger,\n tools,\n signal,\n endpoint,\n thinking,\n maxTokens,\n cache\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 (descriptor.streamingCorsRestricted) {\n return fail(`provider \"${descriptor.id}\" requires a proxy for streaming; none is configured`);\n }\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n const hasTools = tools !== undefined && tools.length > 0;\n const 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: IStreamApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model\n };\n\n switch (descriptor.apiFormat) {\n case 'openai': {\n // Same gating as callProviderCompletion's 'openai' case in completionClient.ts — see the\n // comment there for why breakpoints and the routing key are gated independently.\n const routing = supportsPromptCacheRouting(descriptor);\n const breakpoints = supportsPromptCacheBreakpoints(descriptor) ? cache?.systemBreakpoints : undefined;\n const routedKey = routing !== undefined ? cache?.cacheKey : undefined;\n const gatedCache: IAiCacheRequest | undefined =\n breakpoints !== undefined || routedKey !== undefined\n ? { systemBreakpoints: breakpoints, cacheKey: routedKey }\n : undefined;\n // Responses-API-only models (e.g. gpt-5.5-pro) 400 on /chat/completions, so they route\n // to the Responses stream even with no tools requested — same path the tools case uses.\n if (hasTools || isResponsesOnlyModel(descriptor, config.model)) {\n return callOpenAiResponsesStream(\n config,\n prompt,\n tools,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\n maxTokens,\n supportsCacheUsageReporting(descriptor),\n gatedCache\n );\n }\n return callOpenAiChatStream(\n config,\n prompt,\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n maxTokens,\n usesMaxCompletionTokensField(descriptor),\n supportsStreamUsageOption(descriptor),\n gatedCache,\n routing?.chatCompletionsHeader\n );\n }\n case 'anthropic':\n return callAnthropicStream(\n config,\n prompt,\n head,\n temperature,\n tools,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\n isAdaptiveThinkingModel(descriptor, config.model),\n maxTokens,\n cache\n );\n case 'gemini':\n return callGeminiStream(\n config,\n prompt,\n head,\n temperature,\n tools,\n logger,\n signal,\n resolvedThinking,\n undefined,\n undefined,\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"]}
|
|
@@ -27,7 +27,12 @@ export declare function providerDiscriminatorForId(providerId: string): Thinking
|
|
|
27
27
|
* @public
|
|
28
28
|
*/
|
|
29
29
|
export interface IResolvedThinkingConfig {
|
|
30
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* Anthropic: effort level. The emit-site picks one of two wire shapes — on the
|
|
32
|
+
* Claude 5 family it sends the effort string verbatim in `output_config` with no
|
|
33
|
+
* budget; on older models it converts via `anthropicEffortToBudgetTokens`. See
|
|
34
|
+
* {@link AiAssist.IAnthropicThinkingConfig.effort}.
|
|
35
|
+
*/
|
|
31
36
|
readonly anthropicEffort?: IAnthropicThinkingConfig['effort'];
|
|
32
37
|
/** OpenAI Chat: reasoning_effort value; OpenAI Responses: reasoning.effort */
|
|
33
38
|
readonly openAiEffort?: IOpenAiThinkingConfig['effort'];
|
|
@@ -44,8 +49,11 @@ export interface IResolvedThinkingConfig {
|
|
|
44
49
|
*
|
|
45
50
|
* Policy: low = 2048, medium = 8192, high = 24000, max = 32000. The lower three
|
|
46
51
|
* align with the Anthropic-published minimum-meaningful budget, a mid-range
|
|
47
|
-
* default, and a "deep thinking" allotment respectively. `max`
|
|
48
|
-
*
|
|
52
|
+
* default, and a "deep thinking" allotment respectively. `max` is the deepest
|
|
53
|
+
* allotment and stays within typical model limits.
|
|
54
|
+
*
|
|
55
|
+
* Only reached for models outside the Claude 5 family — the adaptive-thinking path
|
|
56
|
+
* sends no budget at all.
|
|
49
57
|
*
|
|
50
58
|
* @public
|
|
51
59
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinkingOptionsResolver.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/thinkingOptionsResolver.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AAEH,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAQ,MAAM,EAAW,MAAM,eAAe,CAAC;AAEtD,OAAO,KAAK,EACV,eAAe,EAEf,wBAAwB,EACxB,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AAMjB;;;;GAIG;AACH,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEtF;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,6BAA6B,GAAG,SAAS,CAaxG;AAMD;;;;;;;;GAQG;AACH,MAAM,WAAW,uBAAuB;IACtC
|
|
1
|
+
{"version":3,"file":"thinkingOptionsResolver.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/thinkingOptionsResolver.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AAEH,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAQ,MAAM,EAAW,MAAM,eAAe,CAAC;AAEtD,OAAO,KAAK,EACV,eAAe,EAEf,wBAAwB,EACxB,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AAMjB;;;;GAIG;AACH,MAAM,MAAM,6BAA6B,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEtF;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,6BAA6B,GAAG,SAAS,CAaxG;AAMD;;;;;;;;GAQG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;;;OAKG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,wBAAwB,CAAC,QAAQ,CAAC,CAAC;IAC9D,8EAA8E;IAC9E,QAAQ,CAAC,YAAY,CAAC,EAAE,qBAAqB,CAAC,QAAQ,CAAC,CAAC;IACxD,6DAA6D;IAC7D,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IACvC,oDAAoD;IACpD,QAAQ,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAClD,2DAA2D;IAC3D,QAAQ,CAAC,WAAW,CAAC,EAAE,UAAU,CAAC;CACnC;AAgBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,6BAA6B,CAC3C,MAAM,EAAE,WAAW,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,GACtD,MAAM,CAWR;AA6FD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,eAAe,EACvB,aAAa,EAAE,MAAM,EACrB,aAAa,EAAE,6BAA6B,GAC3C,MAAM,CAAC,uBAAuB,CAAC,CA+CjC;AAyDD;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,uBAAuB,EACjC,aAAa,EAAE,6BAA6B,EAC5C,WAAW,EAAE,MAAM,GAAG,SAAS,GAC9B,MAAM,CAAC,SAAS,CAAC,CAkCnB"}
|
|
@@ -61,8 +61,11 @@ function genericEffortToAnthropic(effort) {
|
|
|
61
61
|
*
|
|
62
62
|
* Policy: low = 2048, medium = 8192, high = 24000, max = 32000. The lower three
|
|
63
63
|
* align with the Anthropic-published minimum-meaningful budget, a mid-range
|
|
64
|
-
* default, and a "deep thinking" allotment respectively. `max`
|
|
65
|
-
*
|
|
64
|
+
* default, and a "deep thinking" allotment respectively. `max` is the deepest
|
|
65
|
+
* allotment and stays within typical model limits.
|
|
66
|
+
*
|
|
67
|
+
* Only reached for models outside the Claude 5 family — the adaptive-thinking path
|
|
68
|
+
* sends no budget at all.
|
|
66
69
|
*
|
|
67
70
|
* @public
|
|
68
71
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinkingOptionsResolver.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/thinkingOptionsResolver.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;;AAkCZ,gEAaC;AAqDD,sEAaC;AAmHD,kDAmDC;AAmED,4DAsCC;AAxXD,4CAAsD;AAqBtD;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,UAAkB;IAC3D,QAAQ,UAAU,EAAE,CAAC;QACnB,KAAK,WAAW;YACd,OAAO,WAAW,CAAC;QACrB,KAAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB,KAAK,eAAe;YAClB,OAAO,QAAQ,CAAC;QAClB,KAAK,UAAU;YACb,OAAO,KAAK,CAAC;QACf;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC;AA4BD,+EAA+E;AAC/E,wBAAwB;AACxB,+EAA+E;AAE/E;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,MAAiC;IACjE,OAAO,MAAM,CAAC,CAAC,oCAAoC;AACrD,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,6BAA6B,CAC3C,MAAuD;I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C,uCAAY,OAAO,KAAE,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,IAAG;gBACxD,CAAC;YACH,CAAC;YACD,MAAM;IACV,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,+EAA+E;AAC/E,6BAA6B;AAC7B,+EAA+E;AAE/E;;;;;;;;;GASG;AACH,SAAgB,wBAAwB,CACtC,QAAiC,EACjC,aAA4C,EAC5C,WAA+B;IAE/B,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IAC5B,CAAC;IAED,QAAQ,aAAa,EAAE,CAAC;QACtB,KAAK,WAAW;YACd,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,EAAE,CAAC;gBAC3C,OAAO,IAAA,eAAI,EACT,gHAAgH,CACjH,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,QAAQ;YACX,kEAAkE;YAClE,IAAI,QAAQ,CAAC,YAAY,KAAK,SAAS,IAAI,QAAQ,CAAC,YAAY,KAAK,MAAM,EAAE,CAAC;gBAC5E,OAAO,IAAA,eAAI,EACT,6GAA6G,CAC9G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,KAAK;YACR,0FAA0F;YAC1F,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS,IAAI,QAAQ,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC;gBACtE,OAAO,IAAA,eAAI,EACT,0GAA0G,CAC3G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,QAAQ;YACX,oEAAoE;YACpE,MAAM;IACV,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;AAC5B,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 * Merge logic and runtime validation for thinking/reasoning options.\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { fail, Result, succeed } from '@fgv/ts-utils';\n\nimport type {\n IThinkingConfig,\n IThinkingProviderConfig,\n IAnthropicThinkingConfig,\n IOpenAiThinkingConfig,\n IXAiThinkingConfig\n} from './model';\n\n// ============================================================================\n// Provider discriminator\n// ============================================================================\n\n/**\n * Coarse provider family used to discriminate thinking config blocks.\n * Maps from AiProviderId to the IThinkingProviderConfig `provider` discriminator.\n * @internal\n */\nexport type ThinkingProviderDiscriminator = 'anthropic' | 'openai' | 'google' | 'xai';\n\n/**\n * Maps an AiProviderId (registry key) to the coarse family discriminator used\n * in IThinkingProviderConfig. Returns undefined for providers without thinking support.\n * @internal\n */\nexport function providerDiscriminatorForId(providerId: string): ThinkingProviderDiscriminator | undefined {\n switch (providerId) {\n case 'anthropic':\n return 'anthropic';\n case 'openai':\n return 'openai';\n case 'google-gemini':\n return 'google';\n case 'xai-grok':\n return 'xai';\n default:\n return undefined;\n }\n}\n\n// ============================================================================\n// Resolved wire shape\n// ============================================================================\n\n/**\n * Resolved thinking wire parameters for a specific provider, after merging\n * all applicable config blocks. Ready for provider-specific wire encoding.\n *\n * Callers that pre-resolve thinking config outside of the standard streaming\n * helpers (e.g. `executeClientToolTurn`) accept this type via the\n * `resolvedThinking` parameter and pass it directly to the adapter layer.\n * @public\n */\nexport interface IResolvedThinkingConfig {\n /** Anthropic: effort level; emit-site converts to `thinking.budget_tokens` via `anthropicEffortToBudgetTokens`. */\n readonly anthropicEffort?: IAnthropicThinkingConfig['effort'];\n /** OpenAI Chat: reasoning_effort value; OpenAI Responses: reasoning.effort */\n readonly openAiEffort?: IOpenAiThinkingConfig['effort'];\n /** Gemini: generationConfig.thinkingConfig.thinkingBudget */\n readonly geminiThinkingBudget?: number;\n /** xAI: reasoning_effort value (omit for grok-4) */\n readonly xaiEffort?: IXAiThinkingConfig['effort'];\n /** Other/passthrough: merged verbatim into wire request */\n readonly otherParams?: JsonObject;\n}\n\n// ============================================================================\n// Common-subset mapping\n// ============================================================================\n\n/**\n * Maps generic effort to Anthropic wire effort. Anthropic has no 'none' value in its\n * own vocabulary — the caller (tier 1 of `mergeThinkingConfig`) handles `'none'` by\n * skipping this mapping entirely, so `anthropicEffort` stays unset and the emit site\n * omits the `thinking` wire param. @internal\n */\nfunction genericEffortToAnthropic(effort: 'low' | 'medium' | 'high'): IAnthropicThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n/**\n * Maps Anthropic effort level to the `thinking.budget_tokens` integer that the\n * Anthropic API requires when `thinking.type === 'enabled'`.\n *\n * Policy: low = 2048, medium = 8192, high = 24000, max = 32000. The lower three\n * align with the Anthropic-published minimum-meaningful budget, a mid-range\n * default, and a \"deep thinking\" allotment respectively. `max` targets Opus 4.6's\n * deepest budget and stays within typical model limits.\n *\n * @public\n */\nexport function anthropicEffortToBudgetTokens(\n effort: NonNullable<IAnthropicThinkingConfig['effort']>\n): number {\n switch (effort) {\n case 'low':\n return 2048;\n case 'medium':\n return 8192;\n case 'high':\n return 24000;\n case 'max':\n return 32000;\n }\n}\n\n/**\n * Maps generic effort to OpenAI wire effort. @internal\n */\nfunction genericEffortToOpenAi(effort: 'none' | 'low' | 'medium' | 'high'): IOpenAiThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n/**\n * Maps generic effort to Gemini thinkingBudget. `'none'` maps to `0` — Gemini's own\n * off value on the wire, though `IGeminiThinkingConfig.thinkingBudget` documents that `0`\n * is valid only on Flash/Flash-Lite and errors on Pro; this mapping is not model-aware and\n * inherits that same caveat (not a new gap — an explicit `providers` block could already\n * request `thinkingBudget: 0` on any model). @internal\n */\nfunction genericEffortToGemini(effort: 'none' | 'low' | 'medium' | 'high'): number {\n switch (effort) {\n case 'none':\n return 0;\n case 'low':\n return 1024;\n case 'medium':\n return 4096;\n case 'high':\n return 8192;\n }\n}\n\n/**\n * Maps generic effort to xAI reasoning_effort. @internal\n */\nfunction genericEffortToXai(effort: 'none' | 'low' | 'medium' | 'high'): IXAiThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n// ============================================================================\n// Block applicability\n// ============================================================================\n\n/**\n * Returns true when a provider config block applies to the given resolved model\n * and provider discriminator.\n *\n * Applicability rules:\n * - provider must match the coarse discriminator\n * - if models array is present, resolved model must match (exact or base-name prefix)\n * - if models array is absent, the block is provider-generic (applies to all)\n *\n * Prefix matching supports versioned IDs: `'claude-sonnet-4-5'` matches resolved\n * `'claude-sonnet-4-5-20250929'`. An entry matches when it equals the resolved model\n * or when the resolved model starts with the entry followed by a `-`.\n *\n * 'other' blocks require models to be present (enforced by the type).\n * @internal\n */\nfunction modelNameMatches(resolvedModel: string, name: string): boolean {\n return resolvedModel === name || resolvedModel.startsWith(`${name}-`);\n}\n\nfunction blockApplies(\n block: IThinkingProviderConfig,\n resolvedModel: string,\n discriminator: ThinkingProviderDiscriminator\n): boolean {\n if (block.provider !== discriminator && block.provider !== 'other') {\n return false;\n }\n if (block.provider === 'other') {\n return block.models.some((name) => modelNameMatches(resolvedModel, name));\n }\n if (block.models !== undefined) {\n return (block.models as ReadonlyArray<string>).some((name) => modelNameMatches(resolvedModel, name));\n }\n return true; // provider-generic block\n}\n\n/**\n * Returns true when a block is model-specific (has a models array).\n * Used to partition blocks into merge tiers.\n * @internal\n */\nfunction isModelSpecific(block: IThinkingProviderConfig): boolean {\n if (block.provider === 'other') {\n return true; // other blocks always require models\n }\n return block.models !== undefined;\n}\n\n// ============================================================================\n// Merge function\n// ============================================================================\n\n/**\n * Resolves the effective thinking wire parameters for a specific resolved model\n * by merging all applicable config blocks in precedence order.\n *\n * Precedence (later tier wins; within tier, later declaration wins):\n * 1. Generic effort (top-level IThinkingConfig.effort) → common-subset mapping\n * 2. Provider-generic blocks (matching provider, no models filter)\n * 3. Model-specific blocks (matching provider + models array includes resolved model)\n * 4. Other blocks (provider: 'other', models includes resolved model) — same tier as 3\n *\n * Blocks whose provider does not match are silently skipped.\n *\n * Note: when the resolved OpenAI effort is `'none'`, reasoning is disabled and\n * temperature is accepted; see {@link IOpenAiThinkingConfig.effort} for the full\n * hybrid-mode semantics.\n *\n * @param config - The caller's IThinkingConfig\n * @param resolvedModel - The concrete model string after registry resolution\n * @param discriminator - Coarse provider family\n * @returns Merged effective config for wire encoding\n * @internal\n */\nexport function mergeThinkingConfig(\n config: IThinkingConfig,\n resolvedModel: string,\n discriminator: ThinkingProviderDiscriminator\n): Result<IResolvedThinkingConfig> {\n let resolved: IResolvedThinkingConfig = {};\n\n // Tier 1: generic effort → common-subset mapping\n if (config.effort !== undefined) {\n switch (discriminator) {\n case 'anthropic':\n // Anthropic has no 'none' value: \"off\" means no `thinking` wire param at all,\n // so 'none' leaves `anthropicEffort` unset rather than mapping to a value. That\n // also satisfies checkTemperatureConflict's anthropic gate (which fails only when\n // anthropicEffort is set), so temperature survives without any special-casing there.\n if (config.effort !== 'none') {\n resolved = { ...resolved, anthropicEffort: genericEffortToAnthropic(config.effort) };\n }\n break;\n case 'openai':\n resolved = { ...resolved, openAiEffort: genericEffortToOpenAi(config.effort) };\n break;\n case 'google':\n resolved = { ...resolved, geminiThinkingBudget: genericEffortToGemini(config.effort) };\n break;\n case 'xai':\n resolved = { ...resolved, xaiEffort: genericEffortToXai(config.effort) };\n break;\n }\n }\n\n if (!config.providers) {\n return succeed(resolved);\n }\n\n // Partition into tiers 2 and 3+4\n const applicableBlocks = config.providers.filter((b) => blockApplies(b, resolvedModel, discriminator));\n const genericBlocks = applicableBlocks.filter((b) => !isModelSpecific(b));\n const specificBlocks = applicableBlocks.filter((b) => isModelSpecific(b));\n\n // Tier 2: provider-generic blocks (declaration order; later wins)\n for (const block of genericBlocks) {\n resolved = applyBlock(resolved, block, discriminator);\n }\n\n // Tier 3+4: model-specific + other blocks (declaration order; later wins)\n for (const block of specificBlocks) {\n resolved = applyBlock(resolved, block, discriminator);\n }\n\n return succeed(resolved);\n}\n\n/**\n * Applies a single config block to the accumulated resolved config.\n * @internal\n */\nfunction applyBlock(\n current: IResolvedThinkingConfig,\n block: IThinkingProviderConfig,\n discriminator: ThinkingProviderDiscriminator\n): IResolvedThinkingConfig {\n if (block.provider === 'other') {\n const merged =\n current.otherParams !== undefined ? { ...current.otherParams, ...block.config } : block.config;\n return { ...current, otherParams: merged };\n }\n\n switch (discriminator) {\n case 'anthropic':\n if (block.provider === 'anthropic') {\n if (block.config.effort !== undefined) {\n return { ...current, anthropicEffort: block.config.effort };\n }\n }\n break;\n case 'openai':\n if (block.provider === 'openai') {\n if (block.config.effort !== undefined) {\n return { ...current, openAiEffort: block.config.effort };\n }\n }\n break;\n case 'google':\n if (block.provider === 'google') {\n const updated: IResolvedThinkingConfig = { ...current };\n if (block.config.thinkingBudget !== undefined) {\n return { ...updated, geminiThinkingBudget: block.config.thinkingBudget };\n }\n return updated;\n }\n /* c8 ignore next - blockApplies guarantees provider match; unreachable for google */\n break;\n case 'xai':\n if (block.provider === 'xai') {\n if (block.config.effort !== undefined) {\n return { ...current, xaiEffort: block.config.effort };\n }\n }\n break;\n }\n return current;\n}\n\n// ============================================================================\n// Temperature conflict check\n// ============================================================================\n\n/**\n * Returns a Result.fail if temperature conflicts with thinking mode for the\n * given provider, otherwise succeed(undefined).\n *\n * Per D4: temperature + thinking = Result.fail for Anthropic, OpenAI (when\n * effective effort is non-null and non-'none'), and xAI (conservative default\n * pending live verification). Gemini accepts temperature alongside thinking.\n *\n * @internal\n */\nexport function checkTemperatureConflict(\n resolved: IResolvedThinkingConfig,\n discriminator: ThinkingProviderDiscriminator,\n temperature: number | undefined\n): Result<undefined> {\n if (temperature === undefined) {\n return succeed(undefined);\n }\n\n switch (discriminator) {\n case 'anthropic':\n if (resolved.anthropicEffort !== undefined) {\n return fail(\n 'thinking mode is not compatible with temperature on provider anthropic: remove temperature or disable thinking'\n );\n }\n break;\n case 'openai':\n // 'none' disables reasoning; temperature is accepted in that case\n if (resolved.openAiEffort !== undefined && resolved.openAiEffort !== 'none') {\n return fail(\n 'thinking mode is not compatible with temperature on provider openai: remove temperature or disable thinking'\n );\n }\n break;\n case 'xai':\n // Conservative default: fail if xAI effort is active (per D8 — live verification pending)\n if (resolved.xaiEffort !== undefined && resolved.xaiEffort !== 'none') {\n return fail(\n 'thinking mode is not compatible with temperature on provider xai: remove temperature or disable thinking'\n );\n }\n break;\n case 'google':\n // Gemini accepts temperature alongside thinkingConfig — no conflict\n break;\n }\n return succeed(undefined);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"thinkingOptionsResolver.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/thinkingOptionsResolver.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;;AAkCZ,gEAaC;AA6DD,sEA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M,EAAE,CAAC;gBAC5E,OAAO,IAAA,eAAI,EACT,6GAA6G,CAC9G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,KAAK;YACR,0FAA0F;YAC1F,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS,IAAI,QAAQ,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC;gBACtE,OAAO,IAAA,eAAI,EACT,0GAA0G,CAC3G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,QAAQ;YACX,oEAAoE;YACpE,MAAM;IACV,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;AAC5B,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 * Merge logic and runtime validation for thinking/reasoning options.\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { fail, Result, succeed } from '@fgv/ts-utils';\n\nimport type {\n IThinkingConfig,\n IThinkingProviderConfig,\n IAnthropicThinkingConfig,\n IOpenAiThinkingConfig,\n IXAiThinkingConfig\n} from './model';\n\n// ============================================================================\n// Provider discriminator\n// ============================================================================\n\n/**\n * Coarse provider family used to discriminate thinking config blocks.\n * Maps from AiProviderId to the IThinkingProviderConfig `provider` discriminator.\n * @internal\n */\nexport type ThinkingProviderDiscriminator = 'anthropic' | 'openai' | 'google' | 'xai';\n\n/**\n * Maps an AiProviderId (registry key) to the coarse family discriminator used\n * in IThinkingProviderConfig. Returns undefined for providers without thinking support.\n * @internal\n */\nexport function providerDiscriminatorForId(providerId: string): ThinkingProviderDiscriminator | undefined {\n switch (providerId) {\n case 'anthropic':\n return 'anthropic';\n case 'openai':\n return 'openai';\n case 'google-gemini':\n return 'google';\n case 'xai-grok':\n return 'xai';\n default:\n return undefined;\n }\n}\n\n// ============================================================================\n// Resolved wire shape\n// ============================================================================\n\n/**\n * Resolved thinking wire parameters for a specific provider, after merging\n * all applicable config blocks. Ready for provider-specific wire encoding.\n *\n * Callers that pre-resolve thinking config outside of the standard streaming\n * helpers (e.g. `executeClientToolTurn`) accept this type via the\n * `resolvedThinking` parameter and pass it directly to the adapter layer.\n * @public\n */\nexport interface IResolvedThinkingConfig {\n /**\n * Anthropic: effort level. The emit-site picks one of two wire shapes — on the\n * Claude 5 family it sends the effort string verbatim in `output_config` with no\n * budget; on older models it converts via `anthropicEffortToBudgetTokens`. See\n * {@link AiAssist.IAnthropicThinkingConfig.effort}.\n */\n readonly anthropicEffort?: IAnthropicThinkingConfig['effort'];\n /** OpenAI Chat: reasoning_effort value; OpenAI Responses: reasoning.effort */\n readonly openAiEffort?: IOpenAiThinkingConfig['effort'];\n /** Gemini: generationConfig.thinkingConfig.thinkingBudget */\n readonly geminiThinkingBudget?: number;\n /** xAI: reasoning_effort value (omit for grok-4) */\n readonly xaiEffort?: IXAiThinkingConfig['effort'];\n /** Other/passthrough: merged verbatim into wire request */\n readonly otherParams?: JsonObject;\n}\n\n// ============================================================================\n// Common-subset mapping\n// ============================================================================\n\n/**\n * Maps generic effort to Anthropic wire effort. Anthropic has no 'none' value in its\n * own vocabulary — the caller (tier 1 of `mergeThinkingConfig`) handles `'none'` by\n * skipping this mapping entirely, so `anthropicEffort` stays unset and the emit site\n * omits the `thinking` wire param. @internal\n */\nfunction genericEffortToAnthropic(effort: 'low' | 'medium' | 'high'): IAnthropicThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n/**\n * Maps Anthropic effort level to the `thinking.budget_tokens` integer that the\n * Anthropic API requires when `thinking.type === 'enabled'`.\n *\n * Policy: low = 2048, medium = 8192, high = 24000, max = 32000. The lower three\n * align with the Anthropic-published minimum-meaningful budget, a mid-range\n * default, and a \"deep thinking\" allotment respectively. `max` is the deepest\n * allotment and stays within typical model limits.\n *\n * Only reached for models outside the Claude 5 family — the adaptive-thinking path\n * sends no budget at all.\n *\n * @public\n */\nexport function anthropicEffortToBudgetTokens(\n effort: NonNullable<IAnthropicThinkingConfig['effort']>\n): number {\n switch (effort) {\n case 'low':\n return 2048;\n case 'medium':\n return 8192;\n case 'high':\n return 24000;\n case 'max':\n return 32000;\n }\n}\n\n/**\n * Maps generic effort to OpenAI wire effort. @internal\n */\nfunction genericEffortToOpenAi(effort: 'none' | 'low' | 'medium' | 'high'): IOpenAiThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n/**\n * Maps generic effort to Gemini thinkingBudget. `'none'` maps to `0` — Gemini's own\n * off value on the wire, though `IGeminiThinkingConfig.thinkingBudget` documents that `0`\n * is valid only on Flash/Flash-Lite and errors on Pro; this mapping is not model-aware and\n * inherits that same caveat (not a new gap — an explicit `providers` block could already\n * request `thinkingBudget: 0` on any model). @internal\n */\nfunction genericEffortToGemini(effort: 'none' | 'low' | 'medium' | 'high'): number {\n switch (effort) {\n case 'none':\n return 0;\n case 'low':\n return 1024;\n case 'medium':\n return 4096;\n case 'high':\n return 8192;\n }\n}\n\n/**\n * Maps generic effort to xAI reasoning_effort. @internal\n */\nfunction genericEffortToXai(effort: 'none' | 'low' | 'medium' | 'high'): IXAiThinkingConfig['effort'] {\n return effort; // 1:1 mapping for the common subset\n}\n\n// ============================================================================\n// Block applicability\n// ============================================================================\n\n/**\n * Returns true when a provider config block applies to the given resolved model\n * and provider discriminator.\n *\n * Applicability rules:\n * - provider must match the coarse discriminator\n * - if models array is present, resolved model must match (exact or base-name prefix)\n * - if models array is absent, the block is provider-generic (applies to all)\n *\n * Prefix matching supports versioned IDs: `'claude-sonnet-4-5'` matches resolved\n * `'claude-sonnet-4-5-20250929'`. An entry matches when it equals the resolved model\n * or when the resolved model starts with the entry followed by a `-`.\n *\n * 'other' blocks require models to be present (enforced by the type).\n * @internal\n */\nfunction modelNameMatches(resolvedModel: string, name: string): boolean {\n return resolvedModel === name || resolvedModel.startsWith(`${name}-`);\n}\n\nfunction blockApplies(\n block: IThinkingProviderConfig,\n resolvedModel: string,\n discriminator: ThinkingProviderDiscriminator\n): boolean {\n if (block.provider !== discriminator && block.provider !== 'other') {\n return false;\n }\n if (block.provider === 'other') {\n return block.models.some((name) => modelNameMatches(resolvedModel, name));\n }\n if (block.models !== undefined) {\n return (block.models as ReadonlyArray<string>).some((name) => modelNameMatches(resolvedModel, name));\n }\n return true; // provider-generic block\n}\n\n/**\n * Returns true when a block is model-specific (has a models array).\n * Used to partition blocks into merge tiers.\n * @internal\n */\nfunction isModelSpecific(block: IThinkingProviderConfig): boolean {\n if (block.provider === 'other') {\n return true; // other blocks always require models\n }\n return block.models !== undefined;\n}\n\n// ============================================================================\n// Merge function\n// ============================================================================\n\n/**\n * Resolves the effective thinking wire parameters for a specific resolved model\n * by merging all applicable config blocks in precedence order.\n *\n * Precedence (later tier wins; within tier, later declaration wins):\n * 1. Generic effort (top-level IThinkingConfig.effort) → common-subset mapping\n * 2. Provider-generic blocks (matching provider, no models filter)\n * 3. Model-specific blocks (matching provider + models array includes resolved model)\n * 4. Other blocks (provider: 'other', models includes resolved model) — same tier as 3\n *\n * Blocks whose provider does not match are silently skipped.\n *\n * Note: when the resolved OpenAI effort is `'none'`, reasoning is disabled and\n * temperature is accepted; see {@link IOpenAiThinkingConfig.effort} for the full\n * hybrid-mode semantics.\n *\n * @param config - The caller's IThinkingConfig\n * @param resolvedModel - The concrete model string after registry resolution\n * @param discriminator - Coarse provider family\n * @returns Merged effective config for wire encoding\n * @internal\n */\nexport function mergeThinkingConfig(\n config: IThinkingConfig,\n resolvedModel: string,\n discriminator: ThinkingProviderDiscriminator\n): Result<IResolvedThinkingConfig> {\n let resolved: IResolvedThinkingConfig = {};\n\n // Tier 1: generic effort → common-subset mapping\n if (config.effort !== undefined) {\n switch (discriminator) {\n case 'anthropic':\n // Anthropic has no 'none' value: \"off\" means no `thinking` wire param at all,\n // so 'none' leaves `anthropicEffort` unset rather than mapping to a value. That\n // also satisfies checkTemperatureConflict's anthropic gate (which fails only when\n // anthropicEffort is set), so temperature survives without any special-casing there.\n if (config.effort !== 'none') {\n resolved = { ...resolved, anthropicEffort: genericEffortToAnthropic(config.effort) };\n }\n break;\n case 'openai':\n resolved = { ...resolved, openAiEffort: genericEffortToOpenAi(config.effort) };\n break;\n case 'google':\n resolved = { ...resolved, geminiThinkingBudget: genericEffortToGemini(config.effort) };\n break;\n case 'xai':\n resolved = { ...resolved, xaiEffort: genericEffortToXai(config.effort) };\n break;\n }\n }\n\n if (!config.providers) {\n return succeed(resolved);\n }\n\n // Partition into tiers 2 and 3+4\n const applicableBlocks = config.providers.filter((b) => blockApplies(b, resolvedModel, discriminator));\n const genericBlocks = applicableBlocks.filter((b) => !isModelSpecific(b));\n const specificBlocks = applicableBlocks.filter((b) => isModelSpecific(b));\n\n // Tier 2: provider-generic blocks (declaration order; later wins)\n for (const block of genericBlocks) {\n resolved = applyBlock(resolved, block, discriminator);\n }\n\n // Tier 3+4: model-specific + other blocks (declaration order; later wins)\n for (const block of specificBlocks) {\n resolved = applyBlock(resolved, block, discriminator);\n }\n\n return succeed(resolved);\n}\n\n/**\n * Applies a single config block to the accumulated resolved config.\n * @internal\n */\nfunction applyBlock(\n current: IResolvedThinkingConfig,\n block: IThinkingProviderConfig,\n discriminator: ThinkingProviderDiscriminator\n): IResolvedThinkingConfig {\n if (block.provider === 'other') {\n const merged =\n current.otherParams !== undefined ? { ...current.otherParams, ...block.config } : block.config;\n return { ...current, otherParams: merged };\n }\n\n switch (discriminator) {\n case 'anthropic':\n if (block.provider === 'anthropic') {\n if (block.config.effort !== undefined) {\n return { ...current, anthropicEffort: block.config.effort };\n }\n }\n break;\n case 'openai':\n if (block.provider === 'openai') {\n if (block.config.effort !== undefined) {\n return { ...current, openAiEffort: block.config.effort };\n }\n }\n break;\n case 'google':\n if (block.provider === 'google') {\n const updated: IResolvedThinkingConfig = { ...current };\n if (block.config.thinkingBudget !== undefined) {\n return { ...updated, geminiThinkingBudget: block.config.thinkingBudget };\n }\n return updated;\n }\n /* c8 ignore next - blockApplies guarantees provider match; unreachable for google */\n break;\n case 'xai':\n if (block.provider === 'xai') {\n if (block.config.effort !== undefined) {\n return { ...current, xaiEffort: block.config.effort };\n }\n }\n break;\n }\n return current;\n}\n\n// ============================================================================\n// Temperature conflict check\n// ============================================================================\n\n/**\n * Returns a Result.fail if temperature conflicts with thinking mode for the\n * given provider, otherwise succeed(undefined).\n *\n * Per D4: temperature + thinking = Result.fail for Anthropic, OpenAI (when\n * effective effort is non-null and non-'none'), and xAI (conservative default\n * pending live verification). Gemini accepts temperature alongside thinking.\n *\n * @internal\n */\nexport function checkTemperatureConflict(\n resolved: IResolvedThinkingConfig,\n discriminator: ThinkingProviderDiscriminator,\n temperature: number | undefined\n): Result<undefined> {\n if (temperature === undefined) {\n return succeed(undefined);\n }\n\n switch (discriminator) {\n case 'anthropic':\n if (resolved.anthropicEffort !== undefined) {\n return fail(\n 'thinking mode is not compatible with temperature on provider anthropic: remove temperature or disable thinking'\n );\n }\n break;\n case 'openai':\n // 'none' disables reasoning; temperature is accepted in that case\n if (resolved.openAiEffort !== undefined && resolved.openAiEffort !== 'none') {\n return fail(\n 'thinking mode is not compatible with temperature on provider openai: remove temperature or disable thinking'\n );\n }\n break;\n case 'xai':\n // Conservative default: fail if xAI effort is active (per D8 — live verification pending)\n if (resolved.xaiEffort !== undefined && resolved.xaiEffort !== 'none') {\n return fail(\n 'thinking mode is not compatible with temperature on provider xai: remove temperature or disable thinking'\n );\n }\n break;\n case 'google':\n // Gemini accepts temperature alongside thinkingConfig — no conflict\n break;\n }\n return succeed(undefined);\n}\n"]}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { type Result } from '@fgv/ts-utils';
|
|
15
15
|
import { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';
|
|
16
|
+
import type { IAiCompletionUsage } from './usageTypes';
|
|
16
17
|
/**
|
|
17
18
|
* Built-in server-side tool types supported across providers.
|
|
18
19
|
* @public
|
|
@@ -24,11 +25,23 @@ export type AiServerToolType = 'web_search';
|
|
|
24
25
|
*/
|
|
25
26
|
export interface IAiWebSearchToolConfig {
|
|
26
27
|
readonly type: 'web_search';
|
|
27
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* Optional: restrict search to these domains.
|
|
30
|
+
* Reaches Anthropic and the OpenAI/xAI Responses API; ignored on Gemini,
|
|
31
|
+
* whose `google_search` tool takes no configuration at all.
|
|
32
|
+
*/
|
|
28
33
|
readonly allowedDomains?: ReadonlyArray<string>;
|
|
29
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Optional: exclude these domains from search.
|
|
36
|
+
* Same reach as {@link AiAssist.IAiWebSearchToolConfig.allowedDomains}:
|
|
37
|
+
* Anthropic and OpenAI/xAI, ignored on Gemini.
|
|
38
|
+
*/
|
|
30
39
|
readonly blockedDomains?: ReadonlyArray<string>;
|
|
31
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* Optional: max number of searches per request.
|
|
42
|
+
* **Anthropic only** — emitted as `max_uses` by the Anthropic formatter and
|
|
43
|
+
* read nowhere else, so it is silently ignored on OpenAI/xAI and Gemini.
|
|
44
|
+
*/
|
|
32
45
|
readonly maxUses?: number;
|
|
33
46
|
/**
|
|
34
47
|
* Optional: enable image understanding during web search.
|
|
@@ -324,5 +337,50 @@ export interface IAiClientToolTurnResult {
|
|
|
324
337
|
* because the pinned model cannot ground and call functions in one request.
|
|
325
338
|
*/
|
|
326
339
|
readonly toolConflicts: IAiToolConflictReport;
|
|
340
|
+
/**
|
|
341
|
+
* Token usage for this turn's provider call, when the provider reports it.
|
|
342
|
+
*
|
|
343
|
+
* @remarks
|
|
344
|
+
* The same `IAiCompletionUsage` the plain completion paths carry — normalized
|
|
345
|
+
* cache reads/writes, output and total input tokens, and a `reports` level
|
|
346
|
+
* saying which of those the provider is able to tell you. Sourced from the
|
|
347
|
+
* terminal `done` event of the underlying stream, so it is exactly what a
|
|
348
|
+
* caller watching `events` would see.
|
|
349
|
+
*
|
|
350
|
+
* Reading it here spares you *inspecting* the event stream, not *driving* it:
|
|
351
|
+
* `nextTurn` only resolves once `events` has been iterated to completion, the
|
|
352
|
+
* same as every other field on this interface.
|
|
353
|
+
*
|
|
354
|
+
* **One call, one usage.** `executeClientToolTurn` makes a single provider
|
|
355
|
+
* call per invocation; the multi-round loop is driven by the caller
|
|
356
|
+
* re-invoking with `continuationMessages`. So each result's `usage` already
|
|
357
|
+
* *is* one round's usage, and a host accumulating a per-turn total sums the
|
|
358
|
+
* results of its own loop. There is deliberately no `perRound` array here —
|
|
359
|
+
* it could only ever have one entry.
|
|
360
|
+
*
|
|
361
|
+
* **Optional on purpose, unlike `toolConflicts`.** The library always knows
|
|
362
|
+
* what it did to your tools, so a silent `toolConflicts` would be a defect
|
|
363
|
+
* and it is required. It cannot always know what a turn cost, so a required
|
|
364
|
+
* `usage` could only be satisfied by inventing one — the exact failure
|
|
365
|
+
* {@link AiAssist.IAiCompletionUsage.reports} exists to prevent.
|
|
366
|
+
*
|
|
367
|
+
* Absent means **no normalized usage is being exposed**, which covers two
|
|
368
|
+
* cases, the same as on {@link AiAssist.IAiCompletionResponse.usage} and
|
|
369
|
+
* {@link AiAssist.IAiStreamDone.usage}:
|
|
370
|
+
*
|
|
371
|
+
* - the provider reported nothing; or
|
|
372
|
+
* - the provider reported something the library declines to normalize,
|
|
373
|
+
* because this descriptor is outside
|
|
374
|
+
* {@link AiAssist.supportsCacheUsageReporting}. Groq, Mistral, Ollama and
|
|
375
|
+
* self-hosted `openai-compat` share the OpenAI-format adapter but have
|
|
376
|
+
* unverified usage shapes, so a raw `usage` block from one of them is
|
|
377
|
+
* dropped rather than stamped with a cache-reporting level it may not
|
|
378
|
+
* have earned.
|
|
379
|
+
*
|
|
380
|
+
* Either way it is never a fabricated zero. If you need to tell the two
|
|
381
|
+
* apart, the descriptor answers it: the second case is a property of the
|
|
382
|
+
* provider you picked, not of the turn.
|
|
383
|
+
*/
|
|
384
|
+
readonly usage?: IAiCompletionUsage;
|
|
327
385
|
}
|
|
328
386
|
//# sourceMappingURL=toolTypes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolTypes.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolTypes.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"toolTypes.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolTypes.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAMvD;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,YAA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H,QAAQ,CAAC,YAAY,EAAE,yBAAyB,GAAG,SAAS,CAAC;IAC7D,qEAAqE;IACrE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;;;;;;OAQG;IACH,QAAQ,CAAC,aAAa,EAAE,qBAAqB,CAAC;IAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2CG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,kBAAkB,CAAC;CACrC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolTypes.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolTypes.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","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 * Tool types for AI assist: server-side tool configs, client-defined (\"function\")\n * tools, the streaming events a tool call produces, the provider-exclusion vocabulary,\n * and the client-tool round-trip result types.\n *\n * @remarks\n * Split out of `model.ts` when the provider-exclusion types pushed that file past the\n * 2000-line lint ceiling. The cut is along a real seam rather than an arbitrary one:\n * everything here is about tools and nothing here depends on the rest of `model.ts`,\n * so the module is a leaf. `model.ts` re-exports all of it, which is why no consumer\n * import changed.\n * @packageDocumentation\n */\n\nimport { type Result } from '@fgv/ts-utils';\nimport { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';\n\n// ============================================================================\n// Server-Side Tools\n// ============================================================================\n\n/**\n * Built-in server-side tool types supported across providers.\n * @public\n */\nexport type AiServerToolType = 'web_search';\n\n/**\n * Configuration specific to web search tools.\n * @public\n */\nexport interface IAiWebSearchToolConfig {\n readonly type: 'web_search';\n /** Optional: restrict search to these domains. */\n readonly allowedDomains?: ReadonlyArray<string>;\n /** Optional: exclude these domains from search. */\n readonly blockedDomains?: ReadonlyArray<string>;\n /** Optional: max number of searches per request. */\n readonly maxUses?: number;\n /**\n * Optional: enable image understanding during web search.\n * When true, the model can view and analyze images found during search.\n * Currently supported by xAI only; ignored by other providers.\n */\n readonly enableImageUnderstanding?: boolean;\n}\n\n/**\n * Union of all server-side tool configurations. Discriminated on `type`.\n * @public\n */\nexport type AiServerToolConfig = IAiWebSearchToolConfig;\n\n/**\n * Declares a tool as enabled/disabled in provider settings.\n * Tools are disabled by default — consuming apps must opt in explicitly.\n * @public\n */\nexport interface IAiToolEnablement {\n /** Which tool type. */\n readonly type: AiServerToolType;\n /** Whether this tool is enabled by default for this provider. */\n readonly enabled: boolean;\n /** Optional tool-specific configuration. */\n readonly config?: AiServerToolConfig;\n}\n\n// ============================================================================\n// Client-Defined Tools\n// ============================================================================\n\n/**\n * Behavior annotations for a client-defined tool.\n *\n * @remarks\n * These are **host-advisory-only hints** describing a tool's side-effect profile.\n * They are consumed by the host's tool loop (e.g. a before-execute gate) and are\n * **never serialized to the model** — the provider wire tool-schemas whitelist\n * `{name, description, parameters}` and ignore this field.\n *\n * Field names mirror MCP's `ToolAnnotations` (`@modelcontextprotocol/sdk`) 1:1 so\n * an MCP tool's annotations pass through unchanged. Per the MCP spec, all fields\n * are hints — a host should never make tool-use decisions based on annotations\n * received from an untrusted server without its own validation.\n *\n * @public\n */\nexport interface IAiToolAnnotations {\n /** Optional human-readable display title for the tool. */\n readonly title?: string;\n /** Hint: the tool does not modify its environment (read-only). */\n readonly readOnlyHint?: boolean;\n /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */\n readonly destructiveHint?: boolean;\n /** Hint: repeated calls with the same arguments have no additional effect. */\n readonly idempotentHint?: boolean;\n /** Hint: the tool interacts with an open world of external entities. */\n readonly openWorldHint?: boolean;\n}\n\n/**\n * Configuration for a client-defined (harness-supplied) tool.\n *\n * @remarks\n * The `parametersSchema` is the single source of truth for both the wire-format\n * JSON Schema sent to the provider (via `.toJson()`) and the runtime argument\n * validation (via `.validate(rawArgs)`). Use `JsonSchema.object(...)` from\n * `@fgv/ts-json-base` to author the schema as a const (e.g. `const mySchema = JsonSchema.object({...})`);\n * the static type `TParams` is then derived via `JsonSchema.Static<typeof mySchema>` —\n * no drift between wire schema and runtime validation.\n *\n * @public\n */\nexport interface IAiClientToolConfig<TParams = unknown> {\n /** Discriminator — always `'client_tool'`. */\n readonly type: 'client_tool';\n /** Tool name sent to the model (must be unique within a call). */\n readonly name: string;\n /** Human-readable description of what the tool does, shown to the model. */\n readonly description: string;\n /**\n * JSON Schema validator for the tool's parameters. Emits wire format via\n * `.toJson()` and validates model-returned args via `.validate(rawArgs)`.\n */\n readonly parametersSchema: JsonSchema.ISchemaValidator<TParams>;\n /**\n * Optional host-advisory behavior annotations (read-only / destructive /\n * idempotent / open-world hints + display title). Consumed by the host's\n * tool loop; never serialized to the model. See {@link AiAssist.IAiToolAnnotations}.\n */\n readonly annotations?: IAiToolAnnotations;\n}\n\n/**\n * A client-defined tool: configuration + execution callback pair.\n *\n * @remarks\n * The `execute` callback receives typed `TParams` (already validated by\n * `config.parametersSchema.validate()`) and returns a `Promise<Result<unknown>>`.\n * Thrown errors are caught via `captureAsyncResult` in the round-trip helper.\n *\n * @public\n */\nexport interface IAiClientTool<TParams = unknown> {\n /** The tool's configuration (name, description, parameters schema). */\n readonly config: IAiClientToolConfig<TParams>;\n /**\n * Execute the tool with validated parameters.\n * @param args - Typed arguments, already validated against `config.parametersSchema`.\n * @returns A `Promise<Result<unknown>>` — the result is stringified and sent back to the model.\n */\n readonly execute: (args: TParams) => Promise<Result<unknown>>;\n}\n\n/**\n * Union of all tool configurations: server-side or client-defined.\n * Discriminated on `type`.\n * @public\n */\nexport type AiToolConfig = AiServerToolConfig | IAiClientToolConfig;\n\n// ============================================================================\n// Client Tool Streaming Events\n// ============================================================================\n\n/**\n * Emitted when a client-defined tool call begins streaming. Carries the tool name\n * and optional provider-assigned call ID (Anthropic / OpenAI Responses API; absent\n * for Gemini which does not assign call IDs).\n * @public\n */\nexport interface IAiStreamToolUseStart {\n readonly type: 'client-tool-call-start';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier (Anthropic: `toolu_*`; OpenAI: `call_*`).\n * Absent for Gemini (correlation by name).\n */\n readonly callId?: string;\n}\n\n/**\n * Emitted when a client-defined tool call is complete and its arguments are fully\n * accumulated. The `args` object is the fully parsed JSON object — no further\n * streaming deltas follow for this call.\n * @public\n */\nexport interface IAiStreamToolUseDelta {\n readonly type: 'client-tool-call-done';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The fully accumulated and parsed tool arguments. */\n readonly args: JsonObject;\n}\n\n/**\n * Emitted after a client-defined tool has been executed and the result is ready\n * to be fed back to the model in the round-trip continuation.\n * @public\n */\nexport interface IAiStreamToolUseComplete {\n readonly type: 'client-tool-result';\n /** The name of the client tool that was executed. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The stringified result returned by the tool's execute callback. */\n readonly result: string;\n /** Whether the tool execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n// ============================================================================\n// Server/Client Tool Conflicts\n// ============================================================================\n\n/**\n * What to do when a request would combine a server tool with client (function)\n * tools on a provider that declares the two mutually exclusive (see\n * `IAiProviderDescriptor.serverToolsExclusiveWithClientTools`).\n *\n * @remarks\n * - `'drop-server-tools'` (the default) removes the offending server tools and\n * keeps every client tool. Client tools are what the host registered\n * explicitly for this turn; a built-in like grounding is a per-provider\n * nicety, and dropping it degrades the turn rather than losing it.\n * - `'prefer-server-tools'` is the mirror image: keep the server tools and drop\n * every client tool. For hosts whose turn is *about* the grounded answer.\n * - `'fail'` refuses the request up front with a message naming the conflict —\n * the behavior before this policy existed. For hosts that would rather\n * choose themselves than have either half silently disappear.\n *\n * Whichever is chosen, what actually happened is reported, never inferred: see\n * {@link AiAssist.IAiToolConflictReport}.\n * @public\n */\nexport type AiToolConflictPolicy = 'drop-server-tools' | 'prefer-server-tools' | 'fail';\n\n/**\n * What the conflict resolution did to a turn's tools.\n *\n * @remarks\n * Required on {@link AiAssist.IAiClientToolTurnResult}, not optional, for the same reason\n * `structuredOutput` is required on a completion response: an absent report is\n * three-ways ambiguous — nothing conflicted / this build predates the feature /\n * the resolution ran and said nothing — and disambiguating exactly that is what\n * it is for. A turn where nothing conflicted reports the policy that was in\n * force and two empty arrays.\n * @public\n */\nexport interface IAiToolConflictReport {\n /** The policy that was in force for this turn (the default when none was passed). */\n readonly policy: AiToolConflictPolicy;\n /** Server tool types removed from the request. Empty when nothing was dropped. */\n readonly droppedServerTools: ReadonlyArray<AiServerToolType>;\n /** Names of client tools removed from the request. Empty when nothing was dropped. */\n readonly droppedClientTools: ReadonlyArray<string>;\n}\n\n// ============================================================================\n// Client Tool Round-Trip Types\n// ============================================================================\n\n/**\n * Summary of a single client tool call within a turn: the tool name, call ID,\n * raw arguments, execution result, and whether the execution was an error.\n * @public\n */\nexport interface IAiClientToolCallSummary {\n /** The name of the tool that was called. */\n readonly toolName: string;\n /** Provider-assigned call identifier (absent for Gemini). */\n readonly callId?: string;\n /** The fully accumulated raw arguments object as parsed JSON. */\n readonly args: JsonObject;\n /** The stringified result (success value or error message). */\n readonly result: string;\n /** Whether execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n/**\n * The provider-specific continuation data needed to build the follow-up request\n * for the next round of the conversation.\n *\n * @remarks\n * `messages` are provider-native request objects (Anthropic: content-block arrays,\n * OpenAI Responses API: input items, Gemini: content parts). The continuation\n * builder in `clientToolContinuationBuilder.ts` populates this.\n *\n * @public\n */\nexport interface IAiClientToolContinuation {\n /**\n * **Cumulative** provider-native wire-format message objects covering all\n * tool rounds so far. On each turn, `executeClientToolTurn` prepends the\n * inbound `continuationMessages` so that this array always contains the\n * complete wire tail from round 1 through the current round.\n *\n * To drive a multi-round loop, simply **replace** `continuationMessages`\n * with this value — do not manually concatenate:\n *\n * ```ts\n * let tail: JsonObject[] | undefined;\n * while (true) {\n * const { events, nextTurn } = executeClientToolTurn({\n * ..., continuationMessages: tail\n * }).orThrow();\n * for await (const e of events) { /* observe *\\/ }\n * const outcome = (await nextTurn).orThrow();\n * if (!outcome.continuation) break;\n * tail = [...outcome.continuation.messages]; // replace — already cumulative\n * }\n * ```\n *\n * The exact shape is provider-native and may include provider-specific\n * blocks (e.g. Anthropic thinking/redacted_thinking/tool_use, OpenAI\n * function_call/function_call_output items, Gemini functionCall/functionResponse\n * parts). These are NOT `IChatMessage[]` and must NOT be placed in the\n * `messages` parameter — the normalized-message path strips provider-native\n * fields (thinking signatures, redacted_thinking data) that the server\n * requires for continuation validation.\n *\n * `toolCallsSummary` is per-round only (the calls executed in the current\n * turn). Only `messages` is cumulative.\n */\n readonly messages: ReadonlyArray<JsonObject>;\n /** Summary of each tool call executed in this turn (per-round, not cumulative). */\n readonly toolCallsSummary: ReadonlyArray<IAiClientToolCallSummary>;\n}\n\n/**\n * The result of a single client-tool turn: the optional continuation for the next\n * call (absent when no tool calls occurred) and whether the stream was truncated.\n * @public\n */\nexport interface IAiClientToolTurnResult {\n /**\n * The continuation data for the next round-trip. `undefined` when the model\n * completed without invoking any client tools.\n */\n readonly continuation: IAiClientToolContinuation | undefined;\n /** Whether the stream was truncated (token limit or stop reason). */\n readonly truncated: boolean;\n /** The full concatenated text from all `text-delta` events in this turn. */\n readonly fullText: string;\n /**\n * What the provider tool-conflict resolution did to this turn's tools.\n * Always present; empty arrays mean nothing conflicted.\n *\n * @remarks\n * Read this to tell the person (or the model, on a later turn) that a\n * capability they expected was unavailable — e.g. that web search was dropped\n * because the pinned model cannot ground and call functions in one request.\n */\n readonly toolConflicts: IAiToolConflictReport;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"toolTypes.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolTypes.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","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 * Tool types for AI assist: server-side tool configs, client-defined (\"function\")\n * tools, the streaming events a tool call produces, the provider-exclusion vocabulary,\n * and the client-tool round-trip result types.\n *\n * @remarks\n * Split out of `model.ts` when the provider-exclusion types pushed that file past the\n * 2000-line lint ceiling. The cut is along a real seam rather than an arbitrary one:\n * everything here is about tools and nothing here depends on the rest of `model.ts`,\n * so the module is a leaf. `model.ts` re-exports all of it, which is why no consumer\n * import changed.\n * @packageDocumentation\n */\n\nimport { type Result } from '@fgv/ts-utils';\nimport { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';\nimport type { IAiCompletionUsage } from './usageTypes';\n\n// ============================================================================\n// Server-Side Tools\n// ============================================================================\n\n/**\n * Built-in server-side tool types supported across providers.\n * @public\n */\nexport type AiServerToolType = 'web_search';\n\n/**\n * Configuration specific to web search tools.\n * @public\n */\nexport interface IAiWebSearchToolConfig {\n readonly type: 'web_search';\n /**\n * Optional: restrict search to these domains.\n * Reaches Anthropic and the OpenAI/xAI Responses API; ignored on Gemini,\n * whose `google_search` tool takes no configuration at all.\n */\n readonly allowedDomains?: ReadonlyArray<string>;\n /**\n * Optional: exclude these domains from search.\n * Same reach as {@link AiAssist.IAiWebSearchToolConfig.allowedDomains}:\n * Anthropic and OpenAI/xAI, ignored on Gemini.\n */\n readonly blockedDomains?: ReadonlyArray<string>;\n /**\n * Optional: max number of searches per request.\n * **Anthropic only** — emitted as `max_uses` by the Anthropic formatter and\n * read nowhere else, so it is silently ignored on OpenAI/xAI and Gemini.\n */\n readonly maxUses?: number;\n /**\n * Optional: enable image understanding during web search.\n * When true, the model can view and analyze images found during search.\n * Currently supported by xAI only; ignored by other providers.\n */\n readonly enableImageUnderstanding?: boolean;\n}\n\n/**\n * Union of all server-side tool configurations. Discriminated on `type`.\n * @public\n */\nexport type AiServerToolConfig = IAiWebSearchToolConfig;\n\n/**\n * Declares a tool as enabled/disabled in provider settings.\n * Tools are disabled by default — consuming apps must opt in explicitly.\n * @public\n */\nexport interface IAiToolEnablement {\n /** Which tool type. */\n readonly type: AiServerToolType;\n /** Whether this tool is enabled by default for this provider. */\n readonly enabled: boolean;\n /** Optional tool-specific configuration. */\n readonly config?: AiServerToolConfig;\n}\n\n// ============================================================================\n// Client-Defined Tools\n// ============================================================================\n\n/**\n * Behavior annotations for a client-defined tool.\n *\n * @remarks\n * These are **host-advisory-only hints** describing a tool's side-effect profile.\n * They are consumed by the host's tool loop (e.g. a before-execute gate) and are\n * **never serialized to the model** — the provider wire tool-schemas whitelist\n * `{name, description, parameters}` and ignore this field.\n *\n * Field names mirror MCP's `ToolAnnotations` (`@modelcontextprotocol/sdk`) 1:1 so\n * an MCP tool's annotations pass through unchanged. Per the MCP spec, all fields\n * are hints — a host should never make tool-use decisions based on annotations\n * received from an untrusted server without its own validation.\n *\n * @public\n */\nexport interface IAiToolAnnotations {\n /** Optional human-readable display title for the tool. */\n readonly title?: string;\n /** Hint: the tool does not modify its environment (read-only). */\n readonly readOnlyHint?: boolean;\n /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */\n readonly destructiveHint?: boolean;\n /** Hint: repeated calls with the same arguments have no additional effect. */\n readonly idempotentHint?: boolean;\n /** Hint: the tool interacts with an open world of external entities. */\n readonly openWorldHint?: boolean;\n}\n\n/**\n * Configuration for a client-defined (harness-supplied) tool.\n *\n * @remarks\n * The `parametersSchema` is the single source of truth for both the wire-format\n * JSON Schema sent to the provider (via `.toJson()`) and the runtime argument\n * validation (via `.validate(rawArgs)`). Use `JsonSchema.object(...)` from\n * `@fgv/ts-json-base` to author the schema as a const (e.g. `const mySchema = JsonSchema.object({...})`);\n * the static type `TParams` is then derived via `JsonSchema.Static<typeof mySchema>` —\n * no drift between wire schema and runtime validation.\n *\n * @public\n */\nexport interface IAiClientToolConfig<TParams = unknown> {\n /** Discriminator — always `'client_tool'`. */\n readonly type: 'client_tool';\n /** Tool name sent to the model (must be unique within a call). */\n readonly name: string;\n /** Human-readable description of what the tool does, shown to the model. */\n readonly description: string;\n /**\n * JSON Schema validator for the tool's parameters. Emits wire format via\n * `.toJson()` and validates model-returned args via `.validate(rawArgs)`.\n */\n readonly parametersSchema: JsonSchema.ISchemaValidator<TParams>;\n /**\n * Optional host-advisory behavior annotations (read-only / destructive /\n * idempotent / open-world hints + display title). Consumed by the host's\n * tool loop; never serialized to the model. See {@link AiAssist.IAiToolAnnotations}.\n */\n readonly annotations?: IAiToolAnnotations;\n}\n\n/**\n * A client-defined tool: configuration + execution callback pair.\n *\n * @remarks\n * The `execute` callback receives typed `TParams` (already validated by\n * `config.parametersSchema.validate()`) and returns a `Promise<Result<unknown>>`.\n * Thrown errors are caught via `captureAsyncResult` in the round-trip helper.\n *\n * @public\n */\nexport interface IAiClientTool<TParams = unknown> {\n /** The tool's configuration (name, description, parameters schema). */\n readonly config: IAiClientToolConfig<TParams>;\n /**\n * Execute the tool with validated parameters.\n * @param args - Typed arguments, already validated against `config.parametersSchema`.\n * @returns A `Promise<Result<unknown>>` — the result is stringified and sent back to the model.\n */\n readonly execute: (args: TParams) => Promise<Result<unknown>>;\n}\n\n/**\n * Union of all tool configurations: server-side or client-defined.\n * Discriminated on `type`.\n * @public\n */\nexport type AiToolConfig = AiServerToolConfig | IAiClientToolConfig;\n\n// ============================================================================\n// Client Tool Streaming Events\n// ============================================================================\n\n/**\n * Emitted when a client-defined tool call begins streaming. Carries the tool name\n * and optional provider-assigned call ID (Anthropic / OpenAI Responses API; absent\n * for Gemini which does not assign call IDs).\n * @public\n */\nexport interface IAiStreamToolUseStart {\n readonly type: 'client-tool-call-start';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier (Anthropic: `toolu_*`; OpenAI: `call_*`).\n * Absent for Gemini (correlation by name).\n */\n readonly callId?: string;\n}\n\n/**\n * Emitted when a client-defined tool call is complete and its arguments are fully\n * accumulated. The `args` object is the fully parsed JSON object — no further\n * streaming deltas follow for this call.\n * @public\n */\nexport interface IAiStreamToolUseDelta {\n readonly type: 'client-tool-call-done';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The fully accumulated and parsed tool arguments. */\n readonly args: JsonObject;\n}\n\n/**\n * Emitted after a client-defined tool has been executed and the result is ready\n * to be fed back to the model in the round-trip continuation.\n * @public\n */\nexport interface IAiStreamToolUseComplete {\n readonly type: 'client-tool-result';\n /** The name of the client tool that was executed. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The stringified result returned by the tool's execute callback. */\n readonly result: string;\n /** Whether the tool execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n// ============================================================================\n// Server/Client Tool Conflicts\n// ============================================================================\n\n/**\n * What to do when a request would combine a server tool with client (function)\n * tools on a provider that declares the two mutually exclusive (see\n * `IAiProviderDescriptor.serverToolsExclusiveWithClientTools`).\n *\n * @remarks\n * - `'drop-server-tools'` (the default) removes the offending server tools and\n * keeps every client tool. Client tools are what the host registered\n * explicitly for this turn; a built-in like grounding is a per-provider\n * nicety, and dropping it degrades the turn rather than losing it.\n * - `'prefer-server-tools'` is the mirror image: keep the server tools and drop\n * every client tool. For hosts whose turn is *about* the grounded answer.\n * - `'fail'` refuses the request up front with a message naming the conflict —\n * the behavior before this policy existed. For hosts that would rather\n * choose themselves than have either half silently disappear.\n *\n * Whichever is chosen, what actually happened is reported, never inferred: see\n * {@link AiAssist.IAiToolConflictReport}.\n * @public\n */\nexport type AiToolConflictPolicy = 'drop-server-tools' | 'prefer-server-tools' | 'fail';\n\n/**\n * What the conflict resolution did to a turn's tools.\n *\n * @remarks\n * Required on {@link AiAssist.IAiClientToolTurnResult}, not optional, for the same reason\n * `structuredOutput` is required on a completion response: an absent report is\n * three-ways ambiguous — nothing conflicted / this build predates the feature /\n * the resolution ran and said nothing — and disambiguating exactly that is what\n * it is for. A turn where nothing conflicted reports the policy that was in\n * force and two empty arrays.\n * @public\n */\nexport interface IAiToolConflictReport {\n /** The policy that was in force for this turn (the default when none was passed). */\n readonly policy: AiToolConflictPolicy;\n /** Server tool types removed from the request. Empty when nothing was dropped. */\n readonly droppedServerTools: ReadonlyArray<AiServerToolType>;\n /** Names of client tools removed from the request. Empty when nothing was dropped. */\n readonly droppedClientTools: ReadonlyArray<string>;\n}\n\n// ============================================================================\n// Client Tool Round-Trip Types\n// ============================================================================\n\n/**\n * Summary of a single client tool call within a turn: the tool name, call ID,\n * raw arguments, execution result, and whether the execution was an error.\n * @public\n */\nexport interface IAiClientToolCallSummary {\n /** The name of the tool that was called. */\n readonly toolName: string;\n /** Provider-assigned call identifier (absent for Gemini). */\n readonly callId?: string;\n /** The fully accumulated raw arguments object as parsed JSON. */\n readonly args: JsonObject;\n /** The stringified result (success value or error message). */\n readonly result: string;\n /** Whether execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n/**\n * The provider-specific continuation data needed to build the follow-up request\n * for the next round of the conversation.\n *\n * @remarks\n * `messages` are provider-native request objects (Anthropic: content-block arrays,\n * OpenAI Responses API: input items, Gemini: content parts). The continuation\n * builder in `clientToolContinuationBuilder.ts` populates this.\n *\n * @public\n */\nexport interface IAiClientToolContinuation {\n /**\n * **Cumulative** provider-native wire-format message objects covering all\n * tool rounds so far. On each turn, `executeClientToolTurn` prepends the\n * inbound `continuationMessages` so that this array always contains the\n * complete wire tail from round 1 through the current round.\n *\n * To drive a multi-round loop, simply **replace** `continuationMessages`\n * with this value — do not manually concatenate:\n *\n * ```ts\n * let tail: JsonObject[] | undefined;\n * while (true) {\n * const { events, nextTurn } = executeClientToolTurn({\n * ..., continuationMessages: tail\n * }).orThrow();\n * for await (const e of events) { /* observe *\\/ }\n * const outcome = (await nextTurn).orThrow();\n * if (!outcome.continuation) break;\n * tail = [...outcome.continuation.messages]; // replace — already cumulative\n * }\n * ```\n *\n * The exact shape is provider-native and may include provider-specific\n * blocks (e.g. Anthropic thinking/redacted_thinking/tool_use, OpenAI\n * function_call/function_call_output items, Gemini functionCall/functionResponse\n * parts). These are NOT `IChatMessage[]` and must NOT be placed in the\n * `messages` parameter — the normalized-message path strips provider-native\n * fields (thinking signatures, redacted_thinking data) that the server\n * requires for continuation validation.\n *\n * `toolCallsSummary` is per-round only (the calls executed in the current\n * turn). Only `messages` is cumulative.\n */\n readonly messages: ReadonlyArray<JsonObject>;\n /** Summary of each tool call executed in this turn (per-round, not cumulative). */\n readonly toolCallsSummary: ReadonlyArray<IAiClientToolCallSummary>;\n}\n\n/**\n * The result of a single client-tool turn: the optional continuation for the next\n * call (absent when no tool calls occurred) and whether the stream was truncated.\n * @public\n */\nexport interface IAiClientToolTurnResult {\n /**\n * The continuation data for the next round-trip. `undefined` when the model\n * completed without invoking any client tools.\n */\n readonly continuation: IAiClientToolContinuation | undefined;\n /** Whether the stream was truncated (token limit or stop reason). */\n readonly truncated: boolean;\n /** The full concatenated text from all `text-delta` events in this turn. */\n readonly fullText: string;\n /**\n * What the provider tool-conflict resolution did to this turn's tools.\n * Always present; empty arrays mean nothing conflicted.\n *\n * @remarks\n * Read this to tell the person (or the model, on a later turn) that a\n * capability they expected was unavailable — e.g. that web search was dropped\n * because the pinned model cannot ground and call functions in one request.\n */\n readonly toolConflicts: IAiToolConflictReport;\n /**\n * Token usage for this turn's provider call, when the provider reports it.\n *\n * @remarks\n * The same `IAiCompletionUsage` the plain completion paths carry — normalized\n * cache reads/writes, output and total input tokens, and a `reports` level\n * saying which of those the provider is able to tell you. Sourced from the\n * terminal `done` event of the underlying stream, so it is exactly what a\n * caller watching `events` would see.\n *\n * Reading it here spares you *inspecting* the event stream, not *driving* it:\n * `nextTurn` only resolves once `events` has been iterated to completion, the\n * same as every other field on this interface.\n *\n * **One call, one usage.** `executeClientToolTurn` makes a single provider\n * call per invocation; the multi-round loop is driven by the caller\n * re-invoking with `continuationMessages`. So each result's `usage` already\n * *is* one round's usage, and a host accumulating a per-turn total sums the\n * results of its own loop. There is deliberately no `perRound` array here —\n * it could only ever have one entry.\n *\n * **Optional on purpose, unlike `toolConflicts`.** The library always knows\n * what it did to your tools, so a silent `toolConflicts` would be a defect\n * and it is required. It cannot always know what a turn cost, so a required\n * `usage` could only be satisfied by inventing one — the exact failure\n * {@link AiAssist.IAiCompletionUsage.reports} exists to prevent.\n *\n * Absent means **no normalized usage is being exposed**, which covers two\n * cases, the same as on {@link AiAssist.IAiCompletionResponse.usage} and\n * {@link AiAssist.IAiStreamDone.usage}:\n *\n * - the provider reported nothing; or\n * - the provider reported something the library declines to normalize,\n * because this descriptor is outside\n * {@link AiAssist.supportsCacheUsageReporting}. Groq, Mistral, Ollama and\n * self-hosted `openai-compat` share the OpenAI-format adapter but have\n * unverified usage shapes, so a raw `usage` block from one of them is\n * dropped rather than stamped with a cache-reporting level it may not\n * have earned.\n *\n * Either way it is never a fabricated zero. If you need to tell the two\n * apart, the descriptor answers it: the second case is a property of the\n * provider you picked, not of the turn.\n */\n readonly usage?: IAiCompletionUsage;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fgv/ts-extras",
|
|
3
|
-
"version": "5.1.0-
|
|
3
|
+
"version": "5.1.0-57",
|
|
4
4
|
"description": "Assorted Typescript Utilities",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"types": "dist/ts-extras.d.ts",
|
|
@@ -100,10 +100,10 @@
|
|
|
100
100
|
"@types/js-yaml": "~4.0.9",
|
|
101
101
|
"typedoc": "~0.28.16",
|
|
102
102
|
"typedoc-plugin-markdown": "~4.9.0",
|
|
103
|
-
"@fgv/heft-dual-rig": "5.1.0-
|
|
104
|
-
"@fgv/typedoc-compact-theme": "5.1.0-
|
|
105
|
-
"@fgv/ts-utils": "5.1.0-
|
|
106
|
-
"@fgv/ts-utils
|
|
103
|
+
"@fgv/heft-dual-rig": "5.1.0-57",
|
|
104
|
+
"@fgv/typedoc-compact-theme": "5.1.0-57",
|
|
105
|
+
"@fgv/ts-utils-jest": "5.1.0-57",
|
|
106
|
+
"@fgv/ts-utils": "5.1.0-57"
|
|
107
107
|
},
|
|
108
108
|
"dependencies": {
|
|
109
109
|
"@types/luxon": "^3.7.1",
|
|
@@ -112,10 +112,10 @@
|
|
|
112
112
|
"papaparse": "^5.4.1",
|
|
113
113
|
"fflate": "~0.8.2",
|
|
114
114
|
"js-yaml": "~4.1.1",
|
|
115
|
-
"@fgv/ts-json-base": "5.1.0-
|
|
115
|
+
"@fgv/ts-json-base": "5.1.0-57"
|
|
116
116
|
},
|
|
117
117
|
"peerDependencies": {
|
|
118
|
-
"@fgv/ts-utils": "5.1.0-
|
|
118
|
+
"@fgv/ts-utils": "5.1.0-57"
|
|
119
119
|
},
|
|
120
120
|
"repository": {
|
|
121
121
|
"type": "git",
|