@fgv/ts-extras 5.1.0-54 → 5.1.0-56

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.
Files changed (166) hide show
  1. package/CAPABILITIES.md +95 -0
  2. package/dist/packlets/ai-assist/cacheRequest.js +118 -0
  3. package/dist/packlets/ai-assist/cacheRequest.js.map +1 -0
  4. package/dist/packlets/ai-assist/chatRequestBuilders.js +70 -5
  5. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  6. package/dist/packlets/ai-assist/completionClient.js +122 -45
  7. package/dist/packlets/ai-assist/completionClient.js.map +1 -1
  8. package/dist/packlets/ai-assist/imageGenerationClient.js +1 -1
  9. package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  10. package/dist/packlets/ai-assist/index.js +3 -1
  11. package/dist/packlets/ai-assist/index.js.map +1 -1
  12. package/dist/packlets/ai-assist/model.js.map +1 -1
  13. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +200 -0
  14. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  15. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js +137 -0
  16. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  17. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js +156 -0
  18. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  19. package/dist/packlets/ai-assist/promptCacheUsageMath.js +124 -0
  20. package/dist/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  21. package/dist/packlets/ai-assist/registry.js +9 -11
  22. package/dist/packlets/ai-assist/registry.js.map +1 -1
  23. package/dist/packlets/ai-assist/streamUsageCapability.js +124 -0
  24. package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  25. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +24 -5
  26. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  27. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +64 -33
  28. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  29. package/dist/packlets/ai-assist/streamingAdapters/common.js +25 -1
  30. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  31. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  32. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  33. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +34 -8
  34. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  35. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +22 -14
  36. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  37. package/dist/packlets/ai-assist/streamingClient.js +3 -2
  38. package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
  39. package/dist/packlets/ai-assist/structuredOutput.js +84 -7
  40. package/dist/packlets/ai-assist/structuredOutput.js.map +1 -1
  41. package/dist/packlets/ai-assist/structuredOutputTypes.js.map +1 -1
  42. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +18 -3
  43. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  44. package/dist/packlets/ai-assist/toolFormats.js +80 -0
  45. package/dist/packlets/ai-assist/toolFormats.js.map +1 -1
  46. package/dist/packlets/ai-assist/toolTypes.js +21 -0
  47. package/dist/packlets/ai-assist/toolTypes.js.map +1 -0
  48. package/dist/packlets/ai-assist/usageNormalization.js +178 -0
  49. package/dist/packlets/ai-assist/usageNormalization.js.map +1 -0
  50. package/dist/packlets/ai-assist/usageTypes.js +21 -0
  51. package/dist/packlets/ai-assist/usageTypes.js.map +1 -0
  52. package/dist/packlets/mustache/index.js.map +1 -1
  53. package/dist/packlets/mustache/interfaces.js.map +1 -1
  54. package/dist/packlets/mustache/mustacheTemplate.js +91 -0
  55. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -1
  56. package/dist/ts-extras.d.ts +577 -30
  57. package/lib/packlets/ai-assist/cacheRequest.d.ts +100 -0
  58. package/lib/packlets/ai-assist/cacheRequest.d.ts.map +1 -0
  59. package/lib/packlets/ai-assist/cacheRequest.js +123 -0
  60. package/lib/packlets/ai-assist/cacheRequest.js.map +1 -0
  61. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +34 -4
  62. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
  63. package/lib/packlets/ai-assist/chatRequestBuilders.js +73 -5
  64. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  65. package/lib/packlets/ai-assist/completionClient.d.ts +6 -0
  66. package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
  67. package/lib/packlets/ai-assist/completionClient.js +121 -44
  68. package/lib/packlets/ai-assist/completionClient.js.map +1 -1
  69. package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
  70. package/lib/packlets/ai-assist/imageGenerationClient.js +1 -1
  71. package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  72. package/lib/packlets/ai-assist/index.d.ts +7 -2
  73. package/lib/packlets/ai-assist/index.d.ts.map +1 -1
  74. package/lib/packlets/ai-assist/index.js +11 -1
  75. package/lib/packlets/ai-assist/index.js.map +1 -1
  76. package/lib/packlets/ai-assist/model.d.ts +59 -288
  77. package/lib/packlets/ai-assist/model.d.ts.map +1 -1
  78. package/lib/packlets/ai-assist/model.js.map +1 -1
  79. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts +124 -0
  80. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts.map +1 -0
  81. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +208 -0
  82. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  83. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts +77 -0
  84. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts.map +1 -0
  85. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js +143 -0
  86. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  87. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts +84 -0
  88. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts.map +1 -0
  89. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js +163 -0
  90. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  91. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts +105 -0
  92. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts.map +1 -0
  93. package/lib/packlets/ai-assist/promptCacheUsageMath.js +130 -0
  94. package/lib/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  95. package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
  96. package/lib/packlets/ai-assist/registry.js +9 -11
  97. package/lib/packlets/ai-assist/registry.js.map +1 -1
  98. package/lib/packlets/ai-assist/streamUsageCapability.d.ts +119 -0
  99. package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -0
  100. package/lib/packlets/ai-assist/streamUsageCapability.js +130 -0
  101. package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  102. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
  103. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +23 -4
  104. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  105. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +21 -12
  106. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
  107. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +64 -34
  108. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  109. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +21 -0
  110. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
  111. package/lib/packlets/ai-assist/streamingAdapters/common.js +25 -1
  112. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  113. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
  114. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  115. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  116. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +1 -1
  117. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
  118. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +33 -7
  119. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  120. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +1 -1
  121. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
  122. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +21 -13
  123. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  124. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
  125. package/lib/packlets/ai-assist/streamingClient.js +3 -2
  126. package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
  127. package/lib/packlets/ai-assist/structuredOutput.d.ts +32 -0
  128. package/lib/packlets/ai-assist/structuredOutput.d.ts.map +1 -1
  129. package/lib/packlets/ai-assist/structuredOutput.js +85 -7
  130. package/lib/packlets/ai-assist/structuredOutput.js.map +1 -1
  131. package/lib/packlets/ai-assist/structuredOutputTypes.d.ts +30 -0
  132. package/lib/packlets/ai-assist/structuredOutputTypes.d.ts.map +1 -1
  133. package/lib/packlets/ai-assist/structuredOutputTypes.js.map +1 -1
  134. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
  135. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +18 -3
  136. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  137. package/lib/packlets/ai-assist/toolFormats.d.ts +55 -1
  138. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -1
  139. package/lib/packlets/ai-assist/toolFormats.js +82 -0
  140. package/lib/packlets/ai-assist/toolFormats.js.map +1 -1
  141. package/lib/packlets/ai-assist/toolTypes.d.ts +328 -0
  142. package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -0
  143. package/lib/packlets/ai-assist/toolTypes.js +22 -0
  144. package/lib/packlets/ai-assist/toolTypes.js.map +1 -0
  145. package/lib/packlets/ai-assist/usageNormalization.d.ts +58 -0
  146. package/lib/packlets/ai-assist/usageNormalization.d.ts.map +1 -0
  147. package/lib/packlets/ai-assist/usageNormalization.js +184 -0
  148. package/lib/packlets/ai-assist/usageNormalization.js.map +1 -0
  149. package/lib/packlets/ai-assist/usageTypes.d.ts +84 -0
  150. package/lib/packlets/ai-assist/usageTypes.d.ts.map +1 -0
  151. package/lib/packlets/ai-assist/usageTypes.js +22 -0
  152. package/lib/packlets/ai-assist/usageTypes.js.map +1 -0
  153. package/lib/packlets/mustache/index.d.ts +1 -1
  154. package/lib/packlets/mustache/index.d.ts.map +1 -1
  155. package/lib/packlets/mustache/index.js.map +1 -1
  156. package/lib/packlets/mustache/interfaces.d.ts +30 -0
  157. package/lib/packlets/mustache/interfaces.d.ts.map +1 -1
  158. package/lib/packlets/mustache/interfaces.js.map +1 -1
  159. package/lib/packlets/mustache/mustacheTemplate.d.ts +56 -1
  160. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -1
  161. package/lib/packlets/mustache/mustacheTemplate.js +91 -0
  162. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -1
  163. package/package.json +16 -16
  164. package/perf/promptCacheAnthropicBreakpoint.js +135 -0
  165. package/perf/promptCacheObservability.js +107 -0
  166. package/perf/promptCacheRoutingAb.js +105 -0
@@ -1 +1 @@
1
- {"version":3,"file":"thinkingOptionsResolver.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/thinkingOptionsResolver.ts"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R,KAAK,QAAQ;YACX,kEAAkE;YAClE,IAAI,QAAQ,CAAC,YAAY,KAAK,SAAS,IAAI,QAAQ,CAAC,YAAY,KAAK,MAAM,EAAE,CAAC;gBAC5E,OAAO,IAAI,CACT,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,IAAI,CACT,0GAA0G,CAC3G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,QAAQ;YACX,oEAAoE;YACpE,MAAM;IACV,CAAC;IACD,OAAO,OAAO,CAAC,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. @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: '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. @internal\n */\nfunction genericEffortToGemini(effort: 'low' | 'medium' | 'high'): number {\n switch (effort) {\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: '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 resolved = { ...resolved, anthropicEffort: genericEffortToAnthropic(config.effort) };\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;AA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;QACR,KAAK,QAAQ;YACX,kEAAkE;YAClE,IAAI,QAAQ,CAAC,YAAY,KAAK,SAAS,IAAI,QAAQ,CAAC,YAAY,KAAK,MAAM,EAAE,CAAC;gBAC5E,OAAO,IAAI,CACT,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,IAAI,CACT,0GAA0G,CAC3G,CAAC;YACJ,CAAC;YACD,MAAM;QACR,KAAK,QAAQ;YACX,oEAAoE;YACpE,MAAM;IACV,CAAC;IACD,OAAO,OAAO,CAAC,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"]}
@@ -17,6 +17,7 @@
17
17
  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
+ import { fail, succeed } from '@fgv/ts-utils';
20
21
  // ============================================================================
21
22
  // Tool resolution
22
23
  // ============================================================================
@@ -46,6 +47,85 @@ export function resolveEffectiveTools(descriptor, settingsTools, perCallTools) {
46
47
  .filter((e) => e.enabled && supported.has(e.type))
47
48
  .map((e) => { var _a; return (_a = e.config) !== null && _a !== void 0 ? _a : { type: e.type }; });
48
49
  }
50
+ /**
51
+ * The default {@link AiAssist.AiToolConflictPolicy} applied when a caller passes none.
52
+ *
53
+ * @remarks
54
+ * Keeping the client tools is the right default because they are what the host
55
+ * registered explicitly for *this* turn, while a built-in server tool is a
56
+ * per-provider nicety the same host would get on some providers and not others.
57
+ * Dropping the nicety degrades a turn; dropping the client tools changes what the
58
+ * turn can do.
59
+ * @public
60
+ */
61
+ export const defaultToolConflictPolicy = 'drop-server-tools';
62
+ /**
63
+ * Applies a provider's declared server-tool/client-tool exclusions to one request's
64
+ * tools.
65
+ *
66
+ * @remarks
67
+ * The generic half of a rule that used to be a provider-identity branch. The
68
+ * constraint is declared on the descriptor
69
+ * (`IAiProviderDescriptor.serverToolsExclusiveWithClientTools`); this reads it
70
+ * and applies `policy`, so no consumer needs to know *which* provider has the limit
71
+ * or *what* the limit is. A descriptor that declares nothing, or a request with no
72
+ * client tools, or one with no server tools, passes through untouched with an empty
73
+ * report — the exclusion is about the *combination*, and either half alone is legal.
74
+ *
75
+ * Sibling to {@link AiAssist.resolveEffectiveTools} rather than an extension of it:
76
+ * that function filters server tools against what the provider supports at all and
77
+ * is used by every completion path, most of which have no client tools to weigh.
78
+ *
79
+ * @param descriptor - The provider descriptor carrying the declared exclusions.
80
+ * @param serverTools - The server tools the caller wants to send, if any.
81
+ * @param clientTools - The client tools the caller wants to send.
82
+ * @param policy - What to do about a conflict. Defaults to
83
+ * {@link AiAssist.defaultToolConflictPolicy}.
84
+ * @returns `Success` with the surviving tools and a report, or `Failure` naming the
85
+ * conflict when `policy` is `'fail'`.
86
+ * @public
87
+ */
88
+ export function resolveToolConflicts(descriptor, serverTools, clientTools, policy = defaultToolConflictPolicy) {
89
+ var _a;
90
+ const present = serverTools !== null && serverTools !== void 0 ? serverTools : [];
91
+ const exclusive = new Set((_a = descriptor.serverToolsExclusiveWithClientTools) !== null && _a !== void 0 ? _a : []);
92
+ const conflicting = clientTools.length > 0 ? present.filter((t) => exclusive.has(t.type)).map((t) => t.type) : [];
93
+ if (conflicting.length === 0) {
94
+ return succeed({
95
+ serverTools: present,
96
+ clientTools,
97
+ report: { policy, droppedServerTools: [], droppedClientTools: [] }
98
+ });
99
+ }
100
+ // Name every conflicting tool, not just the first: a host reading the message is
101
+ // deciding what to send instead, and a partial list invites a second round.
102
+ const named = conflicting.join(', ');
103
+ switch (policy) {
104
+ case 'fail':
105
+ return fail(`provider "${descriptor.id}" cannot combine server tool(s) [${named}] with client (function) tools in the same request; send one or the other`);
106
+ case 'prefer-server-tools':
107
+ return succeed({
108
+ serverTools: present,
109
+ clientTools: [],
110
+ report: {
111
+ policy,
112
+ droppedServerTools: [],
113
+ droppedClientTools: clientTools.map((t) => t.config.name)
114
+ }
115
+ });
116
+ case 'drop-server-tools':
117
+ return succeed({
118
+ serverTools: present.filter((t) => !exclusive.has(t.type)),
119
+ clientTools,
120
+ report: { policy, droppedServerTools: conflicting, droppedClientTools: [] }
121
+ });
122
+ /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */
123
+ default: {
124
+ const _exhaustive = policy;
125
+ return fail(`unknown tool conflict policy: ${JSON.stringify(_exhaustive)}`);
126
+ }
127
+ }
128
+ }
49
129
  // ============================================================================
50
130
  // OpenAI / xAI Responses API format
51
131
  // ============================================================================
@@ -1 +1 @@
1
- {"version":3,"file":"toolFormats.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.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;AAkBZ,+EAA+E;AAC/E,kBAAkB;AAClB,+EAA+E;AAE/E;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,qBAAqB,CACnC,UAAiC,EACjC,aAAgD,EAChD,YAAgD;IAEhD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;IAErD,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAC/B,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,aAAa;SACjB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;SACjD,GAAG,CAAC,CAAC,CAAC,EAAsB,EAAE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Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Provider-specific tool format translation and tool resolution logic.\n * @packageDocumentation\n */\n\nimport { type JsonObject, type JsonValue } from '@fgv/ts-json-base';\n\nimport {\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiClientToolConfig,\n type IAiProviderDescriptor,\n type IAiToolEnablement,\n type IAiWebSearchToolConfig\n} from './model';\n\n// ============================================================================\n// Tool resolution\n// ============================================================================\n\n/**\n * Resolves the effective tools for a completion call.\n *\n * - If per-call tools are provided, they override settings-level tools entirely.\n * - Otherwise, settings-level enabled tools are used.\n * - Only tools supported by the provider are included.\n * - Returns an empty array if no tools are enabled (= no tools sent).\n *\n * @param descriptor - The provider descriptor (used to filter by supported tools)\n * @param settingsTools - Tool enablement from provider settings (optional)\n * @param perCallTools - Per-call tool override (optional)\n * @returns The resolved list of tool configs to include in the request\n * @public\n */\nexport function resolveEffectiveTools(\n descriptor: IAiProviderDescriptor,\n settingsTools?: ReadonlyArray<IAiToolEnablement>,\n perCallTools?: ReadonlyArray<AiServerToolConfig>\n): ReadonlyArray<AiServerToolConfig> {\n const supported = new Set(descriptor.supportedTools);\n\n if (perCallTools !== undefined) {\n return perCallTools.filter((t) => supported.has(t.type));\n }\n\n if (settingsTools === undefined) {\n return [];\n }\n\n return settingsTools\n .filter((e) => e.enabled && supported.has(e.type))\n .map((e): AiServerToolConfig => e.config ?? { type: e.type });\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction webSearchToResponsesApi(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = { type: 'web_search' };\n\n if (config.allowedDomains || config.blockedDomains) {\n const filters: Record<string, unknown> = {};\n if (config.allowedDomains) {\n filters.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n filters.excluded_domains = [...config.blockedDomains];\n }\n tool.filters = filters;\n }\n\n if (config.enableImageUnderstanding) {\n tool.enable_image_understanding = true;\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction clientToolToResponsesApi(config: IAiClientToolConfig): JsonObject {\n return {\n type: 'function',\n name: config.name,\n description: config.description,\n parameters: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the xAI/OpenAI Responses API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toResponsesApiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToResponsesApi(t);\n case 'client_tool':\n return clientToolToResponsesApi(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Anthropic Messages API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the Anthropic Messages API.\n * @internal\n */\nfunction webSearchToAnthropic(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = {\n type: 'web_search_20250305',\n name: 'web_search'\n };\n\n if (config.maxUses !== undefined) {\n tool.max_uses = config.maxUses;\n }\n if (config.allowedDomains) {\n tool.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n tool.blocked_domains = [...config.blockedDomains];\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the Anthropic Messages API.\n * Note: Anthropic client tools have no `type` field (unlike server tools).\n * @internal\n */\nfunction clientToolToAnthropic(config: IAiClientToolConfig): JsonObject {\n return {\n name: config.name,\n description: config.description,\n input_schema: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the Anthropic Messages API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toAnthropicTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToAnthropic(t);\n case 'client_tool':\n return clientToolToAnthropic(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Gemini generateContent API format\n// ============================================================================\n\n/**\n * Sanitizes a draft-07 JSON Schema (as emitted by `JsonSchema.object(...).toJson()`)\n * into the OpenAPI 3.0 Schema Object subset that Gemini's `function_declarations[].parameters`\n * accepts.\n *\n * @remarks\n * Gemini's function-declaration schema is **not** full JSON Schema — it is a subset of\n * the OpenAPI 3.0 Schema Object and **rejects** (rather than ignores) draft-07-only\n * keywords. `JsonSchema` objects are strict-by-default, so `.toJson()` emits\n * `additionalProperties: false` on every object node, which 400s the whole request on\n * Gemini. This helper recursively strips the unsupported keywords so any\n * `JsonSchema`-authored client tool works on Gemini without consumer awareness of the\n * dialect difference. Stripping is infallible, so it returns a plain value rather than a\n * `Result`.\n *\n * `additionalProperties` and `$schema` are stripped only where they appear as schema\n * *keywords* (siblings of `type`/`properties`/etc.). Inside a `properties` map the keys\n * are user-defined parameter names, not keywords, so they are preserved verbatim while\n * each property's subschema value is still recursively sanitized — a tool parameter\n * legitimately named `additionalProperties` survives.\n *\n * @internal\n */\n/**\n * The non-`null` member of a draft-07 nullable `type` union, or `undefined` when `type` is\n * not one.\n *\n * @remarks\n * Deliberately narrow: only the two-member `[<type>, 'null']` shape `JsonSchema` emits is\n * recognised. A general union has no OpenAPI equivalent, so translating one would be\n * inventing a meaning — it is passed through unchanged and Gemini refuses it, which is the\n * honest outcome.\n * @internal\n */\nfunction _nullableUnionMember(type: JsonValue | undefined): string | undefined {\n if (!Array.isArray(type) || type.length !== 2 || !type.includes('null')) {\n return undefined;\n }\n const other: JsonValue | undefined = type.find((member) => member !== 'null');\n return typeof other === 'string' ? other : undefined;\n}\n\nexport function toGeminiParameterSchema(schema: JsonValue): JsonValue {\n if (Array.isArray(schema)) {\n return schema.map(toGeminiParameterSchema);\n }\n if (schema !== null && typeof schema === 'object') {\n const out: JsonObject = {};\n // Nullability is spelled differently in the two dialects and they are mutually\n // exclusive: draft-07 (and OpenAI strict mode) wants `type: ['string', 'null']`,\n // OpenAPI 3.0 (and Gemini) wants `type: 'string'` + `nullable: true` and rejects the\n // union array. This is the same class of translation as the `additionalProperties`\n // strip above — a dialect difference the consumer should not have to know about.\n const nullableType: string | undefined = _nullableUnionMember(schema.type);\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'additionalProperties' || key === '$schema') {\n continue;\n }\n if (nullableType !== undefined && key === 'type') {\n out.type = nullableType;\n out.nullable = true;\n continue;\n }\n if (nullableType !== undefined && key === 'enum' && Array.isArray(value)) {\n // A nullable enum carries `null` among its values in draft-07. OpenAPI expresses\n // that with `nullable` alone, so the member is dropped rather than sent as a value\n // Gemini would reject.\n out.enum = value.filter((member) => member !== null);\n continue;\n }\n if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n // `properties` maps user-defined parameter names to subschemas: recurse each\n // subschema value but never treat a parameter name as a strippable keyword.\n const properties: JsonObject = {};\n for (const [name, propSchema] of Object.entries(value)) {\n properties[name] = toGeminiParameterSchema(propSchema);\n }\n out[key] = properties;\n } else {\n out[key] = toGeminiParameterSchema(value);\n }\n }\n return out;\n }\n return schema;\n}\n\n/**\n * Formats tool configs for the Gemini generateContent API.\n *\n * @remarks\n * Gemini uses `google_search` for search grounding (no per-tool config).\n * Client-defined tools are accumulated into a single `function_declarations` entry.\n * Each client tool's parameters schema is sanitized to Gemini's OpenAPI-subset\n * dialect via {@link toGeminiParameterSchema} (the raw draft-07 `.toJson()` output\n * carries `additionalProperties`, which Gemini rejects).\n *\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toGeminiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n const result: JsonObject[] = [];\n const functionDeclarations: JsonObject[] = [];\n\n for (const t of tools) {\n switch (t.type) {\n case 'web_search':\n result.push({ google_search: {} } as JsonObject);\n break;\n case 'client_tool':\n functionDeclarations.push({\n name: t.name,\n description: t.description,\n parameters: toGeminiParameterSchema(t.parametersSchema.toJson())\n } as JsonObject);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n result.push({ type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject);\n }\n }\n }\n\n if (functionDeclarations.length > 0) {\n result.push({ function_declarations: functionDeclarations } as JsonObject);\n }\n\n return result;\n}\n"]}
1
+ {"version":3,"file":"toolFormats.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.ts"],"names":[],"mappings":"AAAA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FAAqF;YACrF,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,WAAW,GAAU,CAAC,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,EAAgB,CAAC,CAAC;YAChF,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,oBAAoB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,CAAC,IAAI,CAAC,EAAE,qBAAqB,EAAE,oBAAoB,EAAgB,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Provider-specific tool format translation and tool resolution logic.\n * @packageDocumentation\n */\n\nimport { type JsonObject, type JsonValue } from '@fgv/ts-json-base';\nimport { type Result, fail, succeed } from '@fgv/ts-utils';\n\nimport { type IAiProviderDescriptor } from './model';\nimport {\n type AiServerToolConfig,\n type AiServerToolType,\n type AiToolConfig,\n type AiToolConflictPolicy,\n type IAiClientTool,\n type IAiClientToolConfig,\n type IAiToolConflictReport,\n type IAiToolEnablement,\n type IAiWebSearchToolConfig\n} from './toolTypes';\n\n// ============================================================================\n// Tool resolution\n// ============================================================================\n\n/**\n * Resolves the effective tools for a completion call.\n *\n * - If per-call tools are provided, they override settings-level tools entirely.\n * - Otherwise, settings-level enabled tools are used.\n * - Only tools supported by the provider are included.\n * - Returns an empty array if no tools are enabled (= no tools sent).\n *\n * @param descriptor - The provider descriptor (used to filter by supported tools)\n * @param settingsTools - Tool enablement from provider settings (optional)\n * @param perCallTools - Per-call tool override (optional)\n * @returns The resolved list of tool configs to include in the request\n * @public\n */\nexport function resolveEffectiveTools(\n descriptor: IAiProviderDescriptor,\n settingsTools?: ReadonlyArray<IAiToolEnablement>,\n perCallTools?: ReadonlyArray<AiServerToolConfig>\n): ReadonlyArray<AiServerToolConfig> {\n const supported = new Set(descriptor.supportedTools);\n\n if (perCallTools !== undefined) {\n return perCallTools.filter((t) => supported.has(t.type));\n }\n\n if (settingsTools === undefined) {\n return [];\n }\n\n return settingsTools\n .filter((e) => e.enabled && supported.has(e.type))\n .map((e): AiServerToolConfig => e.config ?? { type: e.type });\n}\n\n/**\n * The default {@link AiAssist.AiToolConflictPolicy} applied when a caller passes none.\n *\n * @remarks\n * Keeping the client tools is the right default because they are what the host\n * registered explicitly for *this* turn, while a built-in server tool is a\n * per-provider nicety the same host would get on some providers and not others.\n * Dropping the nicety degrades a turn; dropping the client tools changes what the\n * turn can do.\n * @public\n */\nexport const defaultToolConflictPolicy: AiToolConflictPolicy = 'drop-server-tools';\n\n/**\n * The outcome of {@link AiAssist.resolveToolConflicts}: the tools that survived,\n * plus the report of what did not.\n * @public\n */\nexport interface IAiResolvedToolConflicts {\n /** Server tools to send, after the policy was applied. */\n readonly serverTools: ReadonlyArray<AiServerToolConfig>;\n /** Client tools to send, after the policy was applied. */\n readonly clientTools: ReadonlyArray<IAiClientTool>;\n /** What the resolution did. Always populated; empty arrays mean nothing conflicted. */\n readonly report: IAiToolConflictReport;\n}\n\n/**\n * Applies a provider's declared server-tool/client-tool exclusions to one request's\n * tools.\n *\n * @remarks\n * The generic half of a rule that used to be a provider-identity branch. The\n * constraint is declared on the descriptor\n * (`IAiProviderDescriptor.serverToolsExclusiveWithClientTools`); this reads it\n * and applies `policy`, so no consumer needs to know *which* provider has the limit\n * or *what* the limit is. A descriptor that declares nothing, or a request with no\n * client tools, or one with no server tools, passes through untouched with an empty\n * report — the exclusion is about the *combination*, and either half alone is legal.\n *\n * Sibling to {@link AiAssist.resolveEffectiveTools} rather than an extension of it:\n * that function filters server tools against what the provider supports at all and\n * is used by every completion path, most of which have no client tools to weigh.\n *\n * @param descriptor - The provider descriptor carrying the declared exclusions.\n * @param serverTools - The server tools the caller wants to send, if any.\n * @param clientTools - The client tools the caller wants to send.\n * @param policy - What to do about a conflict. Defaults to\n * {@link AiAssist.defaultToolConflictPolicy}.\n * @returns `Success` with the surviving tools and a report, or `Failure` naming the\n * conflict when `policy` is `'fail'`.\n * @public\n */\nexport function resolveToolConflicts(\n descriptor: IAiProviderDescriptor,\n serverTools: ReadonlyArray<AiServerToolConfig> | undefined,\n clientTools: ReadonlyArray<IAiClientTool>,\n policy: AiToolConflictPolicy = defaultToolConflictPolicy\n): Result<IAiResolvedToolConflicts> {\n const present = serverTools ?? [];\n const exclusive = new Set(descriptor.serverToolsExclusiveWithClientTools ?? []);\n const conflicting: ReadonlyArray<AiServerToolType> =\n clientTools.length > 0 ? present.filter((t) => exclusive.has(t.type)).map((t) => t.type) : [];\n\n if (conflicting.length === 0) {\n return succeed({\n serverTools: present,\n clientTools,\n report: { policy, droppedServerTools: [], droppedClientTools: [] }\n });\n }\n\n // Name every conflicting tool, not just the first: a host reading the message is\n // deciding what to send instead, and a partial list invites a second round.\n const named = conflicting.join(', ');\n switch (policy) {\n case 'fail':\n return fail(\n `provider \"${descriptor.id}\" cannot combine server tool(s) [${named}] with client (function) tools in the same request; send one or the other`\n );\n case 'prefer-server-tools':\n return succeed({\n serverTools: present,\n clientTools: [],\n report: {\n policy,\n droppedServerTools: [],\n droppedClientTools: clientTools.map((t) => t.config.name)\n }\n });\n case 'drop-server-tools':\n return succeed({\n serverTools: present.filter((t) => !exclusive.has(t.type)),\n clientTools,\n report: { policy, droppedServerTools: conflicting, droppedClientTools: [] }\n });\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = policy;\n return fail(`unknown tool conflict policy: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction webSearchToResponsesApi(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = { type: 'web_search' };\n\n if (config.allowedDomains || config.blockedDomains) {\n const filters: Record<string, unknown> = {};\n if (config.allowedDomains) {\n filters.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n filters.excluded_domains = [...config.blockedDomains];\n }\n tool.filters = filters;\n }\n\n if (config.enableImageUnderstanding) {\n tool.enable_image_understanding = true;\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction clientToolToResponsesApi(config: IAiClientToolConfig): JsonObject {\n return {\n type: 'function',\n name: config.name,\n description: config.description,\n parameters: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the xAI/OpenAI Responses API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toResponsesApiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToResponsesApi(t);\n case 'client_tool':\n return clientToolToResponsesApi(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Anthropic Messages API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the Anthropic Messages API.\n * @internal\n */\nfunction webSearchToAnthropic(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = {\n type: 'web_search_20250305',\n name: 'web_search'\n };\n\n if (config.maxUses !== undefined) {\n tool.max_uses = config.maxUses;\n }\n if (config.allowedDomains) {\n tool.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n tool.blocked_domains = [...config.blockedDomains];\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the Anthropic Messages API.\n * Note: Anthropic client tools have no `type` field (unlike server tools).\n * @internal\n */\nfunction clientToolToAnthropic(config: IAiClientToolConfig): JsonObject {\n return {\n name: config.name,\n description: config.description,\n input_schema: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the Anthropic Messages API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toAnthropicTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToAnthropic(t);\n case 'client_tool':\n return clientToolToAnthropic(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Gemini generateContent API format\n// ============================================================================\n\n/**\n * Sanitizes a draft-07 JSON Schema (as emitted by `JsonSchema.object(...).toJson()`)\n * into the OpenAPI 3.0 Schema Object subset that Gemini's `function_declarations[].parameters`\n * accepts.\n *\n * @remarks\n * Gemini's function-declaration schema is **not** full JSON Schema — it is a subset of\n * the OpenAPI 3.0 Schema Object and **rejects** (rather than ignores) draft-07-only\n * keywords. `JsonSchema` objects are strict-by-default, so `.toJson()` emits\n * `additionalProperties: false` on every object node, which 400s the whole request on\n * Gemini. This helper recursively strips the unsupported keywords so any\n * `JsonSchema`-authored client tool works on Gemini without consumer awareness of the\n * dialect difference. Stripping is infallible, so it returns a plain value rather than a\n * `Result`.\n *\n * `additionalProperties` and `$schema` are stripped only where they appear as schema\n * *keywords* (siblings of `type`/`properties`/etc.). Inside a `properties` map the keys\n * are user-defined parameter names, not keywords, so they are preserved verbatim while\n * each property's subschema value is still recursively sanitized — a tool parameter\n * legitimately named `additionalProperties` survives.\n *\n * @internal\n */\n/**\n * The non-`null` member of a draft-07 nullable `type` union, or `undefined` when `type` is\n * not one.\n *\n * @remarks\n * Deliberately narrow: only the two-member `[<type>, 'null']` shape `JsonSchema` emits is\n * recognised. A general union has no OpenAPI equivalent, so translating one would be\n * inventing a meaning — it is passed through unchanged and Gemini refuses it, which is the\n * honest outcome.\n * @internal\n */\nfunction _nullableUnionMember(type: JsonValue | undefined): string | undefined {\n if (!Array.isArray(type) || type.length !== 2 || !type.includes('null')) {\n return undefined;\n }\n const other: JsonValue | undefined = type.find((member) => member !== 'null');\n return typeof other === 'string' ? other : undefined;\n}\n\nexport function toGeminiParameterSchema(schema: JsonValue): JsonValue {\n if (Array.isArray(schema)) {\n return schema.map(toGeminiParameterSchema);\n }\n if (schema !== null && typeof schema === 'object') {\n const out: JsonObject = {};\n // Nullability is spelled differently in the two dialects and they are mutually\n // exclusive: draft-07 (and OpenAI strict mode) wants `type: ['string', 'null']`,\n // OpenAPI 3.0 (and Gemini) wants `type: 'string'` + `nullable: true` and rejects the\n // union array. This is the same class of translation as the `additionalProperties`\n // strip above — a dialect difference the consumer should not have to know about.\n const nullableType: string | undefined = _nullableUnionMember(schema.type);\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'additionalProperties' || key === '$schema') {\n continue;\n }\n if (nullableType !== undefined && key === 'type') {\n out.type = nullableType;\n out.nullable = true;\n continue;\n }\n if (nullableType !== undefined && key === 'enum' && Array.isArray(value)) {\n // A nullable enum carries `null` among its values in draft-07. OpenAPI expresses\n // that with `nullable` alone, so the member is dropped rather than sent as a value\n // Gemini would reject.\n out.enum = value.filter((member) => member !== null);\n continue;\n }\n if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n // `properties` maps user-defined parameter names to subschemas: recurse each\n // subschema value but never treat a parameter name as a strippable keyword.\n const properties: JsonObject = {};\n for (const [name, propSchema] of Object.entries(value)) {\n properties[name] = toGeminiParameterSchema(propSchema);\n }\n out[key] = properties;\n } else {\n out[key] = toGeminiParameterSchema(value);\n }\n }\n return out;\n }\n return schema;\n}\n\n/**\n * Formats tool configs for the Gemini generateContent API.\n *\n * @remarks\n * Gemini uses `google_search` for search grounding (no per-tool config).\n * Client-defined tools are accumulated into a single `function_declarations` entry.\n * Each client tool's parameters schema is sanitized to Gemini's OpenAPI-subset\n * dialect via {@link toGeminiParameterSchema} (the raw draft-07 `.toJson()` output\n * carries `additionalProperties`, which Gemini rejects).\n *\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toGeminiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n const result: JsonObject[] = [];\n const functionDeclarations: JsonObject[] = [];\n\n for (const t of tools) {\n switch (t.type) {\n case 'web_search':\n result.push({ google_search: {} } as JsonObject);\n break;\n case 'client_tool':\n functionDeclarations.push({\n name: t.name,\n description: t.description,\n parameters: toGeminiParameterSchema(t.parametersSchema.toJson())\n } as JsonObject);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n result.push({ type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject);\n }\n }\n }\n\n if (functionDeclarations.length > 0) {\n result.push({ function_declarations: functionDeclarations } as JsonObject);\n }\n\n return result;\n}\n"]}
@@ -0,0 +1,21 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ export {};
21
+ //# sourceMappingURL=toolTypes.js.map
@@ -0,0 +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"]}
@@ -0,0 +1,178 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ import { Validators } from '@fgv/ts-utils';
21
+ const anthropicRawUsage = Validators.object({
22
+ input_tokens: Validators.number,
23
+ output_tokens: Validators.number.optional(),
24
+ cache_creation_input_tokens: Validators.number.optional(),
25
+ cache_read_input_tokens: Validators.number.optional()
26
+ });
27
+ /**
28
+ * Normalizes an Anthropic Messages API `usage` block. Anthropic always
29
+ * reports both reads and writes, so `reports` is unconditionally
30
+ * `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely
31
+ * means zero tokens were written this request.
32
+ * @internal
33
+ */
34
+ export function normalizeAnthropicUsage(raw) {
35
+ if (raw === undefined) {
36
+ return undefined;
37
+ }
38
+ const parsed = anthropicRawUsage.validate(raw);
39
+ if (parsed.isFailure()) {
40
+ return undefined;
41
+ }
42
+ const { input_tokens: uncachedInputTokens, output_tokens: outputTokens, cache_creation_input_tokens: cacheWriteTokens, cache_read_input_tokens: cachedInputTokens } = parsed.value;
43
+ return {
44
+ reports: 'reads-and-writes',
45
+ uncachedInputTokens,
46
+ cachedInputTokens,
47
+ cacheWriteTokens,
48
+ outputTokens,
49
+ totalInputTokens: cachedInputTokens !== undefined ? uncachedInputTokens + cachedInputTokens : undefined,
50
+ raw
51
+ };
52
+ }
53
+ const openAiChatPromptTokensDetails = Validators.object({ cached_tokens: Validators.number.optional() });
54
+ const openAiChatRawUsage = Validators.object({
55
+ prompt_tokens: Validators.number.optional(),
56
+ completion_tokens: Validators.number.optional(),
57
+ prompt_tokens_details: openAiChatPromptTokensDetails.optional()
58
+ });
59
+ /**
60
+ * Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is
61
+ * unconditionally `'reads'`: `cache_write_tokens` does not exist on this API
62
+ * for any provider reached through it, so `cacheWriteTokens` is never set —
63
+ * not even to `0`.
64
+ * @internal
65
+ */
66
+ export function normalizeOpenAiChatUsage(raw) {
67
+ if (raw === undefined) {
68
+ return undefined;
69
+ }
70
+ const parsed = openAiChatRawUsage.validate(raw);
71
+ if (parsed.isFailure()) {
72
+ return undefined;
73
+ }
74
+ const { prompt_tokens: promptTokens, completion_tokens: outputTokens, prompt_tokens_details } = parsed.value;
75
+ const cachedInputTokens = prompt_tokens_details === null || prompt_tokens_details === void 0 ? void 0 : prompt_tokens_details.cached_tokens;
76
+ const uncachedInputTokens = cachedInputTokens !== undefined && promptTokens !== undefined
77
+ ? promptTokens - cachedInputTokens
78
+ : undefined;
79
+ return {
80
+ reports: 'reads',
81
+ uncachedInputTokens,
82
+ cachedInputTokens,
83
+ outputTokens,
84
+ totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
85
+ ? uncachedInputTokens + cachedInputTokens
86
+ : undefined,
87
+ raw
88
+ };
89
+ }
90
+ const openAiResponsesInputTokensDetails = Validators.object({
91
+ cached_tokens: Validators.number.optional(),
92
+ cache_write_tokens: Validators.number.optional()
93
+ });
94
+ const openAiResponsesRawUsage = Validators.object({
95
+ input_tokens: Validators.number.optional(),
96
+ output_tokens: Validators.number.optional(),
97
+ input_tokens_details: openAiResponsesInputTokensDetails.optional()
98
+ });
99
+ /**
100
+ * Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared
101
+ * by two providers that disagree about write reporting — OpenAI always sends
102
+ * `cache_write_tokens` (even when `0`), xAI never does — so `reports` is
103
+ * derived from field **presence**, not from provider identity: a wire that
104
+ * sends the field, however small its value, is `'reads-and-writes'`; a wire
105
+ * that omits it entirely is `'reads'`.
106
+ * @internal
107
+ */
108
+ export function normalizeOpenAiResponsesUsage(raw) {
109
+ if (raw === undefined) {
110
+ return undefined;
111
+ }
112
+ const parsed = openAiResponsesRawUsage.validate(raw);
113
+ if (parsed.isFailure()) {
114
+ return undefined;
115
+ }
116
+ const { input_tokens: inputTokens, output_tokens: outputTokens, input_tokens_details } = parsed.value;
117
+ const cachedInputTokens = input_tokens_details === null || input_tokens_details === void 0 ? void 0 : input_tokens_details.cached_tokens;
118
+ const cacheWriteTokens = input_tokens_details === null || input_tokens_details === void 0 ? void 0 : input_tokens_details.cache_write_tokens;
119
+ const reports = cacheWriteTokens !== undefined ? 'reads-and-writes' : 'reads';
120
+ const uncachedInputTokens = cachedInputTokens !== undefined && inputTokens !== undefined
121
+ ? inputTokens - cachedInputTokens
122
+ : undefined;
123
+ return {
124
+ reports,
125
+ uncachedInputTokens,
126
+ cachedInputTokens,
127
+ cacheWriteTokens,
128
+ outputTokens,
129
+ totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
130
+ ? uncachedInputTokens + cachedInputTokens
131
+ : undefined,
132
+ raw
133
+ };
134
+ }
135
+ const geminiRawUsage = Validators.object({
136
+ promptTokenCount: Validators.number.optional(),
137
+ candidatesTokenCount: Validators.number.optional(),
138
+ cachedContentTokenCount: Validators.number.optional()
139
+ });
140
+ /**
141
+ * Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally
142
+ * `'reads'` — Gemini has no cache-write concept in a `generateContent` call;
143
+ * writes happen out-of-band via the explicit `cachedContents` resource,
144
+ * out of scope per the design (§10).
145
+ *
146
+ * @remarks
147
+ * The Gemini-specific footgun: `promptTokenCount` already **includes**
148
+ * `cachedContentTokenCount` (it is the total effective prompt size), unlike
149
+ * OpenAI where the cached figure sits in a sub-object alongside a separate
150
+ * total. `uncachedInputTokens` subtracts to correct for it — but only when
151
+ * `cachedContentTokenCount` is itself present, per the module's absent-means-
152
+ * absent rule.
153
+ * @internal
154
+ */
155
+ export function normalizeGeminiUsage(raw) {
156
+ if (raw === undefined) {
157
+ return undefined;
158
+ }
159
+ const parsed = geminiRawUsage.validate(raw);
160
+ if (parsed.isFailure()) {
161
+ return undefined;
162
+ }
163
+ const { promptTokenCount, candidatesTokenCount: outputTokens, cachedContentTokenCount: cachedInputTokens } = parsed.value;
164
+ const uncachedInputTokens = cachedInputTokens !== undefined && promptTokenCount !== undefined
165
+ ? promptTokenCount - cachedInputTokens
166
+ : undefined;
167
+ return {
168
+ reports: 'reads',
169
+ uncachedInputTokens,
170
+ cachedInputTokens,
171
+ outputTokens,
172
+ totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
173
+ ? uncachedInputTokens + cachedInputTokens
174
+ : undefined,
175
+ raw
176
+ };
177
+ }
178
+ //# sourceMappingURL=usageNormalization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageNormalization.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageNormalization.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;AAmBZ,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAgB3D,MAAM,iBAAiB,GAAkC,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AAgB,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC9C,oBAAoB,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClD,uBAAuB,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;CACtD,CAAC,CAAC;AAEH;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAA2B;IAC9D,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,MAAM,GAAG,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,EACJ,gBAAgB,EAChB,oBAAoB,EAAE,YAAY,EAClC,uBAAuB,EAAE,iBAAiB,EAC3C,GAAG,MAAM,CAAC,KAAK,CAAC;IACjB,MAAM,mBAAmB,GACvB,iBAAiB,KAAK,SAAS,IAAI,gBAAgB,KAAK,SAAS;QAC/D,CAAC,CAAC,gBAAgB,GAAG,iBAAiB;QACtC,CAAC,CAAC,SAAS,CAAC;IAChB,OAAO;QACL,OAAO,EAAE,OAAO;QAChB,mBAAmB;QACnB,iBAAiB;QACjB,YAAY;QACZ,gBAAgB,EACd,mBAAmB,KAAK,SAAS,IAAI,iBAAiB,KAAK,SAAS;YAClE,CAAC,CAAC,mBAAmB,GAAG,iBAAiB;YACzC,CAAC,CAAC,SAAS;QACf,GAAG;KACJ,CAAC;AACJ,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 * Per-wire-shape `usage` block normalization, shared by the non-streaming\n * adapters (`completionClient.ts`) and the streaming adapters\n * (`streamingAdapters/*.ts`) so the same JSON layout is parsed once.\n *\n * @remarks\n * Every function here follows one rule throughout: a field that is absent\n * from the wire response stays absent on {@link AiAssist.IAiCompletionUsage} —\n * never defaulted to `0`, and never derived from a sibling field unless the\n * value that sibling would need is itself known. See `IAiCompletionUsage`\n * for why.\n * @packageDocumentation\n */\n\n/* eslint-disable @typescript-eslint/naming-convention -- wire field names are snake_case */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { type Validator, Validators } from '@fgv/ts-utils';\n\nimport { type AiCacheReportingLevel, type IAiCompletionUsage } from './usageTypes';\n\n// ============================================================================\n// Anthropic Messages\n// ============================================================================\n\n/** @internal */\ninterface IAnthropicRawUsage {\n readonly input_tokens: number;\n readonly output_tokens?: number;\n readonly cache_creation_input_tokens?: number;\n readonly cache_read_input_tokens?: number;\n}\n\nconst anthropicRawUsage: Validator<IAnthropicRawUsage> = Validators.object<IAnthropicRawUsage>({\n input_tokens: Validators.number,\n output_tokens: Validators.number.optional(),\n cache_creation_input_tokens: Validators.number.optional(),\n cache_read_input_tokens: Validators.number.optional()\n});\n\n/**\n * Normalizes an Anthropic Messages API `usage` block. Anthropic always\n * reports both reads and writes, so `reports` is unconditionally\n * `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely\n * means zero tokens were written this request.\n * @internal\n */\nexport function normalizeAnthropicUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = anthropicRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n input_tokens: uncachedInputTokens,\n output_tokens: outputTokens,\n cache_creation_input_tokens: cacheWriteTokens,\n cache_read_input_tokens: cachedInputTokens\n } = parsed.value;\n return {\n reports: 'reads-and-writes',\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens: cachedInputTokens !== undefined ? uncachedInputTokens + cachedInputTokens : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Chat Completions\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiChatPromptTokensDetails {\n readonly cached_tokens?: number;\n}\n\nconst openAiChatPromptTokensDetails: Validator<IOpenAiChatPromptTokensDetails> =\n Validators.object<IOpenAiChatPromptTokensDetails>({ cached_tokens: Validators.number.optional() });\n\n/** @internal */\ninterface IOpenAiChatRawUsage {\n readonly prompt_tokens?: number;\n readonly completion_tokens?: number;\n readonly prompt_tokens_details?: IOpenAiChatPromptTokensDetails;\n}\n\nconst openAiChatRawUsage: Validator<IOpenAiChatRawUsage> = Validators.object<IOpenAiChatRawUsage>({\n prompt_tokens: Validators.number.optional(),\n completion_tokens: Validators.number.optional(),\n prompt_tokens_details: openAiChatPromptTokensDetails.optional()\n});\n\n/**\n * Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is\n * unconditionally `'reads'`: `cache_write_tokens` does not exist on this API\n * for any provider reached through it, so `cacheWriteTokens` is never set —\n * not even to `0`.\n * @internal\n */\nexport function normalizeOpenAiChatUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiChatRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n prompt_tokens: promptTokens,\n completion_tokens: outputTokens,\n prompt_tokens_details\n } = parsed.value;\n const cachedInputTokens = prompt_tokens_details?.cached_tokens;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokens !== undefined\n ? promptTokens - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Responses\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiResponsesInputTokensDetails {\n readonly cached_tokens?: number;\n readonly cache_write_tokens?: number;\n}\n\nconst openAiResponsesInputTokensDetails: Validator<IOpenAiResponsesInputTokensDetails> =\n Validators.object<IOpenAiResponsesInputTokensDetails>({\n cached_tokens: Validators.number.optional(),\n cache_write_tokens: Validators.number.optional()\n });\n\n/** @internal */\ninterface IOpenAiResponsesRawUsage {\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n readonly input_tokens_details?: IOpenAiResponsesInputTokensDetails;\n}\n\nconst openAiResponsesRawUsage: Validator<IOpenAiResponsesRawUsage> =\n Validators.object<IOpenAiResponsesRawUsage>({\n input_tokens: Validators.number.optional(),\n output_tokens: Validators.number.optional(),\n input_tokens_details: openAiResponsesInputTokensDetails.optional()\n });\n\n/**\n * Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared\n * by two providers that disagree about write reporting — OpenAI always sends\n * `cache_write_tokens` (even when `0`), xAI never does — so `reports` is\n * derived from field **presence**, not from provider identity: a wire that\n * sends the field, however small its value, is `'reads-and-writes'`; a wire\n * that omits it entirely is `'reads'`.\n * @internal\n */\nexport function normalizeOpenAiResponsesUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiResponsesRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const { input_tokens: inputTokens, output_tokens: outputTokens, input_tokens_details } = parsed.value;\n const cachedInputTokens = input_tokens_details?.cached_tokens;\n const cacheWriteTokens = input_tokens_details?.cache_write_tokens;\n const reports: AiCacheReportingLevel = cacheWriteTokens !== undefined ? 'reads-and-writes' : 'reads';\n const uncachedInputTokens =\n cachedInputTokens !== undefined && inputTokens !== undefined\n ? inputTokens - cachedInputTokens\n : undefined;\n return {\n reports,\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// Gemini generateContent / streamGenerateContent\n// ============================================================================\n\n/** @internal */\ninterface IGeminiRawUsage {\n readonly promptTokenCount?: number;\n readonly candidatesTokenCount?: number;\n readonly cachedContentTokenCount?: number;\n}\n\nconst geminiRawUsage: Validator<IGeminiRawUsage> = Validators.object<IGeminiRawUsage>({\n promptTokenCount: Validators.number.optional(),\n candidatesTokenCount: Validators.number.optional(),\n cachedContentTokenCount: Validators.number.optional()\n});\n\n/**\n * Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally\n * `'reads'` — Gemini has no cache-write concept in a `generateContent` call;\n * writes happen out-of-band via the explicit `cachedContents` resource,\n * out of scope per the design (§10).\n *\n * @remarks\n * The Gemini-specific footgun: `promptTokenCount` already **includes**\n * `cachedContentTokenCount` (it is the total effective prompt size), unlike\n * OpenAI where the cached figure sits in a sub-object alongside a separate\n * total. `uncachedInputTokens` subtracts to correct for it — but only when\n * `cachedContentTokenCount` is itself present, per the module's absent-means-\n * absent rule.\n * @internal\n */\nexport function normalizeGeminiUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = geminiRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n promptTokenCount,\n candidatesTokenCount: outputTokens,\n cachedContentTokenCount: cachedInputTokens\n } = parsed.value;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokenCount !== undefined\n ? promptTokenCount - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n"]}
@@ -0,0 +1,21 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ export {};
21
+ //# sourceMappingURL=usageTypes.js.map