@fgv/ts-extras 5.1.0-26 → 5.1.0-27

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 (103) hide show
  1. package/dist/index.browser.js +2 -2
  2. package/dist/index.browser.js.map +1 -1
  3. package/dist/packlets/ai-assist/apiClient.js +300 -213
  4. package/dist/packlets/ai-assist/apiClient.js.map +1 -1
  5. package/dist/packlets/ai-assist/chatRequestBuilders.js +6 -0
  6. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  7. package/dist/packlets/ai-assist/imageOptionsResolver.js +212 -0
  8. package/dist/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  9. package/dist/packlets/ai-assist/index.js +1 -0
  10. package/dist/packlets/ai-assist/index.js.map +1 -1
  11. package/dist/packlets/ai-assist/model.js +1 -1
  12. package/dist/packlets/ai-assist/model.js.map +1 -1
  13. package/dist/packlets/ai-assist/registry.js +120 -22
  14. package/dist/packlets/ai-assist/registry.js.map +1 -1
  15. package/dist/packlets/ai-assist/sseParser.js +1 -0
  16. package/dist/packlets/ai-assist/sseParser.js.map +1 -1
  17. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +17 -12
  18. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  19. package/dist/packlets/ai-assist/streamingAdapters/common.js +2 -0
  20. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  21. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +17 -5
  22. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  23. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +19 -4
  24. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  25. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +20 -5
  26. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  27. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +9 -3
  28. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  29. package/dist/packlets/ai-assist/streamingClient.js +28 -6
  30. package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
  31. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +265 -0
  32. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  33. package/dist/packlets/conversion/converters.js +1 -0
  34. package/dist/packlets/conversion/converters.js.map +1 -1
  35. package/dist/packlets/crypto-utils/keystore/keyStore.js +2 -1
  36. package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
  37. package/dist/ts-extras.d.ts +595 -119
  38. package/lib/index.browser.d.ts +2 -2
  39. package/lib/index.browser.d.ts.map +1 -1
  40. package/lib/index.browser.js +4 -3
  41. package/lib/index.browser.js.map +1 -1
  42. package/lib/packlets/ai-assist/apiClient.d.ts +29 -85
  43. package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -1
  44. package/lib/packlets/ai-assist/apiClient.js +300 -213
  45. package/lib/packlets/ai-assist/apiClient.js.map +1 -1
  46. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
  47. package/lib/packlets/ai-assist/chatRequestBuilders.js +6 -0
  48. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  49. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts +74 -0
  50. package/lib/packlets/ai-assist/imageOptionsResolver.d.ts.map +1 -0
  51. package/lib/packlets/ai-assist/imageOptionsResolver.js +216 -0
  52. package/lib/packlets/ai-assist/imageOptionsResolver.js.map +1 -0
  53. package/lib/packlets/ai-assist/index.d.ts +2 -1
  54. package/lib/packlets/ai-assist/index.d.ts.map +1 -1
  55. package/lib/packlets/ai-assist/index.js +4 -1
  56. package/lib/packlets/ai-assist/index.js.map +1 -1
  57. package/lib/packlets/ai-assist/model.d.ts +410 -35
  58. package/lib/packlets/ai-assist/model.d.ts.map +1 -1
  59. package/lib/packlets/ai-assist/model.js +1 -1
  60. package/lib/packlets/ai-assist/model.js.map +1 -1
  61. package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
  62. package/lib/packlets/ai-assist/registry.js +120 -22
  63. package/lib/packlets/ai-assist/registry.js.map +1 -1
  64. package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -1
  65. package/lib/packlets/ai-assist/sseParser.js +1 -0
  66. package/lib/packlets/ai-assist/sseParser.js.map +1 -1
  67. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +2 -1
  68. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
  69. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +17 -12
  70. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  71. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +5 -1
  72. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
  73. package/lib/packlets/ai-assist/streamingAdapters/common.js +2 -0
  74. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  75. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +2 -1
  76. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
  77. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +17 -5
  78. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  79. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +2 -1
  80. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
  81. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +19 -4
  82. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  83. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +2 -1
  84. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
  85. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +20 -5
  86. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  87. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
  88. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +9 -3
  89. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  90. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
  91. package/lib/packlets/ai-assist/streamingClient.js +28 -6
  92. package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
  93. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +71 -0
  94. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -0
  95. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +270 -0
  96. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -0
  97. package/lib/packlets/conversion/converters.d.ts.map +1 -1
  98. package/lib/packlets/conversion/converters.js +1 -0
  99. package/lib/packlets/conversion/converters.js.map +1 -1
  100. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -1
  101. package/lib/packlets/crypto-utils/keystore/keyStore.js +2 -1
  102. package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -1
  103. package/package.json +13 -13
@@ -41,7 +41,8 @@ const BUILTIN_PROVIDERS = [
41
41
  supportedTools: [],
42
42
  corsRestricted: false,
43
43
  streamingCorsRestricted: false,
44
- acceptsImageInput: false
44
+ acceptsImageInput: false,
45
+ thinkingMode: 'unsupported'
45
46
  },
46
47
  {
47
48
  id: 'anthropic',
@@ -54,7 +55,8 @@ const BUILTIN_PROVIDERS = [
54
55
  supportedTools: ['web_search'],
55
56
  corsRestricted: false,
56
57
  streamingCorsRestricted: false,
57
- acceptsImageInput: true
58
+ acceptsImageInput: true,
59
+ thinkingMode: 'optional'
58
60
  },
59
61
  {
60
62
  id: 'google-gemini',
@@ -68,11 +70,38 @@ const BUILTIN_PROVIDERS = [
68
70
  corsRestricted: false,
69
71
  streamingCorsRestricted: false,
70
72
  acceptsImageInput: true,
73
+ thinkingMode: 'optional',
71
74
  imageGeneration: [
72
- // imagen-* models are predict-only and do not accept reference images;
73
- // everything else uses chat-style :generateContent with refs.
74
- { modelPrefix: 'imagen-', format: 'gemini-imagen' },
75
- { modelPrefix: '', format: 'gemini-image-out', acceptsImageReferenceInput: true }
75
+ {
76
+ // Imagen 4 Ultra: max 1 image
77
+ modelPrefix: 'imagen-4.0-ultra-',
78
+ format: 'gemini-imagen',
79
+ acceptsImageReferenceInput: false,
80
+ supportsQualityParam: false,
81
+ maxCount: 1,
82
+ outputParamStyle: 'none',
83
+ defaultOutputMimeType: 'image/png'
84
+ },
85
+ {
86
+ // All other Imagen 4 models: max 4 images
87
+ modelPrefix: 'imagen-',
88
+ format: 'gemini-imagen',
89
+ acceptsImageReferenceInput: false,
90
+ supportsQualityParam: false,
91
+ maxCount: 4,
92
+ outputParamStyle: 'none',
93
+ defaultOutputMimeType: 'image/png'
94
+ },
95
+ {
96
+ // Gemini Flash Image: chat-style generateContent
97
+ modelPrefix: '',
98
+ format: 'gemini-image-out',
99
+ acceptsImageReferenceInput: true,
100
+ supportsQualityParam: false,
101
+ maxCount: 1,
102
+ outputParamStyle: 'none',
103
+ defaultOutputMimeType: 'image/jpeg'
104
+ }
76
105
  ]
77
106
  },
78
107
  {
@@ -86,7 +115,8 @@ const BUILTIN_PROVIDERS = [
86
115
  supportedTools: [],
87
116
  corsRestricted: false,
88
117
  streamingCorsRestricted: false,
89
- acceptsImageInput: false
118
+ acceptsImageInput: false,
119
+ thinkingMode: 'unsupported'
90
120
  },
91
121
  {
92
122
  id: 'mistral',
@@ -99,7 +129,8 @@ const BUILTIN_PROVIDERS = [
99
129
  supportedTools: [],
100
130
  corsRestricted: false,
101
131
  streamingCorsRestricted: false,
102
- acceptsImageInput: false
132
+ acceptsImageInput: false,
133
+ thinkingMode: 'unsupported'
103
134
  },
104
135
  {
105
136
  id: 'ollama',
@@ -112,7 +143,8 @@ const BUILTIN_PROVIDERS = [
112
143
  supportedTools: [],
113
144
  corsRestricted: false,
114
145
  streamingCorsRestricted: false,
115
- acceptsImageInput: false
146
+ acceptsImageInput: false,
147
+ thinkingMode: 'unsupported'
116
148
  },
117
149
  {
118
150
  id: 'openai',
@@ -126,13 +158,46 @@ const BUILTIN_PROVIDERS = [
126
158
  corsRestricted: false,
127
159
  streamingCorsRestricted: false,
128
160
  acceptsImageInput: true,
161
+ thinkingMode: 'optional',
129
162
  imageGeneration: [
130
- // gpt-image-1 supports /images/edits with reference images. dall-e-3
131
- // (the default image model) does not, so the catch-all rule omits
132
- // acceptsImageReferenceInput; callers selecting dall-e-3 with refs hit
133
- // the up-front rejection rather than a provider 400.
134
- { modelPrefix: 'gpt-image-', format: 'openai-images', acceptsImageReferenceInput: true },
135
- { modelPrefix: '', format: 'openai-images' }
163
+ {
164
+ modelPrefix: 'gpt-image-',
165
+ format: 'openai-images',
166
+ acceptsImageReferenceInput: true,
167
+ acceptedSizes: ['1024x1024', '1536x1024', '1024x1536', 'auto'],
168
+ supportsQualityParam: true,
169
+ acceptedQualities: ['low', 'medium', 'high', 'auto'],
170
+ maxCount: 10,
171
+ outputParamStyle: 'output-format',
172
+ defaultOutputMimeType: 'image/png'
173
+ },
174
+ {
175
+ modelPrefix: 'dall-e-3',
176
+ format: 'openai-images',
177
+ acceptsImageReferenceInput: false,
178
+ acceptedSizes: ['1024x1024', '1792x1024', '1024x1792'],
179
+ supportsQualityParam: true,
180
+ acceptedQualities: ['standard', 'hd'],
181
+ maxCount: 1,
182
+ outputParamStyle: 'response-format',
183
+ defaultOutputMimeType: 'image/png'
184
+ },
185
+ {
186
+ modelPrefix: 'dall-e-2',
187
+ format: 'openai-images',
188
+ acceptsImageReferenceInput: false,
189
+ acceptedSizes: ['256x256', '512x512', '1024x1024'],
190
+ supportsQualityParam: false,
191
+ maxCount: 10,
192
+ outputParamStyle: 'response-format',
193
+ defaultOutputMimeType: 'image/png'
194
+ },
195
+ {
196
+ modelPrefix: '',
197
+ format: 'openai-images',
198
+ outputParamStyle: 'response-format',
199
+ defaultOutputMimeType: 'image/png'
200
+ }
136
201
  ]
137
202
  },
138
203
  {
@@ -146,7 +211,8 @@ const BUILTIN_PROVIDERS = [
146
211
  supportedTools: [],
147
212
  corsRestricted: false,
148
213
  streamingCorsRestricted: false,
149
- acceptsImageInput: false
214
+ acceptsImageInput: false,
215
+ thinkingMode: 'unsupported'
150
216
  },
151
217
  {
152
218
  id: 'xai-grok',
@@ -156,15 +222,38 @@ const BUILTIN_PROVIDERS = [
156
222
  apiFormat: 'openai',
157
223
  baseUrl: 'https://api.x.ai/v1',
158
224
  defaultModel: {
159
- base: 'grok-4-1-fast',
160
- tools: 'grok-4-1-fast-reasoning',
161
- image: 'grok-2-image-1212'
225
+ base: 'grok-4.3',
226
+ tools: 'grok-4.3',
227
+ thinking: 'grok-4.3',
228
+ image: 'grok-imagine-image-quality'
162
229
  },
163
230
  supportedTools: ['web_search'],
164
231
  corsRestricted: true,
165
232
  streamingCorsRestricted: true,
166
233
  acceptsImageInput: true,
167
- imageGeneration: [{ modelPrefix: '', format: 'xai-images' }]
234
+ thinkingMode: 'optional',
235
+ imageGeneration: [
236
+ {
237
+ // grok-imagine models use JSON edits with image_url objects (different wire format)
238
+ modelPrefix: 'grok-imagine-',
239
+ format: 'xai-images-edits',
240
+ acceptsImageReferenceInput: true,
241
+ supportsQualityParam: false,
242
+ maxCount: 10,
243
+ outputParamStyle: 'response-format',
244
+ defaultOutputMimeType: 'image/jpeg'
245
+ },
246
+ {
247
+ // catch-all for other xai image models
248
+ modelPrefix: '',
249
+ format: 'xai-images',
250
+ acceptsImageReferenceInput: false,
251
+ supportsQualityParam: false,
252
+ maxCount: 10,
253
+ outputParamStyle: 'response-format',
254
+ defaultOutputMimeType: 'image/jpeg'
255
+ }
256
+ ]
168
257
  }
169
258
  ];
170
259
  /**
@@ -249,22 +338,31 @@ export const DEFAULT_MODEL_CAPABILITY_CONFIG = {
249
338
  openai: [
250
339
  { idPattern: /^dall-e/, capabilities: ['image-generation'] },
251
340
  { idPattern: /^gpt-image/, capabilities: ['image-generation'] },
341
+ { idPattern: /^gpt-5/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },
252
342
  { idPattern: /^gpt-4/, capabilities: ['chat', 'tools', 'vision'] },
253
343
  { idPattern: /^gpt-3\.5/, capabilities: ['chat'] },
254
- { idPattern: /^o\d/, capabilities: ['chat', 'tools'] }
344
+ { idPattern: /^o\d/, capabilities: ['chat', 'tools', 'thinking'] }
255
345
  ],
256
346
  'xai-grok': [
257
347
  { idPattern: /-image/, capabilities: ['image-generation'] },
348
+ { idPattern: /^grok-4\.3/, capabilities: ['chat', 'tools', 'thinking'] },
349
+ { idPattern: /^grok-4$/, capabilities: ['chat', 'tools', 'thinking'] },
258
350
  { idPattern: /^grok-4/, capabilities: ['chat', 'tools', 'vision'] },
351
+ { idPattern: /^grok-3-mini/, capabilities: ['chat', 'tools', 'thinking'] },
259
352
  { idPattern: /^grok-3/, capabilities: ['chat', 'tools'] },
260
353
  { idPattern: /^grok-2/, capabilities: ['chat', 'vision'] }
261
354
  ],
262
355
  'google-gemini': [
263
356
  { idPattern: /^imagen/, capabilities: ['image-generation'] },
264
357
  { idPattern: /^gemini-.*-image/, capabilities: ['image-generation'] },
358
+ { idPattern: /^gemini-2\.5/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },
265
359
  { idPattern: /^gemini-/, capabilities: ['chat', 'tools', 'vision'] }
266
360
  ],
267
- anthropic: [{ idPattern: /^claude-/, capabilities: ['chat', 'tools', 'vision'] }],
361
+ anthropic: [
362
+ { idPattern: /^claude-opus-4/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },
363
+ { idPattern: /^claude-sonnet-4/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },
364
+ { idPattern: /^claude-/, capabilities: ['chat', 'tools', 'vision'] }
365
+ ],
268
366
  groq: [{ idPattern: /./, capabilities: ['chat'] }],
269
367
  mistral: [{ idPattern: /./, capabilities: ['chat'] }]
270
368
  }
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/packlets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CAAC,EAAE;YAC5D,EAAE,SAAS,EAAE,kBAAkB,EAAE,YAAY,EAAE,CAAC,kBAAkB,CAAC,EAAE;YACrE,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE;SACrE;QACD,SAAS,EAAE,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC;QACjF,IAAI,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,OAAO,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;KACtD;CACF,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 * Centralized provider registry — single source of truth for all AI provider metadata.\n * @packageDocumentation\n */\n\nimport { fail, Result, succeed } from '@fgv/ts-utils';\n\nimport {\n type AiProviderId,\n type IAiImageModelCapability,\n type IAiModelCapabilityConfig,\n type IAiProviderDescriptor\n} from './model';\n\n// ============================================================================\n// Built-in providers\n// ============================================================================\n\n/**\n * All known AI provider descriptors. Copy-paste first, then alphabetical.\n * @internal\n */\nconst BUILTIN_PROVIDERS: ReadonlyArray<IAiProviderDescriptor> = [\n {\n id: 'copy-paste',\n label: 'Copy / Paste',\n buttonLabel: 'AI Assist | Copy',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: '',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false\n },\n {\n id: 'anthropic',\n label: 'Anthropic Claude',\n buttonLabel: 'AI Assist | Claude',\n needsSecret: true,\n apiFormat: 'anthropic',\n baseUrl: 'https://api.anthropic.com/v1',\n defaultModel: 'claude-sonnet-4-5-20250929',\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true\n },\n {\n id: 'google-gemini',\n label: 'Google Gemini',\n buttonLabel: 'AI Assist | Gemini',\n needsSecret: true,\n apiFormat: 'gemini',\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta',\n defaultModel: { base: 'gemini-2.5-flash', image: 'gemini-2.5-flash-image' },\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true,\n imageGeneration: [\n // imagen-* models are predict-only and do not accept reference images;\n // everything else uses chat-style :generateContent with refs.\n { modelPrefix: 'imagen-', format: 'gemini-imagen' },\n { modelPrefix: '', format: 'gemini-image-out', acceptsImageReferenceInput: true }\n ]\n },\n {\n id: 'groq',\n label: 'Groq',\n buttonLabel: 'AI Assist | Groq',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.groq.com/openai/v1',\n defaultModel: 'llama-3.3-70b-versatile',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false\n },\n {\n id: 'mistral',\n label: 'Mistral',\n buttonLabel: 'AI Assist | Mistral',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.mistral.ai/v1',\n defaultModel: 'mistral-large-latest',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false\n },\n {\n id: 'ollama',\n label: 'Ollama (self-hosted)',\n buttonLabel: 'AI Assist | Ollama',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: 'http://localhost:11434/v1',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false\n },\n {\n id: 'openai',\n label: 'OpenAI',\n buttonLabel: 'AI Assist | OpenAI',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.openai.com/v1',\n defaultModel: { base: 'gpt-4o', image: 'dall-e-3' },\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true,\n imageGeneration: [\n // gpt-image-1 supports /images/edits with reference images. dall-e-3\n // (the default image model) does not, so the catch-all rule omits\n // acceptsImageReferenceInput; callers selecting dall-e-3 with refs hit\n // the up-front rejection rather than a provider 400.\n { modelPrefix: 'gpt-image-', format: 'openai-images', acceptsImageReferenceInput: true },\n { modelPrefix: '', format: 'openai-images' }\n ]\n },\n {\n id: 'openai-compat',\n label: 'OpenAI-compatible (self-hosted)',\n buttonLabel: 'AI Assist | OpenAI-compat',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: '',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false\n },\n {\n id: 'xai-grok',\n label: 'xAI Grok',\n buttonLabel: 'AI Assist | Grok',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.x.ai/v1',\n defaultModel: {\n base: 'grok-4-1-fast',\n tools: 'grok-4-1-fast-reasoning',\n image: 'grok-2-image-1212'\n },\n supportedTools: ['web_search'],\n corsRestricted: true,\n streamingCorsRestricted: true,\n acceptsImageInput: true,\n imageGeneration: [{ modelPrefix: '', format: 'xai-images' }]\n }\n];\n\n/**\n * Index for O(1) lookup by id.\n * @internal\n */\nconst PROVIDER_BY_ID: ReadonlyMap<string, IAiProviderDescriptor> = new Map(\n BUILTIN_PROVIDERS.map((d) => [d.id, d])\n);\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * All valid provider ID values, in the same order as the registry.\n * @public\n */\nexport const allProviderIds: ReadonlyArray<AiProviderId> = BUILTIN_PROVIDERS.map((d) => d.id);\n\n/**\n * Get all known provider descriptors. Copy-paste first, then alphabetical.\n * @returns All built-in provider descriptors\n * @public\n */\nexport function getProviderDescriptors(): ReadonlyArray<IAiProviderDescriptor> {\n return BUILTIN_PROVIDERS;\n}\n\n/**\n * Get a provider descriptor by id.\n * @param id - The provider identifier\n * @returns The descriptor, or a failure if the provider is unknown\n * @public\n */\nexport function getProviderDescriptor(id: string): Result<IAiProviderDescriptor> {\n const descriptor = PROVIDER_BY_ID.get(id);\n if (!descriptor) {\n return fail(`unknown AI provider: ${id}`);\n }\n return succeed(descriptor);\n}\n\n/**\n * Whether a provider declares any image-generation capability at all.\n *\n * @param descriptor - The provider descriptor\n * @returns `true` when {@link IAiProviderDescriptor.imageGeneration} has at\n * least one entry; `false` otherwise.\n * @public\n */\nexport function supportsImageGeneration(descriptor: IAiProviderDescriptor): boolean {\n return (descriptor.imageGeneration?.length ?? 0) > 0;\n}\n\n/**\n * Resolve the image-generation capability that applies to a given model id\n * for a provider. Returns the entry from\n * {@link IAiProviderDescriptor.imageGeneration} whose `modelPrefix` is the\n * longest prefix of `modelId`. Ties are broken by first-encountered, so rule\n * order does not matter for correctness — only for tie-breaking among rules\n * with identical-length prefixes (an unusual case).\n *\n * @param descriptor - The provider descriptor\n * @param modelId - The resolved image model id\n * @returns The matching capability, or `undefined` when no rule matches or\n * the provider declares no image-generation capabilities.\n * @public\n */\nexport function resolveImageCapability(\n descriptor: IAiProviderDescriptor,\n modelId: string\n): IAiImageModelCapability | undefined {\n return (descriptor.imageGeneration ?? [])\n .filter((cap) => modelId.startsWith(cap.modelPrefix))\n .reduce<IAiImageModelCapability | undefined>(\n (best, cap) => (best && best.modelPrefix.length >= cap.modelPrefix.length ? best : cap),\n undefined\n );\n}\n\n// ============================================================================\n// Default model capability config\n// ============================================================================\n\n/**\n * Default capability config used by `callProviderListModels` when callers\n * don't supply their own. Patterns are intentionally narrow — false\n * positives are worse than missing a model. Caller can override per call\n * via {@link IProviderListModelsParams.capabilityConfig}.\n *\n * @public\n */\nexport const DEFAULT_MODEL_CAPABILITY_CONFIG: IAiModelCapabilityConfig = {\n perProvider: {\n openai: [\n { idPattern: /^dall-e/, capabilities: ['image-generation'] },\n { idPattern: /^gpt-image/, capabilities: ['image-generation'] },\n { idPattern: /^gpt-4/, capabilities: ['chat', 'tools', 'vision'] },\n { idPattern: /^gpt-3\\.5/, capabilities: ['chat'] },\n { idPattern: /^o\\d/, capabilities: ['chat', 'tools'] }\n ],\n 'xai-grok': [\n { idPattern: /-image/, capabilities: ['image-generation'] },\n { idPattern: /^grok-4/, capabilities: ['chat', 'tools', 'vision'] },\n { idPattern: /^grok-3/, capabilities: ['chat', 'tools'] },\n { idPattern: /^grok-2/, capabilities: ['chat', 'vision'] }\n ],\n 'google-gemini': [\n { idPattern: /^imagen/, capabilities: ['image-generation'] },\n { idPattern: /^gemini-.*-image/, capabilities: ['image-generation'] },\n { idPattern: /^gemini-/, capabilities: ['chat', 'tools', 'vision'] }\n ],\n anthropic: [{ idPattern: /^claude-/, capabilities: ['chat', 'tools', 'vision'] }],\n groq: [{ idPattern: /./, capabilities: ['chat'] }],\n mistral: [{ idPattern: /./, capabilities: ['chat'] }]\n }\n};\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/registry.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+E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EAAE;YACpF,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE;SACrE;QACD,SAAS,EAAE;YACT,EAAE,SAAS,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE;YACtF,EAAE,SAAS,EAAE,kBAAkB,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE;YACxF,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE;SACrE;QACD,IAAI,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,OAAO,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;KACtD;CACF,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 * Centralized provider registry — single source of truth for all AI provider metadata.\n * @packageDocumentation\n */\n\nimport { fail, Result, succeed } from '@fgv/ts-utils';\n\nimport {\n type AiProviderId,\n type IAiImageModelCapability,\n type IAiModelCapabilityConfig,\n type IAiProviderDescriptor\n} from './model';\n\n// ============================================================================\n// Built-in providers\n// ============================================================================\n\n/**\n * All known AI provider descriptors. Copy-paste first, then alphabetical.\n * @internal\n */\nconst BUILTIN_PROVIDERS: ReadonlyArray<IAiProviderDescriptor> = [\n {\n id: 'copy-paste',\n label: 'Copy / Paste',\n buttonLabel: 'AI Assist | Copy',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: '',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false,\n thinkingMode: 'unsupported'\n },\n {\n id: 'anthropic',\n label: 'Anthropic Claude',\n buttonLabel: 'AI Assist | Claude',\n needsSecret: true,\n apiFormat: 'anthropic',\n baseUrl: 'https://api.anthropic.com/v1',\n defaultModel: 'claude-sonnet-4-5-20250929',\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true,\n thinkingMode: 'optional'\n },\n {\n id: 'google-gemini',\n label: 'Google Gemini',\n buttonLabel: 'AI Assist | Gemini',\n needsSecret: true,\n apiFormat: 'gemini',\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta',\n defaultModel: { base: 'gemini-2.5-flash', image: 'gemini-2.5-flash-image' },\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true,\n thinkingMode: 'optional',\n imageGeneration: [\n {\n // Imagen 4 Ultra: max 1 image\n modelPrefix: 'imagen-4.0-ultra-',\n format: 'gemini-imagen',\n acceptsImageReferenceInput: false,\n supportsQualityParam: false,\n maxCount: 1,\n outputParamStyle: 'none',\n defaultOutputMimeType: 'image/png'\n },\n {\n // All other Imagen 4 models: max 4 images\n modelPrefix: 'imagen-',\n format: 'gemini-imagen',\n acceptsImageReferenceInput: false,\n supportsQualityParam: false,\n maxCount: 4,\n outputParamStyle: 'none',\n defaultOutputMimeType: 'image/png'\n },\n {\n // Gemini Flash Image: chat-style generateContent\n modelPrefix: '',\n format: 'gemini-image-out',\n acceptsImageReferenceInput: true,\n supportsQualityParam: false,\n maxCount: 1,\n outputParamStyle: 'none',\n defaultOutputMimeType: 'image/jpeg'\n }\n ]\n },\n {\n id: 'groq',\n label: 'Groq',\n buttonLabel: 'AI Assist | Groq',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.groq.com/openai/v1',\n defaultModel: 'llama-3.3-70b-versatile',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false,\n thinkingMode: 'unsupported'\n },\n {\n id: 'mistral',\n label: 'Mistral',\n buttonLabel: 'AI Assist | Mistral',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.mistral.ai/v1',\n defaultModel: 'mistral-large-latest',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false,\n thinkingMode: 'unsupported'\n },\n {\n id: 'ollama',\n label: 'Ollama (self-hosted)',\n buttonLabel: 'AI Assist | Ollama',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: 'http://localhost:11434/v1',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false,\n thinkingMode: 'unsupported'\n },\n {\n id: 'openai',\n label: 'OpenAI',\n buttonLabel: 'AI Assist | OpenAI',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.openai.com/v1',\n defaultModel: { base: 'gpt-4o', image: 'dall-e-3' },\n supportedTools: ['web_search'],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: true,\n thinkingMode: 'optional',\n imageGeneration: [\n {\n modelPrefix: 'gpt-image-',\n format: 'openai-images',\n acceptsImageReferenceInput: true,\n acceptedSizes: ['1024x1024', '1536x1024', '1024x1536', 'auto'],\n supportsQualityParam: true,\n acceptedQualities: ['low', 'medium', 'high', 'auto'],\n maxCount: 10,\n outputParamStyle: 'output-format',\n defaultOutputMimeType: 'image/png'\n },\n {\n modelPrefix: 'dall-e-3',\n format: 'openai-images',\n acceptsImageReferenceInput: false,\n acceptedSizes: ['1024x1024', '1792x1024', '1024x1792'],\n supportsQualityParam: true,\n acceptedQualities: ['standard', 'hd'],\n maxCount: 1,\n outputParamStyle: 'response-format',\n defaultOutputMimeType: 'image/png'\n },\n {\n modelPrefix: 'dall-e-2',\n format: 'openai-images',\n acceptsImageReferenceInput: false,\n acceptedSizes: ['256x256', '512x512', '1024x1024'],\n supportsQualityParam: false,\n maxCount: 10,\n outputParamStyle: 'response-format',\n defaultOutputMimeType: 'image/png'\n },\n {\n modelPrefix: '',\n format: 'openai-images',\n outputParamStyle: 'response-format',\n defaultOutputMimeType: 'image/png'\n }\n ]\n },\n {\n id: 'openai-compat',\n label: 'OpenAI-compatible (self-hosted)',\n buttonLabel: 'AI Assist | OpenAI-compat',\n needsSecret: false,\n apiFormat: 'openai',\n baseUrl: '',\n defaultModel: '',\n supportedTools: [],\n corsRestricted: false,\n streamingCorsRestricted: false,\n acceptsImageInput: false,\n thinkingMode: 'unsupported'\n },\n {\n id: 'xai-grok',\n label: 'xAI Grok',\n buttonLabel: 'AI Assist | Grok',\n needsSecret: true,\n apiFormat: 'openai',\n baseUrl: 'https://api.x.ai/v1',\n defaultModel: {\n base: 'grok-4.3',\n tools: 'grok-4.3',\n thinking: 'grok-4.3',\n image: 'grok-imagine-image-quality'\n },\n supportedTools: ['web_search'],\n corsRestricted: true,\n streamingCorsRestricted: true,\n acceptsImageInput: true,\n thinkingMode: 'optional',\n imageGeneration: [\n {\n // grok-imagine models use JSON edits with image_url objects (different wire format)\n modelPrefix: 'grok-imagine-',\n format: 'xai-images-edits',\n acceptsImageReferenceInput: true,\n supportsQualityParam: false,\n maxCount: 10,\n outputParamStyle: 'response-format',\n defaultOutputMimeType: 'image/jpeg'\n },\n {\n // catch-all for other xai image models\n modelPrefix: '',\n format: 'xai-images',\n acceptsImageReferenceInput: false,\n supportsQualityParam: false,\n maxCount: 10,\n outputParamStyle: 'response-format',\n defaultOutputMimeType: 'image/jpeg'\n }\n ]\n }\n];\n\n/**\n * Index for O(1) lookup by id.\n * @internal\n */\nconst PROVIDER_BY_ID: ReadonlyMap<string, IAiProviderDescriptor> = new Map(\n BUILTIN_PROVIDERS.map((d) => [d.id, d])\n);\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * All valid provider ID values, in the same order as the registry.\n * @public\n */\nexport const allProviderIds: ReadonlyArray<AiProviderId> = BUILTIN_PROVIDERS.map((d) => d.id);\n\n/**\n * Get all known provider descriptors. Copy-paste first, then alphabetical.\n * @returns All built-in provider descriptors\n * @public\n */\nexport function getProviderDescriptors(): ReadonlyArray<IAiProviderDescriptor> {\n return BUILTIN_PROVIDERS;\n}\n\n/**\n * Get a provider descriptor by id.\n * @param id - The provider identifier\n * @returns The descriptor, or a failure if the provider is unknown\n * @public\n */\nexport function getProviderDescriptor(id: string): Result<IAiProviderDescriptor> {\n const descriptor = PROVIDER_BY_ID.get(id);\n if (!descriptor) {\n return fail(`unknown AI provider: ${id}`);\n }\n return succeed(descriptor);\n}\n\n/**\n * Whether a provider declares any image-generation capability at all.\n *\n * @param descriptor - The provider descriptor\n * @returns `true` when {@link IAiProviderDescriptor.imageGeneration} has at\n * least one entry; `false` otherwise.\n * @public\n */\nexport function supportsImageGeneration(descriptor: IAiProviderDescriptor): boolean {\n return (descriptor.imageGeneration?.length ?? 0) > 0;\n}\n\n/**\n * Resolve the image-generation capability that applies to a given model id\n * for a provider. Returns the entry from\n * {@link IAiProviderDescriptor.imageGeneration} whose `modelPrefix` is the\n * longest prefix of `modelId`. Ties are broken by first-encountered, so rule\n * order does not matter for correctness — only for tie-breaking among rules\n * with identical-length prefixes (an unusual case).\n *\n * @param descriptor - The provider descriptor\n * @param modelId - The resolved image model id\n * @returns The matching capability, or `undefined` when no rule matches or\n * the provider declares no image-generation capabilities.\n * @public\n */\nexport function resolveImageCapability(\n descriptor: IAiProviderDescriptor,\n modelId: string\n): IAiImageModelCapability | undefined {\n return (descriptor.imageGeneration ?? [])\n .filter((cap) => modelId.startsWith(cap.modelPrefix))\n .reduce<IAiImageModelCapability | undefined>(\n (best, cap) => (best && best.modelPrefix.length >= cap.modelPrefix.length ? best : cap),\n undefined\n );\n}\n\n// ============================================================================\n// Default model capability config\n// ============================================================================\n\n/**\n * Default capability config used by `callProviderListModels` when callers\n * don't supply their own. Patterns are intentionally narrow — false\n * positives are worse than missing a model. Caller can override per call\n * via {@link IProviderListModelsParams.capabilityConfig}.\n *\n * @public\n */\nexport const DEFAULT_MODEL_CAPABILITY_CONFIG: IAiModelCapabilityConfig = {\n perProvider: {\n openai: [\n { idPattern: /^dall-e/, capabilities: ['image-generation'] },\n { idPattern: /^gpt-image/, capabilities: ['image-generation'] },\n { idPattern: /^gpt-5/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },\n { idPattern: /^gpt-4/, capabilities: ['chat', 'tools', 'vision'] },\n { idPattern: /^gpt-3\\.5/, capabilities: ['chat'] },\n { idPattern: /^o\\d/, capabilities: ['chat', 'tools', 'thinking'] }\n ],\n 'xai-grok': [\n { idPattern: /-image/, capabilities: ['image-generation'] },\n { idPattern: /^grok-4\\.3/, capabilities: ['chat', 'tools', 'thinking'] },\n { idPattern: /^grok-4$/, capabilities: ['chat', 'tools', 'thinking'] },\n { idPattern: /^grok-4/, capabilities: ['chat', 'tools', 'vision'] },\n { idPattern: /^grok-3-mini/, capabilities: ['chat', 'tools', 'thinking'] },\n { idPattern: /^grok-3/, capabilities: ['chat', 'tools'] },\n { idPattern: /^grok-2/, capabilities: ['chat', 'vision'] }\n ],\n 'google-gemini': [\n { idPattern: /^imagen/, capabilities: ['image-generation'] },\n { idPattern: /^gemini-.*-image/, capabilities: ['image-generation'] },\n { idPattern: /^gemini-2\\.5/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },\n { idPattern: /^gemini-/, capabilities: ['chat', 'tools', 'vision'] }\n ],\n anthropic: [\n { idPattern: /^claude-opus-4/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },\n { idPattern: /^claude-sonnet-4/, capabilities: ['chat', 'tools', 'vision', 'thinking'] },\n { idPattern: /^claude-/, capabilities: ['chat', 'tools', 'vision'] }\n ],\n groq: [{ idPattern: /./, capabilities: ['chat'] }],\n mistral: [{ idPattern: /./, capabilities: ['chat'] }]\n }\n};\n"]}
@@ -87,6 +87,7 @@ export function readSseEvents(body) {
87
87
  const normalized = buffer.replace(/\r\n/g, '\n');
88
88
  const parts = normalized.split('\n\n');
89
89
  // Last element is the partial chunk (no terminating blank line yet); buffer it.
90
+ /* c8 ignore next 1 - defensive: parts.pop() returning undefined is unreachable after split */
90
91
  buffer = (_a = parts.pop()) !== null && _a !== void 0 ? _a : '';
91
92
  for (const chunk of parts) {
92
93
  const event = parseSseEvent(chunk);
@@ -1 +1 @@
1
- {"version":3,"file":"sseParser.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/sseParser.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;;;;;;;;;;;;;;AAwBZ;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,IAAI,KAAyB,CAAC;IAC9B,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,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AC","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 * Server-Sent Events (SSE) parser primitives shared by the streaming format\n * adapters in `streamingClient.ts`. Implements the subset of the SSE wire\n * format that LLM providers actually emit: optional `event:` line, one or\n * more `data:` lines per message, messages separated by a blank line.\n *\n * @packageDocumentation\n */\n\n/**\n * One parsed SSE message (the SSE spec calls each blank-line-terminated\n * record an \"event\").\n *\n * @internal\n */\nexport interface ISseEvent {\n /** The `event:` field, if present (some providers omit it). */\n readonly event?: string;\n /** Concatenated contents of the message's `data:` lines. */\n readonly data: string;\n}\n\n/**\n * Parses a single SSE message (the text between blank-line separators) into\n * an {@link ISseEvent}. Returns undefined for messages with no `data:` lines\n * (comments, heartbeats).\n *\n * @internal\n */\nexport function parseSseEvent(chunk: string): ISseEvent | undefined {\n let event: string | undefined;\n const dataLines: string[] = [];\n for (const line of chunk.split('\\n')) {\n if (line.startsWith('event:')) {\n event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n // Per the SSE spec the value starts after the colon, with one optional leading space stripped.\n const value = line.slice(5);\n dataLines.push(value.startsWith(' ') ? value.slice(1) : value);\n }\n }\n if (dataLines.length === 0) {\n return undefined;\n }\n return event !== undefined ? { event, data: dataLines.join('\\n') } : { data: dataLines.join('\\n') };\n}\n\n/**\n * Reads an SSE response body and yields parsed events. Buffers across read()\n * boundaries so a message split mid-chunk still parses cleanly. Terminates\n * when the stream closes (normal EOF or aborted fetch).\n *\n * @internal\n */\nexport async function* readSseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<ISseEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n let streaming = true;\n while (streaming) {\n const { value, done } = await reader.read();\n if (done) {\n streaming = false;\n if (buffer.length > 0) {\n const tail = parseSseEvent(buffer.replace(/\\r\\n/g, '\\n'));\n if (tail) {\n yield tail;\n }\n }\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n // SSE messages are separated by a blank line; some servers use \\r\\n.\n const normalized = buffer.replace(/\\r\\n/g, '\\n');\n const parts = normalized.split('\\n\\n');\n // Last element is the partial chunk (no terminating blank line yet); buffer it.\n buffer = parts.pop() ?? '';\n for (const chunk of parts) {\n const event = parseSseEvent(chunk);\n if (event) {\n yield event;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Parses the `data` payload of an SSE event as JSON. Returns undefined for\n * the OpenAI `[DONE]` sentinel and for any payload that fails to parse —\n * adapters treat both as \"skip this event.\"\n *\n * @internal\n */\nexport function parseSseEventJson(data: string): unknown | undefined {\n if (data === '[DONE]') {\n return undefined;\n }\n try {\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"sseParser.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/sseParser.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AA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T,MAAM,CAAC,WAAW,EAAE,CAAC;QACvB,CAAC;IACH,CAAC;CAAA;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Server-Sent Events (SSE) parser primitives shared by the streaming format\n * adapters in `streamingClient.ts`. Implements the subset of the SSE wire\n * format that LLM providers actually emit: optional `event:` line, one or\n * more `data:` lines per message, messages separated by a blank line.\n *\n * @packageDocumentation\n */\n\n/**\n * One parsed SSE message (the SSE spec calls each blank-line-terminated\n * record an \"event\").\n *\n * @internal\n */\nexport interface ISseEvent {\n /** The `event:` field, if present (some providers omit it). */\n readonly event?: string;\n /** Concatenated contents of the message's `data:` lines. */\n readonly data: string;\n}\n\n/**\n * Parses a single SSE message (the text between blank-line separators) into\n * an {@link ISseEvent}. Returns undefined for messages with no `data:` lines\n * (comments, heartbeats).\n *\n * @internal\n */\nexport function parseSseEvent(chunk: string): ISseEvent | undefined {\n let event: string | undefined;\n const dataLines: string[] = [];\n for (const line of chunk.split('\\n')) {\n if (line.startsWith('event:')) {\n event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n // Per the SSE spec the value starts after the colon, with one optional leading space stripped.\n const value = line.slice(5);\n dataLines.push(value.startsWith(' ') ? value.slice(1) : value);\n }\n }\n if (dataLines.length === 0) {\n return undefined;\n }\n return event !== undefined ? { event, data: dataLines.join('\\n') } : { data: dataLines.join('\\n') };\n}\n\n/**\n * Reads an SSE response body and yields parsed events. Buffers across read()\n * boundaries so a message split mid-chunk still parses cleanly. Terminates\n * when the stream closes (normal EOF or aborted fetch).\n *\n * @internal\n */\nexport async function* readSseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<ISseEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n let streaming = true;\n while (streaming) {\n const { value, done } = await reader.read();\n if (done) {\n streaming = false;\n if (buffer.length > 0) {\n const tail = parseSseEvent(buffer.replace(/\\r\\n/g, '\\n'));\n if (tail) {\n yield tail;\n }\n }\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n // SSE messages are separated by a blank line; some servers use \\r\\n.\n const normalized = buffer.replace(/\\r\\n/g, '\\n');\n const parts = normalized.split('\\n\\n');\n // Last element is the partial chunk (no terminating blank line yet); buffer it.\n /* c8 ignore next 1 - defensive: parts.pop() returning undefined is unreachable after split */\n buffer = parts.pop() ?? '';\n for (const chunk of parts) {\n const event = parseSseEvent(chunk);\n if (event) {\n yield event;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Parses the `data` payload of an SSE event as JSON. Returns undefined for\n * the OpenAI `[DONE]` sentinel and for any payload that fails to parse —\n * adapters treat both as \"skip this event.\"\n *\n * @internal\n */\nexport function parseSseEventJson(data: string): unknown | undefined {\n if (data === '[DONE]') {\n return undefined;\n }\n try {\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n}\n"]}
@@ -96,6 +96,7 @@ function translateAnthropicStream(response) {
96
96
  const eventName = message.event;
97
97
  if (eventName === 'content_block_start') {
98
98
  const payload = validateEventPayload(parseSseEventJson(message.data), anthropicContentBlockStartPayload);
99
+ /* c8 ignore next 6 - defensive: block?.type optional chaining null branches are unreachable */
99
100
  const block = payload === null || payload === void 0 ? void 0 : payload.content_block;
100
101
  if ((block === null || block === void 0 ? void 0 : block.type) === 'server_tool_use' && block.name === 'web_search') {
101
102
  yield yield __await({ type: 'tool-event', toolType: 'web_search', phase: 'started' });
@@ -106,6 +107,7 @@ function translateAnthropicStream(response) {
106
107
  }
107
108
  else if (eventName === 'content_block_delta') {
108
109
  const payload = validateEventPayload(parseSseEventJson(message.data), anthropicContentBlockDeltaPayload);
110
+ /* c8 ignore next 1 - defensive: payload?.delta.type null branch unreachable after validation */
109
111
  if ((payload === null || payload === void 0 ? void 0 : payload.delta.type) === 'text_delta' && typeof payload.delta.text === 'string') {
110
112
  const delta = payload.delta.text;
111
113
  if (delta.length > 0) {
@@ -116,6 +118,7 @@ function translateAnthropicStream(response) {
116
118
  }
117
119
  else if (eventName === 'message_delta') {
118
120
  const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);
121
+ /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */
119
122
  if ((payload === null || payload === void 0 ? void 0 : payload.delta.stop_reason) === 'max_tokens') {
120
123
  truncated = true;
121
124
  }
@@ -127,6 +130,7 @@ function translateAnthropicStream(response) {
127
130
  const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);
128
131
  yield yield __await({
129
132
  type: 'error',
133
+ /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */
130
134
  message: (_e = (_d = payload === null || payload === void 0 ? void 0 : payload.error) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : 'Anthropic stream returned an error event'
131
135
  });
132
136
  return yield __await(void 0);
@@ -141,10 +145,10 @@ function translateAnthropicStream(response) {
141
145
  finally { if (e_1) throw e_1.error; }
142
146
  }
143
147
  }
144
- catch (err) {
148
+ catch (err) /* c8 ignore start - defensive: stream errors are always Error instances */ {
145
149
  yield yield __await({ type: 'error', message: err instanceof Error ? err.message : String(err) });
146
150
  return yield __await(void 0);
147
- }
151
+ } /* c8 ignore stop */
148
152
  if (stopped) {
149
153
  yield yield __await({ type: 'done', truncated, fullText });
150
154
  }
@@ -162,17 +166,18 @@ function translateAnthropicStream(response) {
162
166
  *
163
167
  * @internal
164
168
  */
165
- export async function callAnthropicStream(config, prompt, messagesBefore, temperature, tools, logger, signal) {
169
+ export async function callAnthropicStream(config, prompt, messagesBefore, temperature, tools, logger, signal, resolvedThinking) {
166
170
  const url = `${config.baseUrl}/messages`;
167
171
  const messages = buildAnthropicMessages(prompt, { head: messagesBefore });
168
- const body = {
169
- model: config.model,
170
- system: prompt.system,
171
- messages,
172
- max_tokens: 4096,
173
- temperature,
174
- stream: true
175
- };
172
+ // When thinking is active, temperature is rejected by Anthropic (validated upstream).
173
+ const body = Object.assign(Object.assign({ model: config.model, system: prompt.system, messages, max_tokens: 4096 }, ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.anthropicEffort) === undefined ? { temperature } : {})), { stream: true });
174
+ if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.anthropicEffort) !== undefined) {
175
+ body.thinking = { type: 'enabled' };
176
+ body.output_config = { effort: resolvedThinking.anthropicEffort };
177
+ }
178
+ if ((resolvedThinking === null || resolvedThinking === void 0 ? void 0 : resolvedThinking.otherParams) !== undefined) {
179
+ Object.assign(body, resolvedThinking.otherParams);
180
+ }
176
181
  if (tools && tools.length > 0) {
177
182
  body.tools = toAnthropicTools(tools);
178
183
  }
@@ -181,7 +186,7 @@ export async function callAnthropicStream(config, prompt, messagesBefore, temper
181
186
  'anthropic-version': '2023-06-01',
182
187
  'anthropic-dangerous-direct-browser-access': 'true'
183
188
  };
184
- /* c8 ignore next 3 - optional logger diagnostic output */
189
+ /* c8 ignore next 4 - optional logger diagnostic output */
185
190
  if (logger) {
186
191
  const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';
187
192
  logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.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;;;;;;;;;;;;;;;;;;;;;AAEZ;;;;;;GAMG;AAEH,OAAO,EAAwB,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAoB,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AA8CrF,MAAM,0BAA0B,GAAgD,UAAU,CAAC,MAAM,CAI/F;IACE,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,UAAU,CA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ACD,MAAM,OAAO,GAA2B;QACtC,WAAW,EAAE,MAAM,CAAC,MAAM;QAC1B,mBAAmB,EAAE,YAAY;QACjC,2CAA2C,EAAE,MAAM;KACpD,CAAC;IACF,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,8BAA8B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AACnF,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for the Anthropic Messages API. Surfaces server tool\n * use (e.g. `web_search`) as unified `tool-event` markers based on the\n * `content_block_start` / `content_block_stop` lifecycle.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport { AiPrompt, type AiServerToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event. The `type` discriminator\n * tells us whether the block is text, a server-tool invocation, or a\n * tool result.\n *\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly content_block: { readonly type?: string; readonly name?: string };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. The inner `delta.type`\n * discriminator is `text_delta` for the text we care about; other values\n * (e.g. `input_json_delta` for tool args) are ignored.\n *\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly delta: { readonly type?: string; readonly text?: string };\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n *\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n *\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{ type?: string; name?: string }> = Validators.object<{\n type?: string;\n name?: string;\n}>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>({\n content_block: anthropicContentBlockInner\n });\n\nconst anthropicContentBlockDeltaInner: Validator<{ type?: string; text?: string }> = Validators.object<{\n type?: string;\n text?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>({\n delta: anthropicContentBlockDeltaInner\n });\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateAnthropicStream(response: Response): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n const block = payload?.content_block;\n if (block?.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block?.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n if (payload?.delta.type === 'text_delta' && typeof payload.delta.text === 'string') {\n const delta = payload.delta.text;\n if (delta.length > 0) {\n fullText += delta;\n yield { type: 'text-delta', delta };\n }\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n }\n }\n } catch (err: unknown) {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n }\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number,\n tools: ReadonlyArray<AiServerToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, { head: messagesBefore });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n max_tokens: 4096,\n temperature,\n stream: true\n };\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = {\n 'x-api-key': config.apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true'\n };\n /* c8 ignore next 3 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response)));\n}\n"]}
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.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;;;;;;;;;;;;;;;;;;;;;AAEZ;;;;;;GAMG;AAEH,OAAO,EAAwB,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,EAAoB,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AA8CrF,MAAM,0BAA0B,GAAgD,UAAU,CAAC,MAAM,CAI/F;IACE,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;CACnC,EACD,EAAE,OAAO,EAAE,EAAE,cAAc,EAA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AAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AACnF,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for the Anthropic Messages API. Surfaces server tool\n * use (e.g. `web_search`) as unified `tool-event` markers based on the\n * `content_block_start` / `content_block_stop` lifecycle.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport { AiPrompt, type AiServerToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event. The `type` discriminator\n * tells us whether the block is text, a server-tool invocation, or a\n * tool result.\n *\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly content_block: { readonly type?: string; readonly name?: string };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. The inner `delta.type`\n * discriminator is `text_delta` for the text we care about; other values\n * (e.g. `input_json_delta` for tool args) are ignored.\n *\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly delta: { readonly type?: string; readonly text?: string };\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n *\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n *\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{ type?: string; name?: string }> = Validators.object<{\n type?: string;\n name?: string;\n}>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>({\n content_block: anthropicContentBlockInner\n });\n\nconst anthropicContentBlockDeltaInner: Validator<{ type?: string; text?: string }> = Validators.object<{\n type?: string;\n text?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>({\n delta: anthropicContentBlockDeltaInner\n });\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateAnthropicStream(response: Response): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 6 - defensive: block?.type optional chaining null branches are unreachable */\n const block = payload?.content_block;\n if (block?.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block?.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload?.delta.type null branch unreachable after validation */\n if (payload?.delta.type === 'text_delta' && typeof payload.delta.text === 'string') {\n const delta = payload.delta.text;\n if (delta.length > 0) {\n fullText += delta;\n yield { type: 'text-delta', delta };\n }\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number,\n tools: ReadonlyArray<AiServerToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, { head: messagesBefore });\n // When thinking is active, temperature is rejected by Anthropic (validated upstream).\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n max_tokens: 4096,\n ...(resolvedThinking?.anthropicEffort === undefined ? { temperature } : {}),\n stream: true\n };\n if (resolvedThinking?.anthropicEffort !== undefined) {\n body.thinking = { type: 'enabled' };\n body.output_config = { effort: resolvedThinking.anthropicEffort };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = {\n 'x-api-key': config.apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true'\n };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response)));\n}\n"]}
@@ -45,6 +45,7 @@ export async function openSseConnection(url, headers, body, logger, signal) {
45
45
  });
46
46
  }
47
47
  catch (err) {
48
+ /* c8 ignore next 1 - defensive: fetch errors are always Error instances in practice */
48
49
  const detail = err instanceof Error ? err.message : String(err);
49
50
  /* c8 ignore next 1 - optional logger */
50
51
  logger === null || logger === void 0 ? void 0 : logger.error(`AI streaming request failed: ${detail}`);
@@ -56,6 +57,7 @@ export async function openSseConnection(url, headers, body, logger, signal) {
56
57
  logger === null || logger === void 0 ? void 0 : logger.error(`AI streaming API returned ${response.status}: ${errorText}`);
57
58
  return fail(`AI streaming API returned ${response.status}: ${errorText}`);
58
59
  }
60
+ /* c8 ignore next 3 - defensive coding: response.body is always defined for successful fetch responses */
59
61
  if (!response.body) {
60
62
  return fail('AI streaming API returned an empty body');
61
63
  }
@@ -1 +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,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;AAEZ;;;;;;GAMG;AAEH,OAAO,EAAE,IAAI,EAAwB,OAAO,EAAkB,MAAM,eAAe,CAAC;AA+DpF;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB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I,CAAC,yCAAyC,CAAC,CAAC;IACzD,CAAC;IACD,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC3B,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAI,IAAa,EAAE,SAAuB;IAC5E,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACvD,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 * 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 AiPrompt,\n type AiServerToolConfig,\n type IAiProviderDescriptor,\n type IChatMessage,\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 * @public\n */\nexport interface IProviderCompletionStreamParams {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /** The structured prompt to send */\n readonly prompt: AiPrompt;\n /**\n * Prior conversation history to insert between the system prompt and the\n * prompt's user message. The new user turn (carried by `prompt.user`) is\n * always sent last, so the wire shape becomes\n * `[system, ...messagesBefore, user=prompt.user]`.\n */\n readonly messagesBefore?: ReadonlyArray<IChatMessage>;\n /** Sampling temperature (default: 0.7) */\n readonly temperature?: number;\n /** Optional model override — string or context-aware map. */\n readonly modelOverride?: ModelSpec;\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\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 * 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 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 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"]}
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,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;AAEZ;;;;;;GAMG;AAEH,OAAO,EAAE,IAAI,EAAwB,OAAO,EAAkB,MAAM,eAAe,CAAC;AAoEpF;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,GAAW,EACX,OAA+B,EAC/B,IAAa,EACb,MAAwB,EACxB,MA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ACzD,CAAC;IACD,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC3B,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAI,IAAa,EAAE,SAAuB;IAC5E,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACvD,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 * 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 AiPrompt,\n type AiServerToolConfig,\n type IAiProviderDescriptor,\n type IChatMessage,\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 * @public\n */\nexport interface IProviderCompletionStreamParams {\n /** The provider descriptor */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication */\n readonly apiKey: string;\n /** The structured prompt to send */\n readonly prompt: AiPrompt;\n /**\n * Prior conversation history to insert between the system prompt and the\n * prompt's user message. The new user turn (carried by `prompt.user`) is\n * always sent last, so the wire shape becomes\n * `[system, ...messagesBefore, user=prompt.user]`.\n */\n readonly messagesBefore?: ReadonlyArray<IChatMessage>;\n /** Sampling temperature (default: 0.7) */\n readonly temperature?: number;\n /** Optional model override — string or context-aware map. */\n readonly modelOverride?: ModelSpec;\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 * 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"]}