@fgv/ts-extras 5.1.0-4 → 5.1.0-40

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 (368) hide show
  1. package/dist/index.browser.js +4 -2
  2. package/dist/index.browser.js.map +1 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/packlets/ai-assist/apiClient.js +886 -158
  5. package/dist/packlets/ai-assist/apiClient.js.map +1 -0
  6. package/dist/packlets/ai-assist/chatRequestBuilders.js +282 -0
  7. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  8. package/dist/packlets/ai-assist/converters.js +47 -3
  9. package/dist/packlets/ai-assist/converters.js.map +1 -0
  10. package/dist/packlets/ai-assist/embeddingClient.js +345 -0
  11. package/dist/packlets/ai-assist/embeddingClient.js.map +1 -0
  12. package/dist/packlets/ai-assist/endpoint.js +78 -0
  13. package/dist/packlets/ai-assist/endpoint.js.map +1 -0
  14. package/dist/packlets/ai-assist/http.js +75 -0
  15. package/dist/packlets/ai-assist/http.js.map +1 -0
  16. package/dist/packlets/ai-assist/imageOptionsResolver.js +193 -0
  17. package/dist/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  18. package/dist/packlets/ai-assist/index.js +10 -4
  19. package/dist/packlets/ai-assist/index.js.map +1 -0
  20. package/dist/packlets/ai-assist/jsonCompletion.js +93 -0
  21. package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -0
  22. package/dist/packlets/ai-assist/jsonResponse.js +149 -0
  23. package/dist/packlets/ai-assist/jsonResponse.js.map +1 -0
  24. package/dist/packlets/ai-assist/model.js +193 -9
  25. package/dist/packlets/ai-assist/model.js.map +1 -0
  26. package/dist/packlets/ai-assist/registry.js +314 -12
  27. package/dist/packlets/ai-assist/registry.js.map +1 -0
  28. package/dist/packlets/ai-assist/sseParser.js +123 -0
  29. package/dist/packlets/ai-assist/sseParser.js.map +1 -0
  30. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +368 -0
  31. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  32. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +687 -0
  33. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
  34. package/dist/packlets/ai-assist/streamingAdapters/common.js +187 -0
  35. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  36. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +204 -0
  37. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  38. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +170 -0
  39. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  40. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +386 -0
  41. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  42. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +173 -0
  43. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  44. package/dist/packlets/ai-assist/streamingClient.js +140 -0
  45. package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
  46. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +288 -0
  47. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  48. package/dist/packlets/ai-assist/toolFormats.js +106 -10
  49. package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
  50. package/dist/packlets/conversion/converters.js +35 -1
  51. package/dist/packlets/conversion/converters.js.map +1 -0
  52. package/dist/packlets/conversion/index.js.map +1 -0
  53. package/dist/packlets/crypto-utils/constants.js.map +1 -0
  54. package/dist/packlets/crypto-utils/converters.js +42 -4
  55. package/dist/packlets/crypto-utils/converters.js.map +1 -0
  56. package/dist/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  57. package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -0
  58. package/dist/packlets/crypto-utils/hpkeProvider.js +333 -0
  59. package/dist/packlets/crypto-utils/hpkeProvider.js.map +1 -0
  60. package/dist/packlets/crypto-utils/index.browser.js +10 -2
  61. package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
  62. package/dist/packlets/crypto-utils/index.js +6 -0
  63. package/dist/packlets/crypto-utils/index.js.map +1 -0
  64. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +71 -0
  65. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  66. package/dist/packlets/crypto-utils/keystore/converters.js +103 -11
  67. package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
  68. package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +287 -0
  69. package/dist/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
  70. package/dist/packlets/crypto-utils/keystore/index.browser.js +36 -0
  71. package/dist/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
  72. package/dist/packlets/crypto-utils/keystore/index.js +3 -0
  73. package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
  74. package/dist/packlets/crypto-utils/keystore/keyStore.js +633 -118
  75. package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  76. package/dist/packlets/crypto-utils/keystore/model.js +22 -1
  77. package/dist/packlets/crypto-utils/keystore/model.js.map +1 -0
  78. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
  79. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  80. package/dist/packlets/crypto-utils/model.js +32 -0
  81. package/dist/packlets/crypto-utils/model.js.map +1 -0
  82. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +270 -1
  83. package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  84. package/dist/packlets/crypto-utils/spkiHelpers.js +209 -0
  85. package/dist/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  86. package/dist/packlets/csv/csvFileHelpers.js +0 -14
  87. package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
  88. package/dist/packlets/csv/csvHelpers.js +14 -0
  89. package/dist/packlets/csv/csvHelpers.js.map +1 -0
  90. package/dist/packlets/csv/index.browser.js +1 -3
  91. package/dist/packlets/csv/index.browser.js.map +1 -0
  92. package/dist/packlets/csv/index.js.map +1 -0
  93. package/dist/packlets/experimental/extendedArray.js.map +1 -0
  94. package/dist/packlets/experimental/formatter.js.map +1 -0
  95. package/dist/packlets/experimental/index.js.map +1 -0
  96. package/dist/packlets/experimental/rangeOf.js.map +1 -0
  97. package/dist/packlets/hash/index.browser.js.map +1 -0
  98. package/dist/packlets/hash/index.js.map +1 -0
  99. package/dist/packlets/hash/index.node.js.map +1 -0
  100. package/dist/packlets/hash/md5Normalizer.browser.js.map +1 -0
  101. package/dist/packlets/hash/md5Normalizer.js.map +1 -0
  102. package/dist/packlets/mustache/index.js.map +1 -0
  103. package/dist/packlets/mustache/interfaces.js.map +1 -0
  104. package/dist/packlets/mustache/mustacheTemplate.js +42 -4
  105. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -0
  106. package/dist/packlets/record-jar/index.browser.js +1 -3
  107. package/dist/packlets/record-jar/index.browser.js.map +1 -0
  108. package/dist/packlets/record-jar/index.js.map +1 -0
  109. package/dist/packlets/record-jar/recordJarFileHelpers.js +0 -18
  110. package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  111. package/dist/packlets/record-jar/recordJarHelpers.js +18 -0
  112. package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -0
  113. package/dist/packlets/yaml/converters.js.map +1 -0
  114. package/dist/packlets/yaml/index.js +1 -0
  115. package/dist/packlets/yaml/index.js.map +1 -0
  116. package/dist/packlets/yaml/serializers.js +48 -0
  117. package/dist/packlets/yaml/serializers.js.map +1 -0
  118. package/dist/packlets/zip-file-tree/index.js.map +1 -0
  119. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  120. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  121. package/dist/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  122. package/dist/ts-extras.d.ts +3880 -105
  123. package/dist/tsdoc-metadata.json +1 -1
  124. package/lib/index.browser.d.ts +4 -2
  125. package/lib/index.browser.d.ts.map +1 -0
  126. package/lib/index.browser.js +8 -3
  127. package/lib/index.browser.js.map +1 -0
  128. package/lib/index.d.ts.map +1 -0
  129. package/lib/index.js.map +1 -0
  130. package/lib/packlets/ai-assist/apiClient.d.ts +115 -32
  131. package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
  132. package/lib/packlets/ai-assist/apiClient.js +888 -156
  133. package/lib/packlets/ai-assist/apiClient.js.map +1 -0
  134. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +149 -0
  135. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
  136. package/lib/packlets/ai-assist/chatRequestBuilders.js +293 -0
  137. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  138. package/lib/packlets/ai-assist/converters.d.ts +15 -1
  139. package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
  140. package/lib/packlets/ai-assist/converters.js +47 -3
  141. package/lib/packlets/ai-assist/converters.js.map +1 -0
  142. package/lib/packlets/ai-assist/embeddingClient.d.ts +69 -0
  143. package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -0
  144. package/lib/packlets/ai-assist/embeddingClient.js +349 -0
  145. package/lib/packlets/ai-assist/embeddingClient.js.map +1 -0
  146. package/lib/packlets/ai-assist/endpoint.d.ts +28 -0
  147. package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -0
  148. package/lib/packlets/ai-assist/endpoint.js +82 -0
  149. package/lib/packlets/ai-assist/endpoint.js.map +1 -0
  150. package/lib/packlets/ai-assist/http.d.ts +24 -0
  151. package/lib/packlets/ai-assist/http.d.ts.map +1 -0
  152. package/lib/packlets/ai-assist/http.js +78 -0
  153. package/lib/packlets/ai-assist/http.js.map +1 -0
  154. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts +66 -0
  155. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts.map +1 -0
  156. package/lib/packlets/ai-assist/imageOptionsResolver.js +197 -0
  157. package/lib/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  158. package/lib/packlets/ai-assist/index.d.ts +10 -4
  159. package/lib/packlets/ai-assist/index.d.ts.map +1 -0
  160. package/lib/packlets/ai-assist/index.js +36 -1
  161. package/lib/packlets/ai-assist/index.js.map +1 -0
  162. package/lib/packlets/ai-assist/jsonCompletion.d.ts +93 -0
  163. package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -0
  164. package/lib/packlets/ai-assist/jsonCompletion.js +97 -0
  165. package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -0
  166. package/lib/packlets/ai-assist/jsonResponse.d.ts +91 -0
  167. package/lib/packlets/ai-assist/jsonResponse.d.ts.map +1 -0
  168. package/lib/packlets/ai-assist/jsonResponse.js +154 -0
  169. package/lib/packlets/ai-assist/jsonResponse.js.map +1 -0
  170. package/lib/packlets/ai-assist/model.d.ts +1202 -12
  171. package/lib/packlets/ai-assist/model.d.ts.map +1 -0
  172. package/lib/packlets/ai-assist/model.js +198 -10
  173. package/lib/packlets/ai-assist/model.js.map +1 -0
  174. package/lib/packlets/ai-assist/registry.d.ts +56 -1
  175. package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
  176. package/lib/packlets/ai-assist/registry.js +319 -13
  177. package/lib/packlets/ai-assist/registry.js.map +1 -0
  178. package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
  179. package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -0
  180. package/lib/packlets/ai-assist/sseParser.js +128 -0
  181. package/lib/packlets/ai-assist/sseParser.js.map +1 -0
  182. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +72 -0
  183. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
  184. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +371 -0
  185. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  186. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +260 -0
  187. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -0
  188. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +694 -0
  189. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -0
  190. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +154 -0
  191. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
  192. package/lib/packlets/ai-assist/streamingAdapters/common.js +193 -0
  193. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  194. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +43 -0
  195. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
  196. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +207 -0
  197. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  198. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +19 -0
  199. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
  200. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +173 -0
  201. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  202. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +33 -0
  203. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
  204. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +389 -0
  205. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  206. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
  207. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -0
  208. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +176 -0
  209. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  210. package/lib/packlets/ai-assist/streamingClient.d.ts +50 -0
  211. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
  212. package/lib/packlets/ai-assist/streamingClient.js +146 -0
  213. package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
  214. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +87 -0
  215. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -0
  216. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +294 -0
  217. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  218. package/lib/packlets/ai-assist/toolFormats.d.ts +40 -9
  219. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
  220. package/lib/packlets/ai-assist/toolFormats.js +107 -10
  221. package/lib/packlets/ai-assist/toolFormats.js.map +1 -0
  222. package/lib/packlets/conversion/converters.d.ts +8 -1
  223. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  224. package/lib/packlets/conversion/converters.js +36 -2
  225. package/lib/packlets/conversion/converters.js.map +1 -0
  226. package/lib/packlets/conversion/index.d.ts.map +1 -0
  227. package/lib/packlets/conversion/index.js.map +1 -0
  228. package/lib/packlets/crypto-utils/constants.d.ts.map +1 -0
  229. package/lib/packlets/crypto-utils/constants.js.map +1 -0
  230. package/lib/packlets/crypto-utils/converters.d.ts +20 -1
  231. package/lib/packlets/crypto-utils/converters.d.ts.map +1 -0
  232. package/lib/packlets/crypto-utils/converters.js +43 -5
  233. package/lib/packlets/crypto-utils/converters.js.map +1 -0
  234. package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts.map +1 -0
  235. package/lib/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  236. package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -0
  237. package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -0
  238. package/lib/packlets/crypto-utils/hpkeProvider.d.ts +142 -0
  239. package/lib/packlets/crypto-utils/hpkeProvider.d.ts.map +1 -0
  240. package/lib/packlets/crypto-utils/hpkeProvider.js +337 -0
  241. package/lib/packlets/crypto-utils/hpkeProvider.js.map +1 -0
  242. package/lib/packlets/crypto-utils/index.browser.d.ts +4 -1
  243. package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
  244. package/lib/packlets/crypto-utils/index.browser.js +21 -3
  245. package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
  246. package/lib/packlets/crypto-utils/index.d.ts +3 -0
  247. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  248. package/lib/packlets/crypto-utils/index.js +17 -1
  249. package/lib/packlets/crypto-utils/index.js.map +1 -0
  250. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +54 -0
  251. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
  252. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +74 -0
  253. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  254. package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
  255. package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -0
  256. package/lib/packlets/crypto-utils/keystore/converters.js +101 -9
  257. package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
  258. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts +148 -0
  259. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.d.ts.map +1 -0
  260. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js +324 -0
  261. package/lib/packlets/crypto-utils/keystore/encryptedFilePrivateKeyStorage.js.map +1 -0
  262. package/lib/packlets/crypto-utils/keystore/index.browser.d.ts +10 -0
  263. package/lib/packlets/crypto-utils/keystore/index.browser.d.ts.map +1 -0
  264. package/lib/packlets/crypto-utils/keystore/index.browser.js +76 -0
  265. package/lib/packlets/crypto-utils/keystore/index.browser.js.map +1 -0
  266. package/lib/packlets/crypto-utils/keystore/index.d.ts +2 -0
  267. package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
  268. package/lib/packlets/crypto-utils/keystore/index.js +5 -1
  269. package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
  270. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +205 -13
  271. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
  272. package/lib/packlets/crypto-utils/keystore/keyStore.js +639 -124
  273. package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  274. package/lib/packlets/crypto-utils/keystore/model.d.ts +275 -19
  275. package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -0
  276. package/lib/packlets/crypto-utils/keystore/model.js +24 -2
  277. package/lib/packlets/crypto-utils/keystore/model.js.map +1 -0
  278. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +53 -0
  279. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts.map +1 -0
  280. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
  281. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  282. package/lib/packlets/crypto-utils/model.d.ts +348 -10
  283. package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
  284. package/lib/packlets/crypto-utils/model.js +33 -1
  285. package/lib/packlets/crypto-utils/model.js.map +1 -0
  286. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +110 -2
  287. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
  288. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +269 -0
  289. package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  290. package/lib/packlets/crypto-utils/spkiHelpers.d.ts +110 -0
  291. package/lib/packlets/crypto-utils/spkiHelpers.d.ts.map +1 -0
  292. package/lib/packlets/crypto-utils/spkiHelpers.js +219 -0
  293. package/lib/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  294. package/lib/packlets/csv/csvFileHelpers.d.ts +0 -10
  295. package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
  296. package/lib/packlets/csv/csvFileHelpers.js +0 -15
  297. package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
  298. package/lib/packlets/csv/csvHelpers.d.ts +10 -0
  299. package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
  300. package/lib/packlets/csv/csvHelpers.js +15 -0
  301. package/lib/packlets/csv/csvHelpers.js.map +1 -0
  302. package/lib/packlets/csv/index.browser.d.ts +0 -1
  303. package/lib/packlets/csv/index.browser.d.ts.map +1 -0
  304. package/lib/packlets/csv/index.browser.js +1 -5
  305. package/lib/packlets/csv/index.browser.js.map +1 -0
  306. package/lib/packlets/csv/index.d.ts.map +1 -0
  307. package/lib/packlets/csv/index.js.map +1 -0
  308. package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
  309. package/lib/packlets/experimental/extendedArray.js.map +1 -0
  310. package/lib/packlets/experimental/formatter.d.ts.map +1 -0
  311. package/lib/packlets/experimental/formatter.js.map +1 -0
  312. package/lib/packlets/experimental/index.d.ts.map +1 -0
  313. package/lib/packlets/experimental/index.js.map +1 -0
  314. package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
  315. package/lib/packlets/experimental/rangeOf.js.map +1 -0
  316. package/lib/packlets/hash/index.browser.d.ts.map +1 -0
  317. package/lib/packlets/hash/index.browser.js.map +1 -0
  318. package/lib/packlets/hash/index.d.ts.map +1 -0
  319. package/lib/packlets/hash/index.js.map +1 -0
  320. package/lib/packlets/hash/index.node.d.ts.map +1 -0
  321. package/lib/packlets/hash/index.node.js.map +1 -0
  322. package/lib/packlets/hash/md5Normalizer.browser.d.ts.map +1 -0
  323. package/lib/packlets/hash/md5Normalizer.browser.js.map +1 -0
  324. package/lib/packlets/hash/md5Normalizer.d.ts.map +1 -0
  325. package/lib/packlets/hash/md5Normalizer.js.map +1 -0
  326. package/lib/packlets/mustache/index.d.ts +1 -1
  327. package/lib/packlets/mustache/index.d.ts.map +1 -0
  328. package/lib/packlets/mustache/index.js.map +1 -0
  329. package/lib/packlets/mustache/interfaces.d.ts +34 -0
  330. package/lib/packlets/mustache/interfaces.d.ts.map +1 -0
  331. package/lib/packlets/mustache/interfaces.js.map +1 -0
  332. package/lib/packlets/mustache/mustacheTemplate.d.ts +2 -0
  333. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -0
  334. package/lib/packlets/mustache/mustacheTemplate.js +42 -4
  335. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
  336. package/lib/packlets/record-jar/index.browser.d.ts +0 -1
  337. package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
  338. package/lib/packlets/record-jar/index.browser.js +1 -5
  339. package/lib/packlets/record-jar/index.browser.js.map +1 -0
  340. package/lib/packlets/record-jar/index.d.ts.map +1 -0
  341. package/lib/packlets/record-jar/index.js.map +1 -0
  342. package/lib/packlets/record-jar/recordJarFileHelpers.d.ts +0 -11
  343. package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -0
  344. package/lib/packlets/record-jar/recordJarFileHelpers.js +0 -19
  345. package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  346. package/lib/packlets/record-jar/recordJarHelpers.d.ts +11 -0
  347. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
  348. package/lib/packlets/record-jar/recordJarHelpers.js +19 -0
  349. package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
  350. package/lib/packlets/yaml/converters.d.ts.map +1 -0
  351. package/lib/packlets/yaml/converters.js.map +1 -0
  352. package/lib/packlets/yaml/index.d.ts +1 -0
  353. package/lib/packlets/yaml/index.d.ts.map +1 -0
  354. package/lib/packlets/yaml/index.js +1 -0
  355. package/lib/packlets/yaml/index.js.map +1 -0
  356. package/lib/packlets/yaml/serializers.d.ts +45 -0
  357. package/lib/packlets/yaml/serializers.d.ts.map +1 -0
  358. package/lib/packlets/yaml/serializers.js +84 -0
  359. package/lib/packlets/yaml/serializers.js.map +1 -0
  360. package/lib/packlets/zip-file-tree/index.d.ts.map +1 -0
  361. package/lib/packlets/zip-file-tree/index.js.map +1 -0
  362. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
  363. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -0
  364. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  365. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  366. package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts.map +1 -0
  367. package/lib/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  368. package/package.json +20 -15
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clientToolContinuationBuilder.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.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;;;;;;;;;;;;;;;;;;;;;;AAuGZ,gEAmHC;AAuBD,0DA+DC;AAuBD,0DAiDC;AAwJD,sDAKC;AAuBD,sDAmYC;AA76BD;;;;;;;;;;;;;;;;GAgBG;AAEH,4CAAwF;AAGxF,oCAUkB;AAElB,gEAA0D;AAC1D,0CAAsD;AAItD,2CAAkD;AAClD,uDAA8D;AAC9D,qCAA4C;AAmB5C,+EAA+E;AAC/E,iCAAiC;AACjC,+EAA+E;AAE/E;;;;;;;;;GASG;AACH,SAAS,UAAU,CAAC,EAAsB;IACxC,OAAO,EAAE,KAAK,SAAS,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAgB,0BAA0B,CACxC,SAAyC,E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E5C,mFAAmF;YACnF,gFAAgF;YAChF,8EAA8E;YAC9E,4EAA4E;YAC5E,oEAAoE;YACpE,IAAI,oBAAoB,IAAI,oBAAoB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC5D,YAAY,mCAAQ,YAAY,KAAE,QAAQ,EAAE,CAAC,GAAG,oBAAoB,EAAE,GAAG,YAAY,CAAC,QAAQ,CAAC,GAAE,CAAC;YACpG,CAAC;YAED,eAAe,CAAC,IAAA,kBAAO,EAAC,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;QAClE,CAAC;KAAA;IAED,OAAO,IAAA,kBAAO,EAAC;QACb,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC,cAAc,EAAE,EAAE;QAC1D,QAAQ;KACT,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Per-provider continuation message builders and the `executeClientToolTurn`\n * helper for orchestrating a single client-tool round-trip.\n *\n * Each provider requires a different wire format for the follow-up request:\n * - **Anthropic**: assistant turn reconstructed from the ordered accumulation\n * buffer (thinking / redacted_thinking / text / tool_use in original stream\n * order) + user turn with `tool_result` blocks. When thinking is active, the\n * follow-up request must NOT set `tool_choice: { type: 'any' }` or\n * `tool_choice: { type: 'tool', ... }` (E3 / §5.4 of b4-spike-findings).\n * - **OpenAI / xAI Responses API**: `function_call` input items +\n * `function_call_output` input items.\n * - **Gemini**: model turn with `functionCall` parts + user turn with\n * `functionResponse` parts (correlation by tool name).\n *\n * @packageDocumentation\n */\n\nimport { captureAsyncResult, fail, type Logging, Result, succeed } from '@fgv/ts-utils';\nimport { type JsonArray, type JsonObject } from '@fgv/ts-json-base';\n\nimport {\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiClientTool,\n type IAiClientToolContinuation,\n type IAiClientToolTurnResult,\n type IAiStreamEvent,\n type IChatRequest,\n type IAiProviderDescriptor,\n resolveProviderModel\n} from '../model';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { splitChatRequest } from '../chatRequestBuilders';\nimport { resolveEffectiveBaseUrl } from '../endpoint';\nimport { type IAccumulatedBlock } from './anthropic';\nimport { type IAccumulatedFunctionCall } from './openaiResponses';\nimport { type IAccumulatedGeminiFunctionCall } from './gemini';\nimport { callAnthropicStream } from './anthropic';\nimport { callOpenAiResponsesStream } from './openaiResponses';\nimport { callGeminiStream } from './gemini';\nimport { type IStreamApiConfig } from './common';\n\n// ============================================================================\n// Tool-result accumulation (internal)\n// ============================================================================\n\n/**\n * Accumulated result for a single tool call, collected during stream iteration.\n * @internal\n */\ninterface IToolCallResult {\n readonly toolName: string;\n readonly callId?: string;\n readonly args: JsonObject;\n readonly result: string;\n readonly isError: boolean;\n}\n\n// ============================================================================\n// Anthropic continuation builder\n// ============================================================================\n\n/**\n * Returns `true` when `id` is a usable correlation id — present and non-empty.\n *\n * `??` is NOT sufficient for this check: an empty string is a *bad* id (a\n * `tool_use_id: ''` is rejected by Anthropic as a \"malformed identifier\") but\n * `'' ?? fallback` yields `''`, silently passing the empty id through. Every id\n * correlation in this module must use this predicate, never `??`.\n *\n * @internal\n */\nfunction isUsableId(id: string | undefined): id is string {\n return id !== undefined && id.length > 0;\n}\n\n/**\n * Builds the Anthropic follow-up messages for a client-tool round-trip.\n *\n * Reconstructs the assistant turn from the ordered accumulation buffer\n * (all block types in original stream order) and appends a user turn\n * with `tool_result` blocks for each executed tool call.\n *\n * **Single source of truth for the id (id-correlation fix).** Each\n * `tool_result.tool_use_id` is drawn from — and validated against — the set of\n * assistant `tool_use.id`s actually present in the accumulation buffer. The id\n * is NEVER derived from the tool name: a tool name can never match a `toolu_*`\n * id, so a name fallback produces exactly the \"malformed identifier\" the\n * provider rejects. If any tool result cannot be correlated to a buffered\n * `tool_use` block with a non-empty id, the build fails loud (naming the tool)\n * rather than emitting a malformed continuation.\n *\n * **Constraint (E3):** The returned continuation does NOT include a forced\n * `tool_choice` field. When thinking is active, Anthropic rejects\n * `tool_choice: { type: 'any' }` and `tool_choice: { type: 'tool', ... }`\n * with an HTTP 400 error. Only `tool_choice: { type: 'auto' }` (the default,\n * i.e. omitted) is compatible with extended thinking.\n *\n * @internal\n */\nexport function buildAnthropicContinuation(\n accBuffer: Map<number, IAccumulatedBlock>,\n toolResults: IToolCallResult[],\n logger?: Logging.ILogger\n): Result<IAiClientToolContinuation> {\n // Reconstruct the assistant turn from the ordered accumulation buffer.\n // Sort by buffer key (SSE index) to restore original stream order.\n const sortedKeys = Array.from(accBuffer.keys()).sort((a, b) => a - b);\n const assistantContent: JsonArray = [];\n // The set of assistant tool_use ids — the single source of truth every\n // tool_result.tool_use_id must be drawn from.\n const bufferedToolUseIds = new Set<string>();\n\n for (const key of sortedKeys) {\n const block = accBuffer.get(key);\n /* c8 ignore next 1 - defensive: key always exists in map since we iterate its keys */\n if (!block) continue;\n if (block.type === 'thinking') {\n assistantContent.push({\n type: 'thinking',\n thinking: block.thinking,\n signature: block.signature\n });\n } else if (block.type === 'redacted_thinking') {\n assistantContent.push({\n type: 'redacted_thinking',\n data: block.data\n });\n } else if (block.type === 'text') {\n if (block.text.length > 0) {\n assistantContent.push({ type: 'text', text: block.text });\n }\n } else if (block.type === 'tool_use') {\n // A buffered tool_use with an empty id can never be referenced by a valid\n // tool_result; emitting it would corrupt the assistant turn. Fail loud.\n if (!isUsableId(block.id)) {\n return fail(\n `Anthropic continuation: buffered tool_use block for tool '${block.name}' has an empty id; ` +\n `cannot build a valid continuation`\n );\n }\n let parsedInput: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer is JSON-parsed in the adapter before emitting client-tool-call-done */\n parsedInput = JSON.parse(block.argsBuffer || '{}') as JsonObject;\n /* c8 ignore start - defensive: malformed argsBuffer defaults to empty object */\n } catch {\n parsedInput = {};\n }\n /* c8 ignore stop */\n bufferedToolUseIds.add(block.id);\n assistantContent.push({\n type: 'tool_use',\n id: block.id,\n name: block.name,\n input: parsedInput\n });\n }\n }\n\n // Build user turn with tool_result blocks for each tool call. Correlate each\n // result to a buffered tool_use id — the SAME id that keys the assistant\n // tool_use block — and fail loud on a missing / empty / mismatched id. A\n // missing callId is a bug to surface, not paper over with a name fallback.\n const userContent: JsonArray = [];\n for (const r of toolResults) {\n if (!isUsableId(r.callId)) {\n return fail(\n `Anthropic continuation: tool '${r.toolName}' result has no call id (missing or empty); ` +\n `cannot correlate it to an assistant tool_use block`\n );\n }\n if (!bufferedToolUseIds.has(r.callId)) {\n return fail(\n `Anthropic continuation: tool '${r.toolName}' call id '${r.callId}' does not match any ` +\n `buffered assistant tool_use block id`\n );\n }\n const block: JsonObject = {\n type: 'tool_result',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tool_use_id: r.callId,\n content: r.result\n };\n userContent.push(r.isError ? { ...block, is_error: true } : block);\n }\n\n // Decisive diagnostic: the tool_use.id ↔ tool_result.tool_use_id pairing for\n // the outgoing continuation. A failing turn is field-confirmable by capturing\n // this line (the pairing is by construction matched here — divergence fails\n // loud above, before reaching this point).\n if (logger) {\n const pairing = toolResults.map((r) => `${r.toolName}:${r.callId}`).join(', ');\n logger.detail(`ai-assist:anthropic-continuation tool_use.id↔tool_result.tool_use_id [${pairing}]`);\n }\n\n const assistantMessage: JsonObject = {\n role: 'assistant',\n content: assistantContent\n };\n const userMessage: JsonObject = {\n role: 'user',\n content: userContent\n };\n\n return succeed({\n messages: [assistantMessage, userMessage],\n toolCallsSummary: toolResults.map((r) => ({\n toolName: r.toolName,\n callId: r.callId,\n args: r.args,\n result: r.result,\n isError: r.isError\n }))\n });\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API continuation builder\n// ============================================================================\n\n/**\n * Builds the OpenAI / xAI Responses API follow-up input items for a\n * client-tool round-trip.\n *\n * Emits `function_call` items (the model's call) followed by\n * `function_call_output` items (the harness execution result), one pair\n * per executed tool call.\n *\n * **Single source of truth for the id (id-correlation fix).** Each\n * `function_call_output.call_id` is drawn from — and validated against — the\n * set of `function_call.call_id`s in the accumulation map. It is NEVER derived\n * from the tool name (the OpenAI parity of the Anthropic `tool_use_id` fix). A\n * missing / empty / unmatched call id fails the build loud rather than emitting\n * a continuation the provider would reject.\n *\n * @internal\n */\nexport function buildOpenAiContinuation(\n calls: Map<string, IAccumulatedFunctionCall>,\n toolResults: IToolCallResult[],\n logger?: Logging.ILogger\n): Result<IAiClientToolContinuation> {\n const items: JsonObject[] = [];\n\n // Emit function_call items for each call (model's side). Per the Responses API spec\n // (ResponseFunctionToolCall), `call_id` is the required correlation field — it must\n // match the matching function_call_output's `call_id` below. The optional `id` field\n // is the output-item id (`fc_*`) used to reference the streamed item; we omit it\n // because it is not load-bearing for input items.\n const bufferedCallIds = new Set<string>();\n for (const [callId, call] of calls) {\n bufferedCallIds.add(callId);\n items.push({\n type: 'function_call',\n call_id: callId,\n name: call.name,\n arguments: call.argsBuffer\n });\n }\n\n // Emit function_call_output items (harness execution results). Correlate each\n // to a buffered function_call call_id — never the tool name — and fail loud on\n // a missing / empty / mismatched id.\n for (const r of toolResults) {\n if (!isUsableId(r.callId)) {\n return fail(\n `OpenAI continuation: tool '${r.toolName}' result has no call id (missing or empty); ` +\n `cannot correlate it to a function_call item`\n );\n }\n if (!bufferedCallIds.has(r.callId)) {\n return fail(\n `OpenAI continuation: tool '${r.toolName}' call id '${r.callId}' does not match any ` +\n `accumulated function_call call_id`\n );\n }\n items.push({\n type: 'function_call_output',\n call_id: r.callId,\n output: r.result\n });\n }\n\n // Decisive diagnostic: the function_call.call_id ↔ function_call_output.call_id\n // pairing for the outgoing continuation (matched by construction here).\n if (logger) {\n const pairing = toolResults.map((r) => `${r.toolName}:${r.callId}`).join(', ');\n logger.detail(`ai-assist:openai-continuation function_call.call_id↔output.call_id [${pairing}]`);\n }\n\n return succeed({\n messages: items,\n toolCallsSummary: toolResults.map((r) => ({\n toolName: r.toolName,\n callId: r.callId,\n args: r.args,\n result: r.result,\n isError: r.isError\n }))\n });\n}\n\n// ============================================================================\n// Gemini continuation builder\n// ============================================================================\n\n/**\n * Builds the Gemini follow-up contents for a client-tool round-trip.\n *\n * Emits a model turn with `functionCall` parts (one per tool call) and a\n * user turn with `functionResponse` parts (correlation by tool name, since\n * Gemini does not assign call IDs).\n *\n * When thinking is enabled, Gemini stamps an opaque `thoughtSignature` on each\n * `functionCall` part and requires it echoed back, verbatim, as a sibling of\n * `functionCall` on the continuation's model turn — otherwise the follow-up is\n * rejected with \"Function call is missing a thought_signature in functionCall\n * parts\". The captured signature (see {@link IAccumulatedGeminiFunctionCall})\n * is replayed here only when present; the key is omitted entirely when thinking\n * was disabled. See https://ai.google.dev/gemini-api/docs/thought-signatures.\n *\n * @internal\n */\nexport function buildGeminiContinuation(\n calls: IAccumulatedGeminiFunctionCall[],\n toolResults: IToolCallResult[]\n): IAiClientToolContinuation {\n // Model turn: functionCall parts for each call. Replay the part-level\n // thoughtSignature as a sibling of functionCall only when present.\n const modelParts: JsonArray = calls.map(\n (call): JsonObject => ({\n functionCall: {\n name: call.name,\n args: call.args\n },\n ...(call.thoughtSignature !== undefined ? { thoughtSignature: call.thoughtSignature } : {})\n })\n );\n\n // User turn: functionResponse parts for each executed result.\n // Correlation is by name since Gemini has no call IDs.\n const userParts: JsonArray = toolResults.map(\n (r): JsonObject => ({\n functionResponse: {\n name: r.toolName,\n response: {\n content: r.result,\n ...(r.isError ? { error: true } : {})\n }\n }\n })\n );\n\n const modelMessage: JsonObject = {\n role: 'model',\n parts: modelParts\n };\n const userMessage: JsonObject = {\n role: 'user',\n parts: userParts\n };\n\n return {\n messages: [modelMessage, userMessage],\n toolCallsSummary: toolResults.map((r) => ({\n toolName: r.toolName,\n callId: r.callId,\n args: r.args,\n result: r.result,\n isError: r.isError\n }))\n };\n}\n\n// ============================================================================\n// executeClientToolTurn parameters\n// ============================================================================\n\n/**\n * Decision returned by an {@link IExecuteClientToolTurnParams.onBeforeToolExecute}\n * gate for a single client-tool call.\n *\n * @remarks\n * - `{ action: 'proceed' }` — run the tool's `execute` normally.\n * - `{ action: 'deny', reason }` — do NOT run `execute`; a synthesized tool-result\n * carrying `reason` is fed into the continuation exactly like a normal result so\n * the model can react, and a `client-tool-result` event is emitted for the call.\n * The turn continues.\n *\n * A gate that wants to signal a hard error (as opposed to a deliberate deny) should\n * return `Result.fail` (or reject) from the callback. Note this is NOT the same as a\n * `tool.execute` failure: an `execute` failure yields an `isError` tool-result and the\n * **turn continues**, whereas a gate `fail`/reject **terminates the turn** — it fails\n * `nextTurn` (and emits an inline `error` event) rather than synthesizing a deny.\n *\n * @public\n */\nexport type IToolExecutionDecision =\n | { readonly action: 'proceed' }\n | { readonly action: 'deny'; readonly reason: string };\n\n/**\n * Parameters for {@link AiAssist.executeClientToolTurn}.\n *\n * @remarks\n * Carries the unified {@link AiAssist.IChatRequest} shape (`system?` + ordered\n * `messages`): the last message is the current user turn and the preceding\n * messages are history, linearized before the current turn — identically to the\n * completion and streaming paths. {@link IExecuteClientToolTurnParams.continuationMessages}\n * remains a distinct post-current-turn axis (see below).\n *\n * @public\n */\nexport interface IExecuteClientToolTurnParams extends IChatRequest {\n /** The provider descriptor for routing (Anthropic / OpenAI / Gemini). */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication. */\n readonly apiKey: string;\n /**\n * The cumulative provider-native wire tail from the previous turn's\n * {@link AiAssist.IAiClientToolContinuation.messages}. Supply this as-is\n * each round — `messages` is already cumulative, so **replace** rather\n * than manually concatenate:\n *\n * ```ts\n * tail = outcome.continuation.messages; // replace — already cumulative\n * ```\n *\n * On the first turn this should be `undefined` (or omitted).\n *\n * Each provider applies its own shape guard to the supplied wire objects:\n * - Anthropic: projects each entry to `{ role, content }` (sufficient for\n * thinking blocks and `tool_result` arrays).\n * - OpenAI / xAI Responses: passes each item verbatim (`function_call` /\n * `function_call_output` items carry distinct fields per `type`); only\n * guards that each entry is a JSON object.\n * - Gemini: projects each entry to `{ role, parts }`.\n *\n * Entries that fail their provider's shape check are silently skipped.\n * Do NOT place these objects in the `messages` parameter — the\n * normalized-message path strips provider-native fields.\n */\n readonly continuationMessages?: ReadonlyArray<JsonObject>;\n /**\n * Sampling temperature. Sent to the provider only when explicitly provided; omitted otherwise\n * so the provider's own default applies (current-gen models reject a caller-supplied default).\n */\n readonly temperature?: number;\n /** Server-side tools to include. */\n readonly tools?: ReadonlyArray<AiServerToolConfig>;\n /** Client-defined tools available for the model to call. */\n readonly clientTools: ReadonlyArray<IAiClientTool>;\n /** Optional abort signal. */\n readonly signal?: AbortSignal;\n /**\n * Optional override of the descriptor's default base URL. Same semantics as\n * the non-streaming completion path and `callProviderCompletionStream`: a\n * well-formed `http`/`https` URL is substituted for `descriptor.baseUrl`\n * when composing the per-format request, with the per-format suffix appended\n * unchanged. Validated at the dispatcher; auth shape is unaffected. Use this\n * to point a client-tool turn at a local / LAN OpenAI-compatible server\n * (Ollama, LM Studio, llama.cpp).\n */\n readonly endpoint?: string;\n /** Optional logger for diagnostics. */\n readonly logger?: Logging.ILogger;\n /** Optional resolved thinking config (pre-resolved by the caller). */\n readonly resolvedThinking?: IResolvedThinkingConfig;\n /** Resolved model string (pre-resolved by the caller). When omitted, uses the descriptor's default model. */\n readonly model?: string;\n /**\n * Optional host gate invoked for each client-tool call **after** the model's raw\n * args have been validated against the tool's `parametersSchema` and **before**\n * `tool.execute(...)` runs. The full `tool` (including `tool.config.annotations`)\n * and the validated `args` are passed so gate logic can key off a tool's behavior\n * annotations (e.g. deny a `destructiveHint` call pending confirmation).\n *\n * Returning `{ action: 'proceed' }` (or omitting the callback) runs `execute`\n * normally. Returning `{ action: 'deny', reason }` skips `execute` and synthesizes\n * a denial tool-result carrying `reason` into the continuation (the model sees the\n * denial and can react); **the turn continues**. A callback that returns `Result.fail`\n * or rejects is a hard error that **terminates the turn** (fails `nextTurn` + emits an\n * inline `error` event) — distinct from a `tool.execute` failure, which continues the\n * turn with an `isError` result. A deny must therefore be explicit.\n */\n readonly onBeforeToolExecute?: (\n tool: IAiClientTool,\n args: unknown\n ) => Promise<Result<IToolExecutionDecision>>;\n}\n\n/**\n * Return value of {@link AiAssist.executeClientToolTurn}.\n * @public\n */\nexport interface IExecuteClientToolTurnResult {\n /**\n * The unified-event iterable. Callers iterate this to drive the streaming UI.\n * The iterable forwards `text-delta`, `tool-event`, `client-tool-call-start`,\n * `client-tool-call-done`, and `client-tool-result` events through.\n */\n readonly events: AsyncIterable<IAiStreamEvent>;\n /**\n * Resolves when the stream terminates. On success, carries the\n * {@link AiAssist.IAiClientToolTurnResult} with the optional continuation for the\n * next round. On failure, carries the error message.\n */\n readonly nextTurn: Promise<Result<IAiClientToolTurnResult>>;\n}\n\n// ============================================================================\n// executeClientToolTurn\n// ============================================================================\n\n/**\n * True when a request would combine Gemini built-in grounding (a `web_search`\n * server tool) with client (function) tools — a combination Gemini's\n * `generateContent` API rejects with HTTP 400 (`INVALID_ARGUMENT`). Callers gate\n * on `descriptor.apiFormat === 'gemini'` before consulting this; other providers\n * accept the mix. Kept as a pure predicate so the conflict rule is unit-testable\n * without a live stream.\n *\n * @internal\n */\nexport function hasGeminiToolConflict(\n tools: ReadonlyArray<AiServerToolConfig> | undefined,\n clientTools: ReadonlyArray<IAiClientTool>\n): boolean {\n return clientTools.length > 0 && (tools?.some((t) => t.type === 'web_search') ?? false);\n}\n\n/**\n * Orchestrates a single client-tool streaming turn for any supported provider.\n *\n * Starts a streaming request, iterates the underlying provider stream, and:\n * - Forwards `text-delta`, `tool-event`, `client-tool-call-start`, and\n * `client-tool-call-done` events through to the consumer.\n * - For each `client-tool-call-done` event: validates the raw args against the\n * tool's `parametersSchema`, invokes `execute(typedArgs)`, and emits a\n * `client-tool-result` event.\n * - After stream completion: builds the per-provider continuation (or\n * `{ continuation: undefined }` when no tool calls occurred) and resolves\n * `nextTurn`.\n *\n * **Anthropic constraint (E3):** The continuation for Anthropic does not set\n * a forced `tool_choice`. Only `tool_choice: 'auto'` (the default, i.e.\n * omitted) is compatible with extended thinking.\n *\n * @param params - Turn parameters\n * @returns `{ events, nextTurn }` — stream iterable + completion promise\n * @public\n */\nexport function executeClientToolTurn(\n params: IExecuteClientToolTurnParams\n): Result<IExecuteClientToolTurnResult> {\n const {\n descriptor,\n apiKey,\n system,\n messages,\n continuationMessages,\n temperature,\n tools,\n clientTools,\n signal,\n logger,\n resolvedThinking,\n model,\n endpoint,\n onBeforeToolExecute\n } = params;\n\n const splitResult = splitChatRequest(system, messages);\n if (splitResult.isFailure()) {\n return fail(splitResult.message);\n }\n const { prompt, head } = splitResult.value;\n if (prompt.attachments.length > 0 && !descriptor.acceptsImageInput) {\n return fail(`provider \"${descriptor.id}\" does not accept image input`);\n }\n\n // Build a lookup map of client tools by name for fast access.\n // Fail fast on duplicate names — silently overwriting would cause one tool\n // to shadow another with no observable signal.\n const toolsByName = new Map<string, IAiClientTool>();\n for (const tool of clientTools) {\n if (toolsByName.has(tool.config.name)) {\n return fail(`executeClientToolTurn: duplicate client tool name '${tool.config.name}'`);\n }\n toolsByName.set(tool.config.name, tool);\n }\n\n // Merge server tools and client tool configs into a single array for the provider.\n // This is the fix for P1-1: client tools were never sent to the provider because\n // the adapters only received `tools` (server tools). Both must coexist per design §2.5.\n const effectiveTools: ReadonlyArray<AiToolConfig> | undefined =\n clientTools.length > 0 ? [...(tools ?? []), ...clientTools.map((t) => t.config)] : tools;\n\n // Gemini pre-flight: its generateContent API HTTP-400s (INVALID_ARGUMENT) when\n // built-in grounding (`web_search`) and function calling (client tools) are\n // combined in one request. Fail fast with a clear, actionable message rather\n // than letting the opaque wire 400 surface. Other providers accept the mix.\n if (descriptor.apiFormat === 'gemini' && hasGeminiToolConflict(tools, clientTools)) {\n return fail(\n 'executeClientToolTurn: Gemini cannot combine web_search grounding with client (function) tools in the same request; send one or the other'\n );\n }\n\n const modelResult = resolveProviderModel(descriptor, model);\n if (modelResult.isFailure()) {\n return fail(modelResult.message);\n }\n const resolvedModel = modelResult.value;\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n const config: IStreamApiConfig = {\n baseUrl: baseUrlResult.value,\n apiKey,\n model: resolvedModel\n };\n\n // Accumulation buffers — populated by the adapter, read by the builder.\n const anthropicBuffer = new Map<number, IAccumulatedBlock>();\n const openAiCallMap = new Map<string, IAccumulatedFunctionCall>();\n const geminiCalls: IAccumulatedGeminiFunctionCall[] = [];\n\n // Collected tool results, populated as each client-tool-call-done is processed.\n const toolResults: IToolCallResult[] = [];\n\n // Stream start: open the underlying adapter stream.\n const streamPromise: Promise<Result<AsyncIterable<IAiStreamEvent>>> = (() => {\n switch (descriptor.apiFormat) {\n case 'anthropic':\n return callAnthropicStream(\n config,\n prompt,\n head,\n temperature,\n effectiveTools,\n logger,\n signal,\n resolvedThinking,\n anthropicBuffer,\n continuationMessages\n );\n case 'openai':\n return callOpenAiResponsesStream(\n config,\n prompt,\n /* c8 ignore next 1 - defensive: openai path requires tools; empty array fallback unreachable in practice */\n effectiveTools ?? [],\n head,\n temperature,\n logger,\n signal,\n resolvedThinking,\n openAiCallMap,\n continuationMessages\n );\n case 'gemini':\n return callGeminiStream(\n config,\n prompt,\n head,\n temperature,\n effectiveTools,\n logger,\n signal,\n resolvedThinking,\n geminiCalls,\n continuationMessages\n );\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = descriptor.apiFormat;\n return Promise.resolve(fail(`unsupported API format: ${String(_exhaustive)}`));\n }\n }\n })();\n\n // Resolve controls for `nextTurn`.\n let resolveNextTurn!: (result: Result<IAiClientToolTurnResult>) => void;\n const nextTurn = new Promise<Result<IAiClientToolTurnResult>>((resolve) => {\n resolveNextTurn = resolve;\n });\n\n // The unified-event generator: opens the stream, proxies events, executes tools.\n async function* eventGenerator(): AsyncGenerator<IAiStreamEvent> {\n const streamResult = await streamPromise;\n if (streamResult.isFailure()) {\n resolveNextTurn(fail(streamResult.message));\n yield { type: 'error', message: streamResult.message };\n return;\n }\n\n let truncated = false;\n let fullText = '';\n let streamError: string | undefined;\n\n for await (const event of streamResult.value) {\n if (event.type === 'done') {\n truncated = event.truncated;\n fullText = event.fullText;\n yield event;\n continue;\n }\n\n if (event.type === 'error') {\n streamError = event.message;\n yield event;\n continue;\n }\n\n if (event.type === 'text-delta') {\n yield event;\n continue;\n }\n\n if (event.type === 'tool-event') {\n yield event;\n continue;\n }\n\n if (event.type === 'client-tool-call-start') {\n yield event;\n continue;\n }\n\n if (event.type === 'client-tool-call-done') {\n yield event;\n\n const { toolName, callId, args } = event;\n const tool = toolsByName.get(toolName);\n\n if (!tool) {\n const errMsg = `model called unknown tool: ${toolName}`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n resolveNextTurn(fail(errMsg));\n return;\n }\n\n const validationResult = tool.config.parametersSchema.validate(args);\n if (validationResult.isFailure()) {\n const errMsg = `${toolName} (callId=${callId}): ${validationResult.message}`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n continue;\n }\n\n // Host gate: run after arg-validation, before execute. A `deny` decision\n // synthesizes a denial tool-result and continues the turn; a `fail`/reject\n // from the gate itself is a hard error (mirrors an execute failure), never\n // a silent deny.\n if (onBeforeToolExecute !== undefined) {\n const decisionResult: Result<IToolExecutionDecision> = (\n await captureAsyncResult(async () => onBeforeToolExecute(tool, validationResult.value))\n ).onSuccess((decision) => decision);\n\n if (decisionResult.isFailure()) {\n const errMsg = `${toolName} (callId=${callId}): ${decisionResult.message}`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n // Gate-fail is a hard, turn-terminating error (unlike a non-fatal `deny`, whose\n // generator continues). Emit an explicit `error` event so a consumer watching only\n // `events` sees the fatal failure inline and can distinguish it from a deny — matching\n // the stream-open / continuation hard-error paths.\n yield { type: 'error', message: errMsg };\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n resolveNextTurn(fail(errMsg));\n return;\n }\n\n if (decisionResult.value.action === 'deny') {\n const denialMsg = `${toolName} (callId=${callId}): tool execution denied: ${decisionResult.value.reason}`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: denialMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: denialMsg, isError: true });\n continue;\n }\n }\n\n const executeResult = await captureAsyncResult(async () => tool.execute(validationResult.value));\n const executionResult: Result<unknown> = executeResult.isSuccess()\n ? executeResult.value\n : executeResult;\n\n if (executionResult.isFailure()) {\n const errMsg = `${toolName} (callId=${callId}): ${executionResult.message}`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n continue;\n }\n\n // JSON.stringify can throw (circular references) or return undefined\n // (e.g. for a bare `undefined` value, or a value of type `function`).\n // Either outcome violates the client-tool-result event contract, so\n // emit an isError result with diagnostic context instead.\n let resultStr: string;\n try {\n const stringified = JSON.stringify(executionResult.value);\n if (stringified === undefined) {\n const errMsg = `${toolName} (callId=${callId}): tool returned a non-serializable value (JSON.stringify produced undefined)`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n continue;\n }\n resultStr = stringified;\n } catch (e) {\n const errMsg = `${toolName} (callId=${callId}): failed to serialize tool result: ${\n (e as Error).message\n }`;\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: errMsg,\n isError: true\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: errMsg, isError: true });\n continue;\n }\n const resultEvent: IAiStreamEvent = {\n type: 'client-tool-result',\n toolName,\n callId,\n result: resultStr,\n isError: false\n };\n yield resultEvent;\n toolResults.push({ toolName, callId, args, result: resultStr, isError: false });\n continue;\n }\n\n // client-tool-result events are emitted by this layer, not the adapters — no passthrough needed.\n }\n\n // Stream has ended. Build the continuation.\n if (streamError !== undefined) {\n resolveNextTurn(fail(streamError));\n return;\n }\n\n if (toolResults.length === 0) {\n resolveNextTurn(succeed({ continuation: undefined, truncated, fullText }));\n return;\n }\n\n let continuationResult: Result<IAiClientToolContinuation>;\n switch (descriptor.apiFormat) {\n case 'anthropic':\n continuationResult = buildAnthropicContinuation(anthropicBuffer, toolResults, logger);\n break;\n case 'openai':\n continuationResult = buildOpenAiContinuation(openAiCallMap, toolResults, logger);\n break;\n case 'gemini':\n // Gemini correlates by tool name by design (no call ids) — its builder\n // cannot mis-key and stays non-fallible.\n continuationResult = succeed(buildGeminiContinuation(geminiCalls, toolResults));\n break;\n /* c8 ignore next 5 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = descriptor.apiFormat;\n resolveNextTurn(fail(`unsupported API format: ${String(_exhaustive)}`));\n return;\n }\n }\n\n // A bad id-correlation fails loud here rather than emitting a malformed\n // continuation the provider would reject as a \"malformed identifier\". Mirror\n // the stream-open-failure path above: surface an `error` event so a consumer\n // iterating `events` sees the failure inline, not only via `nextTurn`.\n if (continuationResult.isFailure()) {\n resolveNextTurn(fail(continuationResult.message));\n yield { type: 'error', message: continuationResult.message };\n return;\n }\n let continuation = continuationResult.value;\n\n // Prepend inbound continuationMessages so the returned continuation is cumulative.\n // A consumer that does `tail = outcome.continuation.messages` (replace) is then\n // correct for all N rounds — messages always contains the full wire tail from\n // round 1 through the current round. toolCallsSummary stays per-round (this\n // round's calls only); messages is the accumulated tail to re-send.\n if (continuationMessages && continuationMessages.length > 0) {\n continuation = { ...continuation, messages: [...continuationMessages, ...continuation.messages] };\n }\n\n resolveNextTurn(succeed({ continuation, truncated, fullText }));\n }\n\n return succeed({\n events: { [Symbol.asyncIterator]: () => eventGenerator() },\n nextTurn\n });\n}\n"]}
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Shared infrastructure for the per-format streaming adapters: HTTP connection
3
+ * helper, common config and request-params types, and a typed-validation
4
+ * helper for SSE event payloads.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { type Logging, Result, type Validator } from '@fgv/ts-utils';
9
+ import { type AiServerToolConfig, type IAiProviderDescriptor, type IChatRequest, type IThinkingConfig, type ModelSpec } from '../model';
10
+ /**
11
+ * Parameters for a streaming completion request. Structurally identical to
12
+ * the non-streaming `IProviderCompletionParams`; kept as its own interface
13
+ * so callers can be explicit about which path they're invoking.
14
+ *
15
+ * @remarks
16
+ * Carries the unified {@link AiAssist.IChatRequest} shape (`system?` + ordered
17
+ * `messages`): the last message is the current user turn and the preceding
18
+ * messages are history, linearized before the current turn (identical to the
19
+ * completion and client-tool turn paths).
20
+ *
21
+ * @public
22
+ */
23
+ export interface IProviderCompletionStreamParams extends IChatRequest {
24
+ /** The provider descriptor */
25
+ readonly descriptor: IAiProviderDescriptor;
26
+ /** API key for authentication */
27
+ readonly apiKey: string;
28
+ /**
29
+ * Sampling temperature. Sent to the provider only when explicitly provided; omitted otherwise
30
+ * so the provider's own default applies (current-gen models reject a caller-supplied default).
31
+ */
32
+ readonly temperature?: number;
33
+ /** Optional model override — string or context-aware map. */
34
+ readonly modelOverride?: ModelSpec;
35
+ /**
36
+ * Optional quality tier selecting which completion model to use. `undefined`
37
+ * selects the `base` tier; `'frontier'` cascades to `advanced` then `base`
38
+ * when a tier is unset for a provider. Orthogonal to `thinking` and `tools`,
39
+ * which never select a model.
40
+ */
41
+ readonly tier?: 'advanced' | 'frontier';
42
+ /** Optional logger for request/response observability. */
43
+ readonly logger?: Logging.ILogger;
44
+ /** Server-side tools to include in the request. */
45
+ readonly tools?: ReadonlyArray<AiServerToolConfig>;
46
+ /** Optional abort signal for cancelling the in-flight stream. */
47
+ readonly signal?: AbortSignal;
48
+ /**
49
+ * Optional override of the descriptor's default base URL. Same semantics as
50
+ * the non-streaming completion path: a well-formed `http`/`https` URL is
51
+ * substituted for `descriptor.baseUrl` when composing the streaming
52
+ * request, with the per-format suffix appended unchanged. Validated at the
53
+ * dispatcher; auth shape is unaffected.
54
+ */
55
+ readonly endpoint?: string;
56
+ /**
57
+ * Optional thinking/reasoning mode configuration.
58
+ */
59
+ readonly thinking?: IThinkingConfig;
60
+ }
61
+ /**
62
+ * Configuration for a single per-format streaming call: where to POST, what
63
+ * key to authenticate with, and which model to request.
64
+ *
65
+ * @internal
66
+ */
67
+ export interface IStreamApiConfig {
68
+ readonly baseUrl: string;
69
+ readonly apiKey: string;
70
+ readonly model: string;
71
+ }
72
+ /**
73
+ * Stable log-line prefix that every streaming adapter's "unrecognized SSE event"
74
+ * warning starts with. Production deployments can filter / alert on this exact
75
+ * substring without coupling to the per-adapter detail message. Surfacing this
76
+ * as a shared constant ensures all adapters emit the same prefix; loosening or
77
+ * renaming the prefix is a coordinated, intentional change rather than a per-file
78
+ * accident.
79
+ *
80
+ * @internal
81
+ */
82
+ export declare const UNRECOGNIZED_EVENT_WARN_TAG: string;
83
+ /**
84
+ * Stable prefix every "malformed tool_use block" warning starts with. Emitted
85
+ * when a streaming adapter sees a client tool_use `content_block_start` that is
86
+ * missing a usable correlation id and/or name — a block that, if silently
87
+ * dropped, would orphan its argument deltas and corrupt the follow-up tool
88
+ * continuation (the id-correlation defect class). Production deployments can
89
+ * filter / alert on this exact substring. Distinct from
90
+ * {@link UNRECOGNIZED_EVENT_WARN_TAG} (which is for unrecognized SSE *event
91
+ * names*); this is a malformed *payload* of a recognized event.
92
+ *
93
+ * @internal
94
+ */
95
+ export declare const MALFORMED_TOOL_USE_WARN_TAG: string;
96
+ /**
97
+ * Environment variable that opts in to **raw payload preview** in the
98
+ * {@link UNRECOGNIZED_EVENT_WARN_TAG} warning. Any non-empty, non-`'0'` value
99
+ * activates the raw preview. **Default behavior** (env var absent / empty /
100
+ * `'0'`) is **structural-only** preview — top-level JSON keys + payload byte
101
+ * length, never the values.
102
+ *
103
+ * The default-safe posture exists because unrecognized SSE event payloads can
104
+ * carry tool arguments, tool results, user-conversation text, or other
105
+ * potentially sensitive content. Emitting them verbatim at `warn` level — which
106
+ * is the level explicitly designed to surface in production logs / alerting —
107
+ * is a PII leak waiting to happen.
108
+ *
109
+ * Ops triaging an active drift signal (`ai-assist:unrecognized-event` warnings
110
+ * appearing in production logs after a provider API evolution) can set this
111
+ * env var to widen the preview and see the actual payload shape during
112
+ * investigation, then unset it once the new event family is handled.
113
+ *
114
+ * @internal
115
+ */
116
+ export declare const UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR: string;
117
+ /**
118
+ * Renders an SSE `data:` payload for inclusion in an unrecognized-event
119
+ * warning.
120
+ *
121
+ * - Empty payload: returns `<no payload>`.
122
+ * - Default (env var unset): returns structural-only preview (e.g.
123
+ * `{ keys: [type, data], length: 1234 }` for a JSON object payload;
124
+ * `<array payload, length=N>` / `<{type} payload, length=N>` /
125
+ * `<non-JSON payload, length=N>` for other shapes). Never includes
126
+ * field values.
127
+ * - With {@link UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR} set to a truthy
128
+ * value: returns the raw payload, newlines collapsed to spaces, capped
129
+ * at {@link UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX} chars with a trailing
130
+ * ellipsis on truncation. **Use this mode only for active drift triage**
131
+ * — it leaks payload content into warn logs.
132
+ *
133
+ * @internal
134
+ */
135
+ export declare function formatUnrecognizedEventPayloadPreview(data: string): string;
136
+ /**
137
+ * Opens an SSE-style POST connection. Returns the underlying Response on a
138
+ * 2xx; failures (network, non-2xx, missing body) surface as Result.fail
139
+ * carrying the body text.
140
+ *
141
+ * @internal
142
+ */
143
+ export declare function openSseConnection(url: string, headers: Record<string, string>, body: unknown, logger?: Logging.ILogger, signal?: AbortSignal): Promise<Result<Response>>;
144
+ /**
145
+ * Validates a parsed SSE event payload against a typed shape, returning the
146
+ * validated value or `undefined` if validation fails. Adapters use the
147
+ * `undefined` return to skip unrecognized event shapes — the same lenient
148
+ * behavior the inline casts had, but with a real type-checked path on the
149
+ * happy case.
150
+ *
151
+ * @internal
152
+ */
153
+ export declare function validateEventPayload<T>(json: unknown, validator: Validator<T>): T | undefined;
154
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/common.ts"],"names":[],"mappings":"AAoBA;;;;;;GAMG;AAEH,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,EAAW,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEpF,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK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C,IAAI,EAAE,MAAM,GAAG,MAAM,CAgC1E;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/B,IAAI,EAAE,OAAO,EACb,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,EACxB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAmC3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,CAG7F"}
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Erik Fortune
3
+ //
4
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ // of this software and associated documentation files (the "Software"), to deal
6
+ // in the Software without restriction, including without limitation the rights
7
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ // copies of the Software, and to permit persons to whom the Software is
9
+ // furnished to do so, subject to the following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included in all
12
+ // copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ // SOFTWARE.
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR = exports.MALFORMED_TOOL_USE_WARN_TAG = exports.UNRECOGNIZED_EVENT_WARN_TAG = void 0;
23
+ exports.formatUnrecognizedEventPayloadPreview = formatUnrecognizedEventPayloadPreview;
24
+ exports.openSseConnection = openSseConnection;
25
+ exports.validateEventPayload = validateEventPayload;
26
+ /**
27
+ * Shared infrastructure for the per-format streaming adapters: HTTP connection
28
+ * helper, common config and request-params types, and a typed-validation
29
+ * helper for SSE event payloads.
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ const ts_utils_1 = require("@fgv/ts-utils");
34
+ /**
35
+ * Stable log-line prefix that every streaming adapter's "unrecognized SSE event"
36
+ * warning starts with. Production deployments can filter / alert on this exact
37
+ * substring without coupling to the per-adapter detail message. Surfacing this
38
+ * as a shared constant ensures all adapters emit the same prefix; loosening or
39
+ * renaming the prefix is a coordinated, intentional change rather than a per-file
40
+ * accident.
41
+ *
42
+ * @internal
43
+ */
44
+ exports.UNRECOGNIZED_EVENT_WARN_TAG = 'ai-assist:unrecognized-event';
45
+ /**
46
+ * Stable prefix every "malformed tool_use block" warning starts with. Emitted
47
+ * when a streaming adapter sees a client tool_use `content_block_start` that is
48
+ * missing a usable correlation id and/or name — a block that, if silently
49
+ * dropped, would orphan its argument deltas and corrupt the follow-up tool
50
+ * continuation (the id-correlation defect class). Production deployments can
51
+ * filter / alert on this exact substring. Distinct from
52
+ * {@link UNRECOGNIZED_EVENT_WARN_TAG} (which is for unrecognized SSE *event
53
+ * names*); this is a malformed *payload* of a recognized event.
54
+ *
55
+ * @internal
56
+ */
57
+ exports.MALFORMED_TOOL_USE_WARN_TAG = 'ai-assist:malformed-tool-use';
58
+ /**
59
+ * Maximum characters of raw SSE payload to include in the
60
+ * {@link UNRECOGNIZED_EVENT_WARN_TAG} warning when raw-preview mode is opted in
61
+ * via {@link UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR}. Long enough to identify
62
+ * the JSON shape that arrived ("the new event carries field X"), short enough
63
+ * that a hot stream of unknown events with a verbose payload doesn't blow up
64
+ * log volume.
65
+ *
66
+ * @internal
67
+ */
68
+ const UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX = 200;
69
+ /**
70
+ * Environment variable that opts in to **raw payload preview** in the
71
+ * {@link UNRECOGNIZED_EVENT_WARN_TAG} warning. Any non-empty, non-`'0'` value
72
+ * activates the raw preview. **Default behavior** (env var absent / empty /
73
+ * `'0'`) is **structural-only** preview — top-level JSON keys + payload byte
74
+ * length, never the values.
75
+ *
76
+ * The default-safe posture exists because unrecognized SSE event payloads can
77
+ * carry tool arguments, tool results, user-conversation text, or other
78
+ * potentially sensitive content. Emitting them verbatim at `warn` level — which
79
+ * is the level explicitly designed to surface in production logs / alerting —
80
+ * is a PII leak waiting to happen.
81
+ *
82
+ * Ops triaging an active drift signal (`ai-assist:unrecognized-event` warnings
83
+ * appearing in production logs after a provider API evolution) can set this
84
+ * env var to widen the preview and see the actual payload shape during
85
+ * investigation, then unset it once the new event family is handled.
86
+ *
87
+ * @internal
88
+ */
89
+ exports.UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR = 'AI_ASSIST_UNRECOGNIZED_EVENT_FULL_PAYLOAD';
90
+ /**
91
+ * Renders an SSE `data:` payload for inclusion in an unrecognized-event
92
+ * warning.
93
+ *
94
+ * - Empty payload: returns `<no payload>`.
95
+ * - Default (env var unset): returns structural-only preview (e.g.
96
+ * `{ keys: [type, data], length: 1234 }` for a JSON object payload;
97
+ * `<array payload, length=N>` / `<{type} payload, length=N>` /
98
+ * `<non-JSON payload, length=N>` for other shapes). Never includes
99
+ * field values.
100
+ * - With {@link UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR} set to a truthy
101
+ * value: returns the raw payload, newlines collapsed to spaces, capped
102
+ * at {@link UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX} chars with a trailing
103
+ * ellipsis on truncation. **Use this mode only for active drift triage**
104
+ * — it leaks payload content into warn logs.
105
+ *
106
+ * @internal
107
+ */
108
+ function formatUnrecognizedEventPayloadPreview(data) {
109
+ var _a;
110
+ if (data.length === 0)
111
+ return '<no payload>';
112
+ // Opt-in raw preview for ops triage. Accessed via `globalThis` (always
113
+ // defined) rather than a bare `process` reference, so webpack/rollup never
114
+ // try to bundle or polyfill `process` for browser consumers. A
115
+ // `typeof process !== 'undefined'` guard is runtime-safe but still triggers
116
+ // webpack's static module resolution on the `process` identifier.
117
+ const proc = globalThis.process;
118
+ const envValue = (_a = proc === null || proc === void 0 ? void 0 : proc.env) === null || _a === void 0 ? void 0 : _a[exports.UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR];
119
+ const rawPreviewOptIn = envValue !== undefined && envValue !== '' && envValue !== '0';
120
+ if (rawPreviewOptIn) {
121
+ const collapsed = data.replace(/\s+/g, ' ');
122
+ return collapsed.length > UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX
123
+ ? `${collapsed.slice(0, UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX)}…`
124
+ : collapsed;
125
+ }
126
+ // Default-safe: structural information only. Never emits payload values.
127
+ try {
128
+ const parsed = JSON.parse(data);
129
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
130
+ const keys = Object.keys(parsed);
131
+ return `{ keys: [${keys.join(', ')}], length: ${data.length} }`;
132
+ }
133
+ if (Array.isArray(parsed)) {
134
+ return `<array payload, length=${data.length}>`;
135
+ }
136
+ return `<${typeof parsed} payload, length=${data.length}>`;
137
+ }
138
+ catch (_b) {
139
+ return `<non-JSON payload, length=${data.length}>`;
140
+ }
141
+ }
142
+ /**
143
+ * Opens an SSE-style POST connection. Returns the underlying Response on a
144
+ * 2xx; failures (network, non-2xx, missing body) surface as Result.fail
145
+ * carrying the body text.
146
+ *
147
+ * @internal
148
+ */
149
+ async function openSseConnection(url, headers, body, logger, signal) {
150
+ /* c8 ignore next 1 - optional logger */
151
+ logger === null || logger === void 0 ? void 0 : logger.detail(`AI streaming request: POST ${url}`);
152
+ let response;
153
+ try {
154
+ response = await fetch(url, {
155
+ method: 'POST',
156
+ headers: Object.assign({ 'Content-Type': 'application/json', Accept: 'text/event-stream' }, headers),
157
+ body: JSON.stringify(body),
158
+ signal
159
+ });
160
+ }
161
+ catch (err) {
162
+ /* c8 ignore next 1 - defensive: fetch errors are always Error instances in practice */
163
+ const detail = err instanceof Error ? err.message : String(err);
164
+ /* c8 ignore next 1 - optional logger */
165
+ logger === null || logger === void 0 ? void 0 : logger.error(`AI streaming request failed: ${detail}`);
166
+ return (0, ts_utils_1.fail)(`AI streaming request failed: ${detail}`);
167
+ }
168
+ if (!response.ok) {
169
+ const errorText = await response.text().catch(() => 'unknown error');
170
+ /* c8 ignore next 1 - optional logger */
171
+ logger === null || logger === void 0 ? void 0 : logger.error(`AI streaming API returned ${response.status}: ${errorText}`);
172
+ return (0, ts_utils_1.fail)(`AI streaming API returned ${response.status}: ${errorText}`);
173
+ }
174
+ /* c8 ignore next 3 - defensive coding: response.body is always defined for successful fetch responses */
175
+ if (!response.body) {
176
+ return (0, ts_utils_1.fail)('AI streaming API returned an empty body');
177
+ }
178
+ return (0, ts_utils_1.succeed)(response);
179
+ }
180
+ /**
181
+ * Validates a parsed SSE event payload against a typed shape, returning the
182
+ * validated value or `undefined` if validation fails. Adapters use the
183
+ * `undefined` return to skip unrecognized event shapes — the same lenient
184
+ * behavior the inline casts had, but with a real type-checked path on the
185
+ * happy case.
186
+ *
187
+ * @internal
188
+ */
189
+ function validateEventPayload(json, validator) {
190
+ const result = validator.validate(json);
191
+ return result.isSuccess() ? result.value : undefined;
192
+ }
193
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/common.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,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// 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 * Shared infrastructure for the per-format streaming adapters: HTTP connection\n * helper, common config and request-params types, and a typed-validation\n * helper for SSE event payloads.\n *\n * @packageDocumentation\n */\n\nimport { fail, type Logging, Result, succeed, type Validator } from '@fgv/ts-utils';\n\nimport {\n type AiServerToolConfig,\n type IAiProviderDescriptor,\n type IChatRequest,\n type IThinkingConfig,\n type ModelSpec\n} from '../model';\n\n/**\n * Parameters for a streaming completion request. Structurally identical to\n * the non-streaming `IProviderCompletionParams`; kept as its own interface\n * so callers can be explicit about which path they're invoking.\n *\n * @remarks\n * Carries the unified {@link AiAssist.IChatRequest} shape (`system?` + ordered\n * `messages`): the last message is the current user turn and the preceding\n * messages are history, linearized before the current turn (identical to the\n * completion and client-tool turn paths).\n *\n * @public\n */\nexport interface IProviderCompletionStreamParams extends IChatRequest {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /**\n * Sampling temperature. Sent to the provider only when explicitly provided; omitted otherwise\n * so the provider's own default applies (current-gen models reject a caller-supplied default).\n */\n readonly temperature?: number;\n /** Optional model override — string or context-aware map. */\n readonly modelOverride?: ModelSpec;\n /**\n * Optional quality tier selecting which completion model to use. `undefined`\n * selects the `base` tier; `'frontier'` cascades to `advanced` then `base`\n * when a tier is unset for a provider. Orthogonal to `thinking` and `tools`,\n * which never select a model.\n */\n readonly tier?: 'advanced' | 'frontier';\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Server-side tools to include in the request. */\n readonly tools?: ReadonlyArray<AiServerToolConfig>;\n /** Optional abort signal for cancelling the in-flight stream. */\n readonly signal?: AbortSignal;\n /**\n * Optional override of the descriptor's default base URL. Same semantics as\n * the non-streaming completion path: a well-formed `http`/`https` URL is\n * substituted for `descriptor.baseUrl` when composing the streaming\n * request, with the per-format suffix appended unchanged. Validated at the\n * dispatcher; auth shape is unaffected.\n */\n readonly endpoint?: string;\n /**\n * Optional thinking/reasoning mode configuration.\n */\n readonly thinking?: IThinkingConfig;\n}\n\n/**\n * Configuration for a single per-format streaming call: where to POST, what\n * key to authenticate with, and which model to request.\n *\n * @internal\n */\nexport interface IStreamApiConfig {\n readonly baseUrl: string;\n readonly apiKey: string;\n readonly model: string;\n}\n\n/**\n * Stable log-line prefix that every streaming adapter's \"unrecognized SSE event\"\n * warning starts with. Production deployments can filter / alert on this exact\n * substring without coupling to the per-adapter detail message. Surfacing this\n * as a shared constant ensures all adapters emit the same prefix; loosening or\n * renaming the prefix is a coordinated, intentional change rather than a per-file\n * accident.\n *\n * @internal\n */\nexport const UNRECOGNIZED_EVENT_WARN_TAG: string = 'ai-assist:unrecognized-event';\n\n/**\n * Stable prefix every \"malformed tool_use block\" warning starts with. Emitted\n * when a streaming adapter sees a client tool_use `content_block_start` that is\n * missing a usable correlation id and/or name — a block that, if silently\n * dropped, would orphan its argument deltas and corrupt the follow-up tool\n * continuation (the id-correlation defect class). Production deployments can\n * filter / alert on this exact substring. Distinct from\n * {@link UNRECOGNIZED_EVENT_WARN_TAG} (which is for unrecognized SSE *event\n * names*); this is a malformed *payload* of a recognized event.\n *\n * @internal\n */\nexport const MALFORMED_TOOL_USE_WARN_TAG: string = 'ai-assist:malformed-tool-use';\n\n/**\n * Maximum characters of raw SSE payload to include in the\n * {@link UNRECOGNIZED_EVENT_WARN_TAG} warning when raw-preview mode is opted in\n * via {@link UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR}. Long enough to identify\n * the JSON shape that arrived (\"the new event carries field X\"), short enough\n * that a hot stream of unknown events with a verbose payload doesn't blow up\n * log volume.\n *\n * @internal\n */\nconst UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX: number = 200;\n\n/**\n * Environment variable that opts in to **raw payload preview** in the\n * {@link UNRECOGNIZED_EVENT_WARN_TAG} warning. Any non-empty, non-`'0'` value\n * activates the raw preview. **Default behavior** (env var absent / empty /\n * `'0'`) is **structural-only** preview — top-level JSON keys + payload byte\n * length, never the values.\n *\n * The default-safe posture exists because unrecognized SSE event payloads can\n * carry tool arguments, tool results, user-conversation text, or other\n * potentially sensitive content. Emitting them verbatim at `warn` level — which\n * is the level explicitly designed to surface in production logs / alerting —\n * is a PII leak waiting to happen.\n *\n * Ops triaging an active drift signal (`ai-assist:unrecognized-event` warnings\n * appearing in production logs after a provider API evolution) can set this\n * env var to widen the preview and see the actual payload shape during\n * investigation, then unset it once the new event family is handled.\n *\n * @internal\n */\nexport const UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR: string = 'AI_ASSIST_UNRECOGNIZED_EVENT_FULL_PAYLOAD';\n\n/**\n * Renders an SSE `data:` payload for inclusion in an unrecognized-event\n * warning.\n *\n * - Empty payload: returns `<no payload>`.\n * - Default (env var unset): returns structural-only preview (e.g.\n * `{ keys: [type, data], length: 1234 }` for a JSON object payload;\n * `<array payload, length=N>` / `<{type} payload, length=N>` /\n * `<non-JSON payload, length=N>` for other shapes). Never includes\n * field values.\n * - With {@link UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR} set to a truthy\n * value: returns the raw payload, newlines collapsed to spaces, capped\n * at {@link UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX} chars with a trailing\n * ellipsis on truncation. **Use this mode only for active drift triage**\n * — it leaks payload content into warn logs.\n *\n * @internal\n */\nexport function formatUnrecognizedEventPayloadPreview(data: string): string {\n if (data.length === 0) return '<no payload>';\n\n // Opt-in raw preview for ops triage. Accessed via `globalThis` (always\n // defined) rather than a bare `process` reference, so webpack/rollup never\n // try to bundle or polyfill `process` for browser consumers. A\n // `typeof process !== 'undefined'` guard is runtime-safe but still triggers\n // webpack's static module resolution on the `process` identifier.\n const proc = (globalThis as unknown as { process?: { env?: Record<string, string | undefined> } }).process;\n const envValue = proc?.env?.[UNRECOGNIZED_EVENT_FULL_PAYLOAD_ENV_VAR];\n const rawPreviewOptIn = envValue !== undefined && envValue !== '' && envValue !== '0';\n if (rawPreviewOptIn) {\n const collapsed = data.replace(/\\s+/g, ' ');\n return collapsed.length > UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX\n ? `${collapsed.slice(0, UNRECOGNIZED_EVENT_PAYLOAD_PREVIEW_MAX)}…`\n : collapsed;\n }\n\n // Default-safe: structural information only. Never emits payload values.\n try {\n const parsed: unknown = JSON.parse(data);\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n const keys = Object.keys(parsed);\n return `{ keys: [${keys.join(', ')}], length: ${data.length} }`;\n }\n if (Array.isArray(parsed)) {\n return `<array payload, length=${data.length}>`;\n }\n return `<${typeof parsed} payload, length=${data.length}>`;\n } catch {\n return `<non-JSON payload, length=${data.length}>`;\n }\n}\n\n/**\n * Opens an SSE-style POST connection. Returns the underlying Response on a\n * 2xx; failures (network, non-2xx, missing body) surface as Result.fail\n * carrying the body text.\n *\n * @internal\n */\nexport async function openSseConnection(\n url: string,\n headers: Record<string, string>,\n body: unknown,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<Response>> {\n /* c8 ignore next 1 - optional logger */\n logger?.detail(`AI streaming request: POST ${url}`);\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n ...headers\n },\n body: JSON.stringify(body),\n signal\n });\n } catch (err: unknown) {\n /* c8 ignore next 1 - defensive: fetch errors are always Error instances in practice */\n const detail = err instanceof Error ? err.message : String(err);\n /* c8 ignore next 1 - optional logger */\n logger?.error(`AI streaming request failed: ${detail}`);\n return fail(`AI streaming request failed: ${detail}`);\n }\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'unknown error');\n /* c8 ignore next 1 - optional logger */\n logger?.error(`AI streaming API returned ${response.status}: ${errorText}`);\n return fail(`AI streaming API returned ${response.status}: ${errorText}`);\n }\n /* c8 ignore next 3 - defensive coding: response.body is always defined for successful fetch responses */\n if (!response.body) {\n return fail('AI streaming API returned an empty body');\n }\n return succeed(response);\n}\n\n/**\n * Validates a parsed SSE event payload against a typed shape, returning the\n * validated value or `undefined` if validation fails. Adapters use the\n * `undefined` return to skip unrecognized event shapes — the same lenient\n * behavior the inline casts had, but with a real type-checked path on the\n * happy case.\n *\n * @internal\n */\nexport function validateEventPayload<T>(json: unknown, validator: Validator<T>): T | undefined {\n const result = validator.validate(json);\n return result.isSuccess() ? result.value : undefined;\n}\n"]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Streaming adapter for Gemini's `streamGenerateContent` endpoint. Gemini
3
+ * emits no explicit tool-progress events even when `google_search` is
4
+ * enabled — grounding metadata arrives attached to text chunks — so this
5
+ * adapter never yields `tool-event`s.
6
+ *
7
+ * Client-defined tools (`functionCall` parts) are emitted as
8
+ * `client-tool-call-done` immediately (no delta accumulation needed for Gemini).
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import { type Logging, Result } from '@fgv/ts-utils';
13
+ import { type JsonObject } from '@fgv/ts-json-base';
14
+ import { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';
15
+ import { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';
16
+ import { IStreamApiConfig } from './common';
17
+ /**
18
+ * An accumulated function call from a Gemini stream. Gemini does not assign
19
+ * call IDs; correlation is by tool name. Arguments arrive complete in the
20
+ * `functionCall` part (no delta accumulation).
21
+ * @internal
22
+ */
23
+ export interface IAccumulatedGeminiFunctionCall {
24
+ readonly name: string;
25
+ readonly args: JsonObject;
26
+ /**
27
+ * The opaque thought signature Gemini stamps on a `functionCall` part when
28
+ * thinking is enabled. It must be echoed back, verbatim, on the continuation's
29
+ * model turn alongside the `functionCall`, or Gemini rejects the follow-up with
30
+ * "Function call is missing a thought_signature in functionCall parts".
31
+ * Absent when thinking is disabled. See
32
+ * https://ai.google.dev/gemini-api/docs/thought-signatures.
33
+ */
34
+ readonly thoughtSignature?: string;
35
+ }
36
+ /**
37
+ * Issues a streaming Gemini request and returns the unified-event iterable
38
+ * on success.
39
+ *
40
+ * @internal
41
+ */
42
+ export declare function callGeminiStream(config: IStreamApiConfig, prompt: AiPrompt, messagesBefore: ReadonlyArray<IChatMessage> | undefined, temperature: number | undefined, tools: ReadonlyArray<AiToolConfig> | undefined, logger?: Logging.ILogger, signal?: AbortSignal, resolvedThinking?: IResolvedThinkingConfig, functionCalls?: IAccumulatedGeminiFunctionCall[], continuationMessages?: ReadonlyArray<JsonObject>): Promise<Result<AsyncIterable<IAiStreamEvent>>>;
43
+ //# sourceMappingURL=gemini.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gemini.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,EAAuC,MAAM,eAAe,CAAC;AAC1F,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAGlE,OAAO,EAAE,QAAQ,EAAE,KAAK,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