@fgv/ts-extras 5.1.0-55 → 5.1.0-57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CAPABILITIES.md +96 -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 +72 -7
  5. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  6. package/dist/packlets/ai-assist/completionClient.js +195 -58
  7. package/dist/packlets/ai-assist/completionClient.js.map +1 -1
  8. package/dist/packlets/ai-assist/converters.js +54 -0
  9. package/dist/packlets/ai-assist/converters.js.map +1 -1
  10. package/dist/packlets/ai-assist/embeddingClient.js +16 -1
  11. package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
  12. package/dist/packlets/ai-assist/imageGenerationClient.js +17 -2
  13. package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  14. package/dist/packlets/ai-assist/index.js +3 -1
  15. package/dist/packlets/ai-assist/index.js.map +1 -1
  16. package/dist/packlets/ai-assist/listModelsClient.js +19 -1
  17. package/dist/packlets/ai-assist/listModelsClient.js.map +1 -1
  18. package/dist/packlets/ai-assist/model.js.map +1 -1
  19. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +200 -0
  20. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  21. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js +137 -0
  22. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  23. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js +156 -0
  24. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  25. package/dist/packlets/ai-assist/promptCacheUsageMath.js +124 -0
  26. package/dist/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  27. package/dist/packlets/ai-assist/registry.js +9 -11
  28. package/dist/packlets/ai-assist/registry.js.map +1 -1
  29. package/dist/packlets/ai-assist/streamUsageCapability.js +134 -0
  30. package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  31. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +32 -9
  32. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  33. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -35
  34. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  35. package/dist/packlets/ai-assist/streamingAdapters/common.js +25 -1
  36. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  37. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  38. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  39. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +45 -11
  40. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  41. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +33 -22
  42. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  43. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
  44. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  45. package/dist/packlets/ai-assist/streamingClient.js +20 -5
  46. package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
  47. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
  48. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  49. package/dist/packlets/ai-assist/toolFormats.js +80 -0
  50. package/dist/packlets/ai-assist/toolFormats.js.map +1 -1
  51. package/dist/packlets/ai-assist/toolTypes.js +21 -0
  52. package/dist/packlets/ai-assist/toolTypes.js.map +1 -0
  53. package/dist/packlets/ai-assist/usageNormalization.js +178 -0
  54. package/dist/packlets/ai-assist/usageNormalization.js.map +1 -0
  55. package/dist/packlets/ai-assist/usageTypes.js +21 -0
  56. package/dist/packlets/ai-assist/usageTypes.js.map +1 -0
  57. package/dist/packlets/mustache/index.js.map +1 -1
  58. package/dist/packlets/mustache/interfaces.js.map +1 -1
  59. package/dist/packlets/mustache/mustacheTemplate.js +91 -0
  60. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -1
  61. package/dist/ts-extras.d.ts +764 -48
  62. package/lib/packlets/ai-assist/cacheRequest.d.ts +100 -0
  63. package/lib/packlets/ai-assist/cacheRequest.d.ts.map +1 -0
  64. package/lib/packlets/ai-assist/cacheRequest.js +123 -0
  65. package/lib/packlets/ai-assist/cacheRequest.js.map +1 -0
  66. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +36 -6
  67. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
  68. package/lib/packlets/ai-assist/chatRequestBuilders.js +75 -7
  69. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  70. package/lib/packlets/ai-assist/completionClient.d.ts +19 -0
  71. package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
  72. package/lib/packlets/ai-assist/completionClient.js +194 -57
  73. package/lib/packlets/ai-assist/completionClient.js.map +1 -1
  74. package/lib/packlets/ai-assist/converters.d.ts +46 -0
  75. package/lib/packlets/ai-assist/converters.d.ts.map +1 -1
  76. package/lib/packlets/ai-assist/converters.js +55 -1
  77. package/lib/packlets/ai-assist/converters.js.map +1 -1
  78. package/lib/packlets/ai-assist/embeddingClient.d.ts +9 -0
  79. package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -1
  80. package/lib/packlets/ai-assist/embeddingClient.js +16 -1
  81. package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
  82. package/lib/packlets/ai-assist/imageGenerationClient.d.ts +9 -0
  83. package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
  84. package/lib/packlets/ai-assist/imageGenerationClient.js +17 -2
  85. package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  86. package/lib/packlets/ai-assist/index.d.ts +7 -2
  87. package/lib/packlets/ai-assist/index.d.ts.map +1 -1
  88. package/lib/packlets/ai-assist/index.js +11 -1
  89. package/lib/packlets/ai-assist/index.js.map +1 -1
  90. package/lib/packlets/ai-assist/listModelsClient.d.ts +12 -0
  91. package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -1
  92. package/lib/packlets/ai-assist/listModelsClient.js +19 -1
  93. package/lib/packlets/ai-assist/listModelsClient.js.map +1 -1
  94. package/lib/packlets/ai-assist/model.d.ts +81 -295
  95. package/lib/packlets/ai-assist/model.d.ts.map +1 -1
  96. package/lib/packlets/ai-assist/model.js.map +1 -1
  97. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts +124 -0
  98. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts.map +1 -0
  99. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +208 -0
  100. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  101. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts +77 -0
  102. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts.map +1 -0
  103. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js +143 -0
  104. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  105. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts +84 -0
  106. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts.map +1 -0
  107. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js +163 -0
  108. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  109. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts +105 -0
  110. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts.map +1 -0
  111. package/lib/packlets/ai-assist/promptCacheUsageMath.js +130 -0
  112. package/lib/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  113. package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
  114. package/lib/packlets/ai-assist/registry.js +9 -11
  115. package/lib/packlets/ai-assist/registry.js.map +1 -1
  116. package/lib/packlets/ai-assist/streamUsageCapability.d.ts +129 -0
  117. package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -0
  118. package/lib/packlets/ai-assist/streamUsageCapability.js +140 -0
  119. package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  120. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +2 -1
  121. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
  122. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +29 -6
  123. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  124. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +58 -14
  125. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
  126. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -36
  127. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  128. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +38 -3
  129. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
  130. package/lib/packlets/ai-assist/streamingAdapters/common.js +25 -1
  131. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  132. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
  133. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  134. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  135. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +2 -1
  136. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
  137. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +42 -8
  138. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  139. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +2 -1
  140. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
  141. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +30 -19
  142. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  143. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +22 -0
  144. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
  145. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
  146. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  147. package/lib/packlets/ai-assist/streamingClient.d.ts +5 -0
  148. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
  149. package/lib/packlets/ai-assist/streamingClient.js +20 -5
  150. package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
  151. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +11 -3
  152. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
  153. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
  154. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  155. package/lib/packlets/ai-assist/toolFormats.d.ts +55 -1
  156. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -1
  157. package/lib/packlets/ai-assist/toolFormats.js +82 -0
  158. package/lib/packlets/ai-assist/toolFormats.js.map +1 -1
  159. package/lib/packlets/ai-assist/toolTypes.d.ts +386 -0
  160. package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -0
  161. package/lib/packlets/ai-assist/toolTypes.js +22 -0
  162. package/lib/packlets/ai-assist/toolTypes.js.map +1 -0
  163. package/lib/packlets/ai-assist/usageNormalization.d.ts +58 -0
  164. package/lib/packlets/ai-assist/usageNormalization.d.ts.map +1 -0
  165. package/lib/packlets/ai-assist/usageNormalization.js +184 -0
  166. package/lib/packlets/ai-assist/usageNormalization.js.map +1 -0
  167. package/lib/packlets/ai-assist/usageTypes.d.ts +84 -0
  168. package/lib/packlets/ai-assist/usageTypes.d.ts.map +1 -0
  169. package/lib/packlets/ai-assist/usageTypes.js +22 -0
  170. package/lib/packlets/ai-assist/usageTypes.js.map +1 -0
  171. package/lib/packlets/mustache/index.d.ts +1 -1
  172. package/lib/packlets/mustache/index.d.ts.map +1 -1
  173. package/lib/packlets/mustache/index.js.map +1 -1
  174. package/lib/packlets/mustache/interfaces.d.ts +30 -0
  175. package/lib/packlets/mustache/interfaces.d.ts.map +1 -1
  176. package/lib/packlets/mustache/interfaces.js.map +1 -1
  177. package/lib/packlets/mustache/mustacheTemplate.d.ts +56 -1
  178. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -1
  179. package/lib/packlets/mustache/mustacheTemplate.js +91 -0
  180. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -1
  181. package/package.json +16 -16
  182. package/perf/promptCacheAnthropicBreakpoint.js +135 -0
  183. package/perf/promptCacheObservability.js +107 -0
  184. package/perf/promptCacheRoutingAb.js +105 -0
@@ -265,10 +265,28 @@ async function callProviderListModels(params) {
265
265
  * `POST ${proxyUrl}/api/ai/list-models`. Capability config is not forwarded;
266
266
  * `capabilities` is serialized as a string array. Error body `{error: string}`
267
267
  * is surfaced as `proxy: ${error}`.
268
+ *
269
+ * @remarks
270
+ * `capabilityConfig` and `endpoint` are both unusable here, but they are not the
271
+ * same case and are not treated the same way. `capabilityConfig` overrides how a
272
+ * model id is classified, and the proxy returns models already classified — so a
273
+ * caller-supplied override could only ever have arrived too late. Ignoring it
274
+ * yields the default classification: a degraded answer, disclosed above, and
275
+ * that is where it stays. `endpoint` names *which server answers at all*, so
276
+ * ignoring it would list the provider's public catalog in place of the host the
277
+ * caller pinned; it is **refused**, on the same terms as
278
+ * `callProxiedCompletion`.
279
+ *
268
280
  * @public
269
281
  */
270
282
  async function callProxiedListModels(proxyUrl, params) {
271
- const { descriptor, apiKey, capability, logger, signal } = params;
283
+ const { descriptor, apiKey, capability, logger, signal, endpoint } = params;
284
+ if (endpoint !== undefined) {
285
+ return (0, ts_utils_1.fail)(`callProxiedListModels: endpoint is not supported on the proxied path — a proxy ` +
286
+ `cannot confirm it honored it, and silently reaching the provider's default ` +
287
+ `upstream would list a different server's catalog than the caller named. Use ` +
288
+ `callProviderListModels, or route the proxy itself at the intended upstream.`);
289
+ }
272
290
  const body = {
273
291
  providerId: descriptor.id,
274
292
  apiKey
@@ -1 +1 @@
1
- {"version":3,"file":"listModelsClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/listModelsClient.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;;AAgWZ,wDA0CC;AAaD,sDAuCC;AA5bD;;;;;;;GAOG;AAEH,4CAAgG;AAEhG,mCAOiB;AACjB,yCAKoB;AACpB,iCAAoE;AACpE,yCAA6D;AAoB7D,MAAM,sBAAsB,GAAuC,qBAAU,CAAC,MAAM,CAClF;IACE,EAAE,EAAE,qBAAU,CAAC,MAAM;IACrB,YAAY,EAAE,qBAAU,CAAC,OAAO,CAAC,qBAAU,CAAC,eAAe,CAAoB,4BAAoB,CAAC,CAAC;IACrG,WAAW,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;CAC1C,CACF,CAAC;AACF,MAAM,yBAAyB,GAC7B,qBAAU,CAAC,MAAM,CAAyB;IACxC,MAAM,EAAE,qBAAU,CAAC,OAAO,CAAC,sBAAsB,CAAC;CACnD,CAAC,CAAC;AA0CL,MAAM,eAAe,GAAgC,qBAAU,CAAC,MAAM,CAAmB;IACvF,EAAE,EAAE,qBAAU,CAAC,M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AE,WAAW,QAAQ,EAAE,CAAC,CAAC;IAE3F,MAAM,GAAG,GAAG,GAAG,QAAQ,qBAAqB,CAAC;IAC7C,MAAM,UAAU,GAAG,MAAM,IAAA,gBAAS,EAAC,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAClE,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAED,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAgC,CAAC;IAC7D,IAAI,OAAO,QAAQ,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,IAAA,eAAI,EAAC,UAAU,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,yBAAyB;SAC7B,QAAQ,CAAC,QAAQ,CAAC;SAClB,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oCAAoC,GAAG,EAAE,CAAC;SACnE,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;QACpB,MAAM,MAAM,GAAmB,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBACtD,EAAE,EAAE,CAAC,CAAC,EAAE,EACR,YAAY,EAAE,IAAI,GAAG,CAAoB,CAAC,CAAC,YAAY,CAAC,IACrD,CAAC,CAAC,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EACtE,CAAC,CAAC;QACJ,OAAO,IAAA,kBAAO,EAAC,MAAM,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Model-listing clients for AI assist. One provider dispatcher over\n * `IAiProviderDescriptor.apiFormat`, its adapters and response validators, the\n * capability-resolution helpers that turn a raw model id into an\n * `IAiModelInfo`, and the proxied variant.\n *\n * @packageDocumentation\n */\n\nimport { fail, type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport {\n type AiModelCapability,\n allModelCapabilities,\n type IAiModelCapabilityConfig,\n type IAiModelCapabilityRule,\n type IAiModelInfo,\n type IAiProviderDescriptor\n} from './model';\nimport {\n anthropicAuthHeaders,\n bearerAuthHeader,\n geminiAuthHeader,\n resolveEffectiveBaseUrl\n} from './endpoint';\nimport { type IAiApiConfig, fetchGetJson, fetchJson } from './http';\nimport { DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';\n\n// ---- Proxied list-models response ----\n\n/**\n * Wire shape for proxy list-models responses. `capabilities` arrives as an\n * array (Sets don't survive JSON), then gets reassembled into a `Set` in\n * {@link callProxiedListModels}.\n * @internal\n */\ninterface IProxiedListModelsEntry {\n id: string;\n capabilities: AiModelCapability[];\n displayName?: string;\n}\n/** @internal */\ninterface IProxiedListModelsBody {\n models: IProxiedListModelsEntry[];\n}\n\nconst proxiedListModelsEntry: Validator<IProxiedListModelsEntry> = Validators.object<IProxiedListModelsEntry>(\n {\n id: Validators.string,\n capabilities: Validators.arrayOf(Validators.enumeratedValue<AiModelCapability>(allModelCapabilities)),\n displayName: Validators.string.optional()\n }\n);\nconst proxiedListModelsResponse: Validator<IProxiedListModelsBody> =\n Validators.object<IProxiedListModelsBody>({\n models: Validators.arrayOf(proxiedListModelsEntry)\n });\n\n// ============================================================================\n// List models — request types\n// ============================================================================\n\n/**\n * Parameters for a list-models request.\n * @public\n */\nexport interface IProviderListModelsParams {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /** Optional capability filter; when set, only models declaring this capability are returned. */\n readonly capability?: AiModelCapability;\n /** Optional capability config override (defaults to {@link DEFAULT_MODEL_CAPABILITY_CONFIG}). */\n readonly capabilityConfig?: IAiModelCapabilityConfig;\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /** Optional override of the descriptor's base URL; per-format `/models` route is appended unchanged. */\n readonly endpoint?: string;\n}\n\n// ============================================================================\n// List models — response validators\n// ============================================================================\n\n// ---- OpenAI / xAI / Groq / Mistral list format ----\n\n/** @internal */\ninterface IOpenAiListEntry {\n id: string;\n}\n/** @internal */\ninterface IOpenAiListResponse {\n data: IOpenAiListEntry[];\n}\n\nconst openAiListEntry: Validator<IOpenAiListEntry> = Validators.object<IOpenAiListEntry>({\n id: Validators.string\n});\nconst openAiListResponse: Validator<IOpenAiListResponse> = Validators.object<IOpenAiListResponse>({\n data: Validators.arrayOf(openAiListEntry)\n});\n\n// ---- Anthropic list format ----\n\n/** @internal */\ninterface IAnthropicListEntry {\n id: string;\n display_name?: string;\n}\n/** @internal */\ninterface IAnthropicListResponse {\n data: IAnthropicListEntry[];\n}\n\nconst anthropicListEntry: Validator<IAnthropicListEntry> = Validators.object<IAnthropicListEntry>({\n id: Validators.string,\n display_name: Validators.string.optional()\n});\nconst anthropicListResponse: Validator<IAnthropicListResponse> = Validators.object<IAnthropicListResponse>({\n data: Validators.arrayOf(anthropicListEntry)\n});\n\n// ---- Gemini list format ----\n\n/** @internal */\ninterface IGeminiListEntry {\n name: string;\n displayName?: string;\n supportedGenerationMethods?: string[];\n}\n/** @internal */\ninterface IGeminiListResponse {\n models: IGeminiListEntry[];\n}\n\nconst geminiListEntry: Validator<IGeminiListEntry> = Validators.object<IGeminiListEntry>({\n name: Validators.string,\n displayName: Validators.string.optional(),\n supportedGenerationMethods: Validators.arrayOf(Validators.string).optional()\n});\nconst geminiListResponse: Validator<IGeminiListResponse> = Validators.object<IGeminiListResponse>({\n models: Validators.arrayOf(geminiListEntry)\n});\n\n// ============================================================================\n// List models — capability resolution\n// ============================================================================\n\n/**\n * Translates Gemini's `supportedGenerationMethods` strings into our abstract\n * capability vocabulary. Methods without a mapping are ignored.\n * @internal\n */\nfunction geminiMethodsToCapabilities(methods: ReadonlyArray<string>): ReadonlyArray<AiModelCapability> {\n const out: AiModelCapability[] = [];\n for (const m of methods) {\n if (m === 'generateContent') {\n out.push('chat');\n } else if (m === 'predict') {\n out.push('image-generation');\n }\n }\n return out;\n}\n\n/**\n * Strips the `models/` prefix Gemini includes on listed model names.\n * @internal\n */\nfunction geminiBareId(name: string): string {\n /* c8 ignore next 1 - defensive: Gemini API always returns names prefixed with 'models/' */\n return name.startsWith('models/') ? name.substring('models/'.length) : name;\n}\n\n/**\n * Applies a capability config to a model id. Walks per-provider rules then\n * global rules; unions all matching rules' capabilities. Returns the union\n * and the first matching `displayName` (if any).\n * @internal\n */\nfunction applyCapabilityConfig(\n config: IAiModelCapabilityConfig,\n providerId: string,\n modelId: string\n): { capabilities: AiModelCapability[]; displayName: string | undefined } {\n const caps = new Set<AiModelCapability>();\n let displayName: string | undefined;\n\n const rulesets: ReadonlyArray<ReadonlyArray<IAiModelCapabilityRule>> = [\n config.perProvider?.[providerId as keyof typeof config.perProvider] ?? [],\n config.global ?? []\n ];\n\n for (const rules of rulesets) {\n for (const rule of rules) {\n rule.idPattern.lastIndex = 0;\n if (rule.idPattern.test(modelId)) {\n for (const cap of rule.capabilities) {\n caps.add(cap);\n }\n if (displayName === undefined && rule.displayName !== undefined) {\n displayName = typeof rule.displayName === 'function' ? rule.displayName(modelId) : rule.displayName;\n }\n }\n }\n }\n return { capabilities: Array.from(caps), displayName };\n}\n\n/**\n * Combines provider-native capability info (when supplied) and config-derived\n * capability info into a final {@link IAiModelInfo}.\n * @internal\n */\nfunction buildModelInfo(\n providerId: string,\n id: string,\n nativeCapabilities: ReadonlyArray<AiModelCapability>,\n nativeDisplayName: string | undefined,\n config: IAiModelCapabilityConfig\n): IAiModelInfo {\n const fromConfig = applyCapabilityConfig(config, providerId, id);\n const all = new Set<AiModelCapability>([...nativeCapabilities, ...fromConfig.capabilities]);\n return {\n id,\n capabilities: all,\n ...(nativeDisplayName !== undefined\n ? { displayName: nativeDisplayName }\n : fromConfig.displayName !== undefined\n ? { displayName: fromConfig.displayName }\n : {})\n };\n}\n\n// ============================================================================\n// List models — adapters\n// ============================================================================\n\n/**\n * Calls the OpenAI-style `GET /models` endpoint. Used by openai, xai-grok,\n * groq, and mistral. Provider supplies no capability info — capabilities are\n * derived entirely from the config.\n * @internal\n */\nasync function callOpenAiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=openai`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], undefined, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Anthropic `GET /models` endpoint. Provider supplies a\n * `display_name` but no native capability info.\n * @internal\n */\nasync function callAnthropicListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=anthropic`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return anthropicListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Anthropic models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], entry.display_name, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Gemini `GET /models` endpoint. Provider supplies both a\n * `displayName` and `supportedGenerationMethods` — translated to native\n * capabilities and unioned with config-derived capabilities.\n * @internal\n */\nasync function callGeminiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=gemini`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.models.map((entry) => {\n const id = geminiBareId(entry.name);\n const native = entry.supportedGenerationMethods\n ? geminiMethodsToCapabilities(entry.supportedGenerationMethods)\n : [];\n return buildModelInfo(providerId, id, native, entry.displayName, capabilityConfig);\n });\n return succeed(models);\n });\n}\n\n// ============================================================================\n// List models — dispatcher\n// ============================================================================\n\n/**\n * Lists models available from a provider, routing by `descriptor.apiFormat`.\n * Capabilities are resolved from native provider info and a configurable rule set.\n * @param params - Request parameters (descriptor, API key, optional capability filter)\n * @public\n */\nexport async function callProviderListModels(\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, capabilityConfig, logger, signal, endpoint } = params;\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n\n const config: IAiApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model: '' // unused by listing\n };\n const effectiveConfig = capabilityConfig ?? DEFAULT_MODEL_CAPABILITY_CONFIG;\n\n let listResult: Result<ReadonlyArray<IAiModelInfo>>;\n switch (descriptor.apiFormat) {\n case 'openai':\n listResult = await callOpenAiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'anthropic':\n listResult = await callAnthropicListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'gemini':\n listResult = await callGeminiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = descriptor.apiFormat;\n return fail(`unsupported API format: ${String(_exhaustive)}`);\n }\n }\n\n if (listResult.isFailure()) {\n return listResult;\n }\n if (capability === undefined) {\n return listResult;\n }\n return succeed(listResult.value.filter((m) => m.capabilities.has(capability)));\n}\n\n// ============================================================================\n// Proxied list models\n// ============================================================================\n\n/**\n * Calls the model-listing endpoint on a proxy server. Endpoint:\n * `POST ${proxyUrl}/api/ai/list-models`. Capability config is not forwarded;\n * `capabilities` is serialized as a string array. Error body `{error: string}`\n * is surfaced as `proxy: ${error}`.\n * @public\n */\nexport async function callProxiedListModels(\n proxyUrl: string,\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, logger, signal } = params;\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey\n };\n if (capability !== undefined) {\n body.capability = capability;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI list-models proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n\n const url = `${proxyUrl}/api/ai/list-models`;\n const jsonResult = await fetchJson(url, {}, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const response = jsonResult.value as Record<string, unknown>;\n if (typeof response.error === 'string') {\n return fail(`proxy: ${response.error}`);\n }\n\n return proxiedListModelsResponse\n .validate(response)\n .withErrorFormat((msg) => `proxy returned invalid response: ${msg}`)\n .onSuccess((parsed) => {\n const models: IAiModelInfo[] = parsed.models.map((m) => ({\n id: m.id,\n capabilities: new Set<AiModelCapability>(m.capabilities),\n ...(m.displayName !== undefined ? { displayName: m.displayName } : {})\n }));\n return succeed(models);\n });\n}\n"]}
1
+ {"version":3,"file":"listModelsClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/listModelsClient.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;;AAgWZ,wDA0CC;AAyBD,sDAgDC;AAjdD;;;;;;;GAOG;AAEH,4CAAgG;AAEhG,mCAOiB;AACjB,yCAK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C7B,QAAQ,CAAC,QAAQ,CAAC;SAClB,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oCAAoC,GAAG,EAAE,CAAC;SACnE,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;QACpB,MAAM,MAAM,GAAmB,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBACtD,EAAE,EAAE,CAAC,CAAC,EAAE,EACR,YAAY,EAAE,IAAI,GAAG,CAAoB,CAAC,CAAC,YAAY,CAAC,IACrD,CAAC,CAAC,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EACtE,CAAC,CAAC;QACJ,OAAO,IAAA,kBAAO,EAAC,MAAM,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Model-listing clients for AI assist. One provider dispatcher over\n * `IAiProviderDescriptor.apiFormat`, its adapters and response validators, the\n * capability-resolution helpers that turn a raw model id into an\n * `IAiModelInfo`, and the proxied variant.\n *\n * @packageDocumentation\n */\n\nimport { fail, type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport {\n type AiModelCapability,\n allModelCapabilities,\n type IAiModelCapabilityConfig,\n type IAiModelCapabilityRule,\n type IAiModelInfo,\n type IAiProviderDescriptor\n} from './model';\nimport {\n anthropicAuthHeaders,\n bearerAuthHeader,\n geminiAuthHeader,\n resolveEffectiveBaseUrl\n} from './endpoint';\nimport { type IAiApiConfig, fetchGetJson, fetchJson } from './http';\nimport { DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';\n\n// ---- Proxied list-models response ----\n\n/**\n * Wire shape for proxy list-models responses. `capabilities` arrives as an\n * array (Sets don't survive JSON), then gets reassembled into a `Set` in\n * {@link callProxiedListModels}.\n * @internal\n */\ninterface IProxiedListModelsEntry {\n id: string;\n capabilities: AiModelCapability[];\n displayName?: string;\n}\n/** @internal */\ninterface IProxiedListModelsBody {\n models: IProxiedListModelsEntry[];\n}\n\nconst proxiedListModelsEntry: Validator<IProxiedListModelsEntry> = Validators.object<IProxiedListModelsEntry>(\n {\n id: Validators.string,\n capabilities: Validators.arrayOf(Validators.enumeratedValue<AiModelCapability>(allModelCapabilities)),\n displayName: Validators.string.optional()\n }\n);\nconst proxiedListModelsResponse: Validator<IProxiedListModelsBody> =\n Validators.object<IProxiedListModelsBody>({\n models: Validators.arrayOf(proxiedListModelsEntry)\n });\n\n// ============================================================================\n// List models — request types\n// ============================================================================\n\n/**\n * Parameters for a list-models request.\n * @public\n */\nexport interface IProviderListModelsParams {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /** Optional capability filter; when set, only models declaring this capability are returned. */\n readonly capability?: AiModelCapability;\n /** Optional capability config override (defaults to {@link DEFAULT_MODEL_CAPABILITY_CONFIG}). */\n readonly capabilityConfig?: IAiModelCapabilityConfig;\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /** Optional override of the descriptor's base URL; per-format `/models` route is appended unchanged. */\n readonly endpoint?: string;\n}\n\n// ============================================================================\n// List models — response validators\n// ============================================================================\n\n// ---- OpenAI / xAI / Groq / Mistral list format ----\n\n/** @internal */\ninterface IOpenAiListEntry {\n id: string;\n}\n/** @internal */\ninterface IOpenAiListResponse {\n data: IOpenAiListEntry[];\n}\n\nconst openAiListEntry: Validator<IOpenAiListEntry> = Validators.object<IOpenAiListEntry>({\n id: Validators.string\n});\nconst openAiListResponse: Validator<IOpenAiListResponse> = Validators.object<IOpenAiListResponse>({\n data: Validators.arrayOf(openAiListEntry)\n});\n\n// ---- Anthropic list format ----\n\n/** @internal */\ninterface IAnthropicListEntry {\n id: string;\n display_name?: string;\n}\n/** @internal */\ninterface IAnthropicListResponse {\n data: IAnthropicListEntry[];\n}\n\nconst anthropicListEntry: Validator<IAnthropicListEntry> = Validators.object<IAnthropicListEntry>({\n id: Validators.string,\n display_name: Validators.string.optional()\n});\nconst anthropicListResponse: Validator<IAnthropicListResponse> = Validators.object<IAnthropicListResponse>({\n data: Validators.arrayOf(anthropicListEntry)\n});\n\n// ---- Gemini list format ----\n\n/** @internal */\ninterface IGeminiListEntry {\n name: string;\n displayName?: string;\n supportedGenerationMethods?: string[];\n}\n/** @internal */\ninterface IGeminiListResponse {\n models: IGeminiListEntry[];\n}\n\nconst geminiListEntry: Validator<IGeminiListEntry> = Validators.object<IGeminiListEntry>({\n name: Validators.string,\n displayName: Validators.string.optional(),\n supportedGenerationMethods: Validators.arrayOf(Validators.string).optional()\n});\nconst geminiListResponse: Validator<IGeminiListResponse> = Validators.object<IGeminiListResponse>({\n models: Validators.arrayOf(geminiListEntry)\n});\n\n// ============================================================================\n// List models — capability resolution\n// ============================================================================\n\n/**\n * Translates Gemini's `supportedGenerationMethods` strings into our abstract\n * capability vocabulary. Methods without a mapping are ignored.\n * @internal\n */\nfunction geminiMethodsToCapabilities(methods: ReadonlyArray<string>): ReadonlyArray<AiModelCapability> {\n const out: AiModelCapability[] = [];\n for (const m of methods) {\n if (m === 'generateContent') {\n out.push('chat');\n } else if (m === 'predict') {\n out.push('image-generation');\n }\n }\n return out;\n}\n\n/**\n * Strips the `models/` prefix Gemini includes on listed model names.\n * @internal\n */\nfunction geminiBareId(name: string): string {\n /* c8 ignore next 1 - defensive: Gemini API always returns names prefixed with 'models/' */\n return name.startsWith('models/') ? name.substring('models/'.length) : name;\n}\n\n/**\n * Applies a capability config to a model id. Walks per-provider rules then\n * global rules; unions all matching rules' capabilities. Returns the union\n * and the first matching `displayName` (if any).\n * @internal\n */\nfunction applyCapabilityConfig(\n config: IAiModelCapabilityConfig,\n providerId: string,\n modelId: string\n): { capabilities: AiModelCapability[]; displayName: string | undefined } {\n const caps = new Set<AiModelCapability>();\n let displayName: string | undefined;\n\n const rulesets: ReadonlyArray<ReadonlyArray<IAiModelCapabilityRule>> = [\n config.perProvider?.[providerId as keyof typeof config.perProvider] ?? [],\n config.global ?? []\n ];\n\n for (const rules of rulesets) {\n for (const rule of rules) {\n rule.idPattern.lastIndex = 0;\n if (rule.idPattern.test(modelId)) {\n for (const cap of rule.capabilities) {\n caps.add(cap);\n }\n if (displayName === undefined && rule.displayName !== undefined) {\n displayName = typeof rule.displayName === 'function' ? rule.displayName(modelId) : rule.displayName;\n }\n }\n }\n }\n return { capabilities: Array.from(caps), displayName };\n}\n\n/**\n * Combines provider-native capability info (when supplied) and config-derived\n * capability info into a final {@link IAiModelInfo}.\n * @internal\n */\nfunction buildModelInfo(\n providerId: string,\n id: string,\n nativeCapabilities: ReadonlyArray<AiModelCapability>,\n nativeDisplayName: string | undefined,\n config: IAiModelCapabilityConfig\n): IAiModelInfo {\n const fromConfig = applyCapabilityConfig(config, providerId, id);\n const all = new Set<AiModelCapability>([...nativeCapabilities, ...fromConfig.capabilities]);\n return {\n id,\n capabilities: all,\n ...(nativeDisplayName !== undefined\n ? { displayName: nativeDisplayName }\n : fromConfig.displayName !== undefined\n ? { displayName: fromConfig.displayName }\n : {})\n };\n}\n\n// ============================================================================\n// List models — adapters\n// ============================================================================\n\n/**\n * Calls the OpenAI-style `GET /models` endpoint. Used by openai, xai-grok,\n * groq, and mistral. Provider supplies no capability info — capabilities are\n * derived entirely from the config.\n * @internal\n */\nasync function callOpenAiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=openai`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], undefined, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Anthropic `GET /models` endpoint. Provider supplies a\n * `display_name` but no native capability info.\n * @internal\n */\nasync function callAnthropicListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=anthropic`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return anthropicListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Anthropic models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.data.map((entry) =>\n buildModelInfo(providerId, entry.id, [], entry.display_name, capabilityConfig)\n );\n return succeed(models);\n });\n}\n\n/**\n * Calls the Gemini `GET /models` endpoint. Provider supplies both a\n * `displayName` and `supportedGenerationMethods` — translated to native\n * capabilities and unioned with config-derived capabilities.\n * @internal\n */\nasync function callGeminiListModels(\n config: IAiApiConfig,\n providerId: string,\n capabilityConfig: IAiModelCapabilityConfig,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const url = `${config.baseUrl}/models`;\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n /* c8 ignore next 1 - optional logger */\n logger?.info(`List models: provider=${providerId}, format=gemini`);\n const jsonResult = await fetchGetJson(url, headers, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiListResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini models API response: ${msg}`)\n .onSuccess((response) => {\n const models = response.models.map((entry) => {\n const id = geminiBareId(entry.name);\n const native = entry.supportedGenerationMethods\n ? geminiMethodsToCapabilities(entry.supportedGenerationMethods)\n : [];\n return buildModelInfo(providerId, id, native, entry.displayName, capabilityConfig);\n });\n return succeed(models);\n });\n}\n\n// ============================================================================\n// List models — dispatcher\n// ============================================================================\n\n/**\n * Lists models available from a provider, routing by `descriptor.apiFormat`.\n * Capabilities are resolved from native provider info and a configurable rule set.\n * @param params - Request parameters (descriptor, API key, optional capability filter)\n * @public\n */\nexport async function callProviderListModels(\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, capabilityConfig, logger, signal, endpoint } = params;\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n\n const config: IAiApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model: '' // unused by listing\n };\n const effectiveConfig = capabilityConfig ?? DEFAULT_MODEL_CAPABILITY_CONFIG;\n\n let listResult: Result<ReadonlyArray<IAiModelInfo>>;\n switch (descriptor.apiFormat) {\n case 'openai':\n listResult = await callOpenAiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'anthropic':\n listResult = await callAnthropicListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n case 'gemini':\n listResult = await callGeminiListModels(config, descriptor.id, effectiveConfig, logger, signal);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = descriptor.apiFormat;\n return fail(`unsupported API format: ${String(_exhaustive)}`);\n }\n }\n\n if (listResult.isFailure()) {\n return listResult;\n }\n if (capability === undefined) {\n return listResult;\n }\n return succeed(listResult.value.filter((m) => m.capabilities.has(capability)));\n}\n\n// ============================================================================\n// Proxied list models\n// ============================================================================\n\n/**\n * Calls the model-listing endpoint on a proxy server. Endpoint:\n * `POST ${proxyUrl}/api/ai/list-models`. Capability config is not forwarded;\n * `capabilities` is serialized as a string array. Error body `{error: string}`\n * is surfaced as `proxy: ${error}`.\n *\n * @remarks\n * `capabilityConfig` and `endpoint` are both unusable here, but they are not the\n * same case and are not treated the same way. `capabilityConfig` overrides how a\n * model id is classified, and the proxy returns models already classified — so a\n * caller-supplied override could only ever have arrived too late. Ignoring it\n * yields the default classification: a degraded answer, disclosed above, and\n * that is where it stays. `endpoint` names *which server answers at all*, so\n * ignoring it would list the provider's public catalog in place of the host the\n * caller pinned; it is **refused**, on the same terms as\n * `callProxiedCompletion`.\n *\n * @public\n */\nexport async function callProxiedListModels(\n proxyUrl: string,\n params: IProviderListModelsParams\n): Promise<Result<ReadonlyArray<IAiModelInfo>>> {\n const { descriptor, apiKey, capability, logger, signal, endpoint } = params;\n\n if (endpoint !== undefined) {\n return fail(\n `callProxiedListModels: endpoint is not supported on the proxied path — a proxy ` +\n `cannot confirm it honored it, and silently reaching the provider's default ` +\n `upstream would list a different server's catalog than the caller named. Use ` +\n `callProviderListModels, or route the proxy itself at the intended upstream.`\n );\n }\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey\n };\n if (capability !== undefined) {\n body.capability = capability;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI list-models proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n\n const url = `${proxyUrl}/api/ai/list-models`;\n const jsonResult = await fetchJson(url, {}, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const response = jsonResult.value as Record<string, unknown>;\n if (typeof response.error === 'string') {\n return fail(`proxy: ${response.error}`);\n }\n\n return proxiedListModelsResponse\n .validate(response)\n .withErrorFormat((msg) => `proxy returned invalid response: ${msg}`)\n .onSuccess((parsed) => {\n const models: IAiModelInfo[] = parsed.models.map((m) => ({\n id: m.id,\n capabilities: new Set<AiModelCapability>(m.capabilities),\n ...(m.displayName !== undefined ? { displayName: m.displayName } : {})\n }));\n return succeed(models);\n });\n}\n"]}
@@ -3,8 +3,10 @@
3
3
  * @packageDocumentation
4
4
  */
5
5
  import { type Result } from '@fgv/ts-utils';
6
- import { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';
6
+ import { type JsonObject } from '@fgv/ts-json-base';
7
7
  import type { IAiStructuredOutputCapability, StructuredOutputEnforcement } from './structuredOutputTypes';
8
+ import type { IAiCompletionUsage } from './usageTypes';
9
+ import type { AiServerToolType, IAiStreamToolUseComplete, IAiStreamToolUseDelta, IAiStreamToolUseStart, IAiToolEnablement } from './toolTypes';
8
10
  /**
9
11
  * Universal image representation used for both image input (vision prompts)
10
12
  * and image output (generation responses).
@@ -125,267 +127,7 @@ export interface IChatRequest {
125
127
  */
126
128
  readonly messages: ReadonlyArray<IChatMessage>;
127
129
  }
128
- /**
129
- * Built-in server-side tool types supported across providers.
130
- * @public
131
- */
132
- export type AiServerToolType = 'web_search';
133
- /**
134
- * Configuration specific to web search tools.
135
- * @public
136
- */
137
- export interface IAiWebSearchToolConfig {
138
- readonly type: 'web_search';
139
- /** Optional: restrict search to these domains. */
140
- readonly allowedDomains?: ReadonlyArray<string>;
141
- /** Optional: exclude these domains from search. */
142
- readonly blockedDomains?: ReadonlyArray<string>;
143
- /** Optional: max number of searches per request. */
144
- readonly maxUses?: number;
145
- /**
146
- * Optional: enable image understanding during web search.
147
- * When true, the model can view and analyze images found during search.
148
- * Currently supported by xAI only; ignored by other providers.
149
- */
150
- readonly enableImageUnderstanding?: boolean;
151
- }
152
- /**
153
- * Union of all server-side tool configurations. Discriminated on `type`.
154
- * @public
155
- */
156
- export type AiServerToolConfig = IAiWebSearchToolConfig;
157
- /**
158
- * Declares a tool as enabled/disabled in provider settings.
159
- * Tools are disabled by default — consuming apps must opt in explicitly.
160
- * @public
161
- */
162
- export interface IAiToolEnablement {
163
- /** Which tool type. */
164
- readonly type: AiServerToolType;
165
- /** Whether this tool is enabled by default for this provider. */
166
- readonly enabled: boolean;
167
- /** Optional tool-specific configuration. */
168
- readonly config?: AiServerToolConfig;
169
- }
170
- /**
171
- * Behavior annotations for a client-defined tool.
172
- *
173
- * @remarks
174
- * These are **host-advisory-only hints** describing a tool's side-effect profile.
175
- * They are consumed by the host's tool loop (e.g. a before-execute gate) and are
176
- * **never serialized to the model** — the provider wire tool-schemas whitelist
177
- * `{name, description, parameters}` and ignore this field.
178
- *
179
- * Field names mirror MCP's `ToolAnnotations` (`@modelcontextprotocol/sdk`) 1:1 so
180
- * an MCP tool's annotations pass through unchanged. Per the MCP spec, all fields
181
- * are hints — a host should never make tool-use decisions based on annotations
182
- * received from an untrusted server without its own validation.
183
- *
184
- * @public
185
- */
186
- export interface IAiToolAnnotations {
187
- /** Optional human-readable display title for the tool. */
188
- readonly title?: string;
189
- /** Hint: the tool does not modify its environment (read-only). */
190
- readonly readOnlyHint?: boolean;
191
- /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */
192
- readonly destructiveHint?: boolean;
193
- /** Hint: repeated calls with the same arguments have no additional effect. */
194
- readonly idempotentHint?: boolean;
195
- /** Hint: the tool interacts with an open world of external entities. */
196
- readonly openWorldHint?: boolean;
197
- }
198
- /**
199
- * Configuration for a client-defined (harness-supplied) tool.
200
- *
201
- * @remarks
202
- * The `parametersSchema` is the single source of truth for both the wire-format
203
- * JSON Schema sent to the provider (via `.toJson()`) and the runtime argument
204
- * validation (via `.validate(rawArgs)`). Use `JsonSchema.object(...)` from
205
- * `@fgv/ts-json-base` to author the schema as a const (e.g. `const mySchema = JsonSchema.object({...})`);
206
- * the static type `TParams` is then derived via `JsonSchema.Static<typeof mySchema>` —
207
- * no drift between wire schema and runtime validation.
208
- *
209
- * @public
210
- */
211
- export interface IAiClientToolConfig<TParams = unknown> {
212
- /** Discriminator — always `'client_tool'`. */
213
- readonly type: 'client_tool';
214
- /** Tool name sent to the model (must be unique within a call). */
215
- readonly name: string;
216
- /** Human-readable description of what the tool does, shown to the model. */
217
- readonly description: string;
218
- /**
219
- * JSON Schema validator for the tool's parameters. Emits wire format via
220
- * `.toJson()` and validates model-returned args via `.validate(rawArgs)`.
221
- */
222
- readonly parametersSchema: JsonSchema.ISchemaValidator<TParams>;
223
- /**
224
- * Optional host-advisory behavior annotations (read-only / destructive /
225
- * idempotent / open-world hints + display title). Consumed by the host's
226
- * tool loop; never serialized to the model. See {@link IAiToolAnnotations}.
227
- */
228
- readonly annotations?: IAiToolAnnotations;
229
- }
230
- /**
231
- * A client-defined tool: configuration + execution callback pair.
232
- *
233
- * @remarks
234
- * The `execute` callback receives typed `TParams` (already validated by
235
- * `config.parametersSchema.validate()`) and returns a `Promise<Result<unknown>>`.
236
- * Thrown errors are caught via `captureAsyncResult` in the round-trip helper.
237
- *
238
- * @public
239
- */
240
- export interface IAiClientTool<TParams = unknown> {
241
- /** The tool's configuration (name, description, parameters schema). */
242
- readonly config: IAiClientToolConfig<TParams>;
243
- /**
244
- * Execute the tool with validated parameters.
245
- * @param args - Typed arguments, already validated against `config.parametersSchema`.
246
- * @returns A `Promise<Result<unknown>>` — the result is stringified and sent back to the model.
247
- */
248
- readonly execute: (args: TParams) => Promise<Result<unknown>>;
249
- }
250
- /**
251
- * Union of all tool configurations: server-side or client-defined.
252
- * Discriminated on `type`.
253
- * @public
254
- */
255
- export type AiToolConfig = AiServerToolConfig | IAiClientToolConfig;
256
- /**
257
- * Emitted when a client-defined tool call begins streaming. Carries the tool name
258
- * and optional provider-assigned call ID (Anthropic / OpenAI Responses API; absent
259
- * for Gemini which does not assign call IDs).
260
- * @public
261
- */
262
- export interface IAiStreamToolUseStart {
263
- readonly type: 'client-tool-call-start';
264
- /** The name of the client tool being called. */
265
- readonly toolName: string;
266
- /**
267
- * Provider-assigned call identifier (Anthropic: `toolu_*`; OpenAI: `call_*`).
268
- * Absent for Gemini (correlation by name).
269
- */
270
- readonly callId?: string;
271
- }
272
- /**
273
- * Emitted when a client-defined tool call is complete and its arguments are fully
274
- * accumulated. The `args` object is the fully parsed JSON object — no further
275
- * streaming deltas follow for this call.
276
- * @public
277
- */
278
- export interface IAiStreamToolUseDelta {
279
- readonly type: 'client-tool-call-done';
280
- /** The name of the client tool being called. */
281
- readonly toolName: string;
282
- /**
283
- * Provider-assigned call identifier. Absent for Gemini.
284
- */
285
- readonly callId?: string;
286
- /** The fully accumulated and parsed tool arguments. */
287
- readonly args: JsonObject;
288
- }
289
- /**
290
- * Emitted after a client-defined tool has been executed and the result is ready
291
- * to be fed back to the model in the round-trip continuation.
292
- * @public
293
- */
294
- export interface IAiStreamToolUseComplete {
295
- readonly type: 'client-tool-result';
296
- /** The name of the client tool that was executed. */
297
- readonly toolName: string;
298
- /**
299
- * Provider-assigned call identifier. Absent for Gemini.
300
- */
301
- readonly callId?: string;
302
- /** The stringified result returned by the tool's execute callback. */
303
- readonly result: string;
304
- /** Whether the tool execution failed (schema validation failure, execute error, or unknown tool). */
305
- readonly isError: boolean;
306
- }
307
- /**
308
- * Summary of a single client tool call within a turn: the tool name, call ID,
309
- * raw arguments, execution result, and whether the execution was an error.
310
- * @public
311
- */
312
- export interface IAiClientToolCallSummary {
313
- /** The name of the tool that was called. */
314
- readonly toolName: string;
315
- /** Provider-assigned call identifier (absent for Gemini). */
316
- readonly callId?: string;
317
- /** The fully accumulated raw arguments object as parsed JSON. */
318
- readonly args: JsonObject;
319
- /** The stringified result (success value or error message). */
320
- readonly result: string;
321
- /** Whether execution failed (schema validation failure, execute error, or unknown tool). */
322
- readonly isError: boolean;
323
- }
324
- /**
325
- * The provider-specific continuation data needed to build the follow-up request
326
- * for the next round of the conversation.
327
- *
328
- * @remarks
329
- * `messages` are provider-native request objects (Anthropic: content-block arrays,
330
- * OpenAI Responses API: input items, Gemini: content parts). The continuation
331
- * builder in `clientToolContinuationBuilder.ts` populates this.
332
- *
333
- * @public
334
- */
335
- export interface IAiClientToolContinuation {
336
- /**
337
- * **Cumulative** provider-native wire-format message objects covering all
338
- * tool rounds so far. On each turn, `executeClientToolTurn` prepends the
339
- * inbound `continuationMessages` so that this array always contains the
340
- * complete wire tail from round 1 through the current round.
341
- *
342
- * To drive a multi-round loop, simply **replace** `continuationMessages`
343
- * with this value — do not manually concatenate:
344
- *
345
- * ```ts
346
- * let tail: JsonObject[] | undefined;
347
- * while (true) {
348
- * const { events, nextTurn } = executeClientToolTurn({
349
- * ..., continuationMessages: tail
350
- * }).orThrow();
351
- * for await (const e of events) { /* observe *\/ }
352
- * const outcome = (await nextTurn).orThrow();
353
- * if (!outcome.continuation) break;
354
- * tail = [...outcome.continuation.messages]; // replace — already cumulative
355
- * }
356
- * ```
357
- *
358
- * The exact shape is provider-native and may include provider-specific
359
- * blocks (e.g. Anthropic thinking/redacted_thinking/tool_use, OpenAI
360
- * function_call/function_call_output items, Gemini functionCall/functionResponse
361
- * parts). These are NOT `IChatMessage[]` and must NOT be placed in the
362
- * `messages` parameter — the normalized-message path strips provider-native
363
- * fields (thinking signatures, redacted_thinking data) that the server
364
- * requires for continuation validation.
365
- *
366
- * `toolCallsSummary` is per-round only (the calls executed in the current
367
- * turn). Only `messages` is cumulative.
368
- */
369
- readonly messages: ReadonlyArray<JsonObject>;
370
- /** Summary of each tool call executed in this turn (per-round, not cumulative). */
371
- readonly toolCallsSummary: ReadonlyArray<IAiClientToolCallSummary>;
372
- }
373
- /**
374
- * The result of a single client-tool turn: the optional continuation for the next
375
- * call (absent when no tool calls occurred) and whether the stream was truncated.
376
- * @public
377
- */
378
- export interface IAiClientToolTurnResult {
379
- /**
380
- * The continuation data for the next round-trip. `undefined` when the model
381
- * completed without invoking any client tools.
382
- */
383
- readonly continuation: IAiClientToolContinuation | undefined;
384
- /** Whether the stream was truncated (token limit or stop reason). */
385
- readonly truncated: boolean;
386
- /** The full concatenated text from all `text-delta` events in this turn. */
387
- readonly fullText: string;
388
- }
130
+ export type { AiServerToolType, IAiWebSearchToolConfig, AiServerToolConfig, IAiToolEnablement, IAiToolAnnotations, IAiClientToolConfig, AiToolConfig, IAiClientTool, IAiStreamToolUseStart, IAiStreamToolUseDelta, IAiStreamToolUseComplete, AiToolConflictPolicy, IAiToolConflictReport, IAiClientToolCallSummary, IAiClientToolContinuation, IAiClientToolTurnResult } from './toolTypes';
389
131
  /**
390
132
  * Known context keys for model specification maps.
391
133
  *
@@ -402,17 +144,15 @@ export interface IAiClientToolTurnResult {
402
144
  * `'advanced'` / `'frontier'`) and sets the tools / thinking request params
403
145
  * independently. Thinking composes with any tier without a tier-level capability
404
146
  * check — but that is a statement about the tier axis, not a claim that every
405
- * provider supports thinking: several descriptors declare
406
- * `thinkingMode: 'unsupported'` (e.g. `copy-paste`, `groq`, `mistral`, `ollama`,
407
- * `openai-compat`).
408
- *
409
- * Thinking availability is declared **per provider**, on the descriptor's
410
- * `thinkingMode`; the descriptor does not encode per-model thinking availability at
411
- * all, so a provider that declares support may still have individual models its own
412
- * API rejects thinking on. (`adaptiveThinkingModelPrefixes` is per-model but selects
413
- * a wire *shape*, not availability.) What the tier axis guarantees is therefore
414
- * narrow and exact: a tier selects a model within one provider and never changes the
415
- * provider, so it never changes `thinkingMode`.
147
+ * provider supports thinking, or that every model of a thinking-capable provider
148
+ * does: the descriptor itself declares no thinking-availability field at all.
149
+ * `AiModelCapability`'s `'thinking'` entry (per-model, RegExp-matched on model id
150
+ * in `DEFAULT_MODEL_CAPABILITY_CONFIG`) is a listing/filtering signal only — the
151
+ * call path does not gate a thinking request on it, so an unlisted model is not
152
+ * rejected, merely absent from a capability-filtered menu. (`adaptiveThinkingModelPrefixes`
153
+ * is per-model but selects a wire *shape*, not availability.) What the tier axis
154
+ * guarantees is therefore narrow and exact: a tier selects a model within one
155
+ * provider and never changes the provider.
416
156
  *
417
157
  * Do not add a `'tools'` or `'thinking'` key here, and do not hand-roll a
418
158
  * `resolveModel` + `resolveModelAlias` walk to emulate one — call
@@ -694,6 +434,8 @@ export interface IAiCompletionResponse {
694
434
  * split.
695
435
  */
696
436
  readonly structuredOutput: StructuredOutputEnforcement;
437
+ /** Token usage, when the provider reports it. */
438
+ readonly usage?: IAiCompletionUsage;
697
439
  }
698
440
  /**
699
441
  * Default `max_tokens` sent to the Anthropic Messages API when the caller does
@@ -764,6 +506,8 @@ export interface IAiStreamDone {
764
506
  * reports truncation without a reason).
765
507
  */
766
508
  readonly incompleteReason?: string;
509
+ /** Token usage, when the provider reports it on this stream. */
510
+ readonly usage?: IAiCompletionUsage;
767
511
  }
768
512
  /**
769
513
  * Terminal failure event for a streaming completion. After this event no
@@ -792,11 +536,6 @@ export interface IAiStreamError {
792
536
  * @public
793
537
  */
794
538
  export type IAiStreamEvent = IAiStreamTextDelta | IAiStreamToolEvent | IAiStreamToolUseStart | IAiStreamToolUseDelta | IAiStreamToolUseComplete | IAiStreamDone | IAiStreamError;
795
- /**
796
- * Thinking/reasoning mode support for a provider.
797
- * @public
798
- */
799
- export type AiThinkingMode = 'optional' | 'required' | 'unsupported';
800
539
  /**
801
540
  * Describes a single AI provider — single source of truth for all metadata.
802
541
  * @public
@@ -831,6 +570,29 @@ export interface IAiProviderDescriptor {
831
570
  readonly aliases?: IModelAliasMap;
832
571
  /** Which server-side tools this provider supports (empty = none). */
833
572
  readonly supportedTools: ReadonlyArray<AiServerToolType>;
573
+ /**
574
+ * Server tools this provider's API refuses to accept in the *same request* as
575
+ * client (function) tools. Absent or empty means the provider imposes no such
576
+ * constraint and any supported server tool may be mixed with client tools.
577
+ *
578
+ * @remarks
579
+ * This is a narrower statement than {@link AiAssist.IAiProviderDescriptor.supportedTools}:
580
+ * a tool listed here is genuinely supported, just not *together* with function
581
+ * calling. Only Gemini declares anything today — its `generateContent` API
582
+ * HTTP-400s (`INVALID_ARGUMENT`) when built-in grounding (`web_search` →
583
+ * `google_search`) and `function_declarations` appear in one request.
584
+ *
585
+ * Declaring the rule here rather than enforcing it at the call site is the
586
+ * point: {@link AiAssist.resolveToolConflicts} applies it generically, so a host
587
+ * never writes `if (descriptor.apiFormat === 'gemini')` in its tool assembly,
588
+ * and the day a provider lifts its limit only this line changes.
589
+ *
590
+ * Optional because most providers have nothing to say. The library's own
591
+ * registry descriptors are the ones that reach the wire and are pinned by test;
592
+ * a hand-built descriptor that omits this simply gets the unconstrained
593
+ * behavior, which is the correct reading of "declares no constraint".
594
+ */
595
+ readonly serverToolsExclusiveWithClientTools?: ReadonlyArray<AiServerToolType>;
834
596
  /** Whether this provider's API enforces CORS restrictions that prevent direct browser calls. */
835
597
  readonly corsRestricted: boolean;
836
598
  /**
@@ -850,13 +612,6 @@ export interface IAiProviderDescriptor {
850
612
  * `prompt.attachments` are rejected up front.
851
613
  */
852
614
  readonly acceptsImageInput: boolean;
853
- /**
854
- * Whether this provider supports thinking/reasoning mode.
855
- * - 'optional': thinking can be enabled but is not required
856
- * - 'required': thinking is always active (e.g. o-series models)
857
- * - 'unsupported': thinking is not supported
858
- */
859
- readonly thinkingMode: AiThinkingMode;
860
615
  /**
861
616
  * Image-generation capabilities, scoped to model id prefixes. Empty or
862
617
  * undefined means the provider does not support image generation.
@@ -1382,11 +1137,25 @@ export type XAiThinkingModelNames = 'grok-3-mini' | 'grok-4.3' | 'grok-4' | 'gro
1382
1137
  */
1383
1138
  export interface IAnthropicThinkingConfig {
1384
1139
  /**
1385
- * Anthropic effort level. The emit-site converts to `thinking.budget_tokens`
1386
- * (the integer budget the Anthropic API requires). Mapping policy: low = 2048,
1387
- * medium = 8192, high = 24000, max = 32000.
1388
- * - 'low' | 'medium' | 'high': all thinking-capable models
1389
- * - 'max': Opus 4.6 only
1140
+ * Anthropic effort level, emitted as one of **two** wire shapes chosen by
1141
+ * {@link AiAssist.isAdaptiveThinkingModel}:
1142
+ *
1143
+ * - **Claude 5 family** (`claude-sonnet-5`, `claude-opus-5`, `claude-fable-5`
1144
+ * — which includes the `base` and `advanced` tiers, so this is the default
1145
+ * path): an adaptive `thinking` block plus an `output_config` block
1146
+ * carrying `effort`. The effort string goes on the wire verbatim and
1147
+ * **no token budget is sent**.
1148
+ * - **Older thinking-capable models**: an enabled `thinking` block carrying
1149
+ * `budget_tokens`, converted by `anthropicEffortToBudgetTokens` — low =
1150
+ * 2048, medium = 8192, high = 24000, max = 32000.
1151
+ *
1152
+ * So the budget mapping is not a description of what a default Anthropic
1153
+ * call sends; size a budget from it only when you have pinned a pre-Claude-5
1154
+ * model.
1155
+ *
1156
+ * `'max'` is accepted on every thinking-capable model here — the library
1157
+ * applies no model restriction of its own, and whether a given model accepts
1158
+ * it is the provider's to enforce.
1390
1159
  */
1391
1160
  readonly effort?: 'low' | 'medium' | 'high' | 'max';
1392
1161
  }
@@ -1428,8 +1197,9 @@ export interface IGeminiThinkingConfig {
1428
1197
  /**
1429
1198
  * Whether to include thought summaries in the response.
1430
1199
  * @remarks
1431
- * INERT in phase B. Adapters never send `includeThoughts: true`.
1432
- * Wired up by the followup stream `ai-assist-thinking-events`.
1200
+ * Reserved for forward compatibility and **currently ignored by every
1201
+ * adapter** — nothing reads this field, so setting it has no effect on the
1202
+ * request. Surfacing thinking output as stream events is not yet built.
1433
1203
  */
1434
1204
  readonly includeThoughts?: boolean;
1435
1205
  }
@@ -1513,11 +1283,27 @@ export type IThinkingProviderConfig = IAnthropicThinkingOptions | IOpenAiThinkin
1513
1283
  export interface IThinkingConfig {
1514
1284
  /**
1515
1285
  * Cross-provider effort level. Common-subset mapping:
1286
+ * - 'none': Anthropic — no thinking param emitted | OpenAI effort:none | Gemini thinkingBudget:0 | xAI reasoning_effort:none
1516
1287
  * - 'low': Anthropic effort:low | OpenAI effort:low | Gemini thinkingBudget:1024 | xAI reasoning_effort:low
1517
- * - 'medium': effort:medium | effort:medium | thinkingBudget:4096 | reasoning_effort:medium
1518
- * - 'high': effort:high | effort:high | thinkingBudget:8192 | reasoning_effort:high
1288
+ * - 'medium': Anthropic effort:medium | OpenAI effort:medium | Gemini thinkingBudget:4096 | xAI reasoning_effort:medium
1289
+ * - 'high': Anthropic effort:high | OpenAI effort:high | Gemini thinkingBudget:8192 | xAI reasoning_effort:high
1290
+ *
1291
+ * @remarks
1292
+ * `'none'` is the one cross-provider spelling for "thinking off". Anthropic has no
1293
+ * off value in its own effort vocabulary — off there means omitting the `thinking`
1294
+ * wire param entirely — so `'none'` maps to that omission rather than to a value.
1295
+ * Whichever provider is in play, `'none'` also re-enables `temperature`: see
1296
+ * `checkTemperatureConflict` in `thinkingOptionsResolver.ts`.
1297
+ *
1298
+ * The mapping is not model-aware (same posture as every other entry in this table —
1299
+ * see `ModelSpecKey`'s remarks for why thinking availability isn't gated at the call
1300
+ * path). For Gemini specifically, `thinkingBudget: 0` is documented as valid only on
1301
+ * Flash and Flash-Lite and erroring on Pro (see `IGeminiThinkingConfig.thinkingBudget`);
1302
+ * `'none'` on a Pro-family model inherits that same caveat, exactly as an explicit
1303
+ * `providers: [{ provider: 'google', config: { thinkingBudget: 0 } }]` block already did
1304
+ * before this field existed.
1519
1305
  */
1520
- readonly effort?: 'low' | 'medium' | 'high';
1306
+ readonly effort?: 'none' | 'low' | 'medium' | 'high';
1521
1307
  /**
1522
1308
  * Optional per-provider precision blocks. Blocks for providers that don't
1523
1309
  * match the resolved model's provider are silently skipped.