@valerypopoff/rivet2-core 2.1.9 → 2.3.0

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 (188) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +5618 -2533
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +333 -22
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/exports.js +1 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +558 -0
  11. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  12. package/dist/esm/model/GraphProcessor.js +165 -74
  13. package/dist/esm/model/NodeImpl.js +6 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +212 -25
  16. package/dist/esm/model/SplitRunProcessor.js +49 -8
  17. package/dist/esm/model/SubprocessorBridge.js +3 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  19. package/dist/esm/model/UiGraph.js +21 -0
  20. package/dist/esm/model/UiGraphActionProtocol.js +3 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  22. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  23. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  24. package/dist/esm/model/UiGraphSchema.js +7 -1
  25. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  29. package/dist/esm/model/chat-v2/chatV2EditorCache.js +47 -20
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  31. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  32. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  33. package/dist/esm/model/chat-v2/chatV2Pipeline.js +101 -149
  34. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +39 -4
  35. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  36. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  37. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +63 -0
  38. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  39. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  40. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -7
  41. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  42. package/dist/esm/model/chat-v2/chatV2Types.js +20 -8
  43. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  44. package/dist/esm/model/chat-v2/customProviderApi.js +40 -0
  45. package/dist/esm/model/chat-v2/index.js +15 -0
  46. package/dist/esm/model/chat-v2/llmChatV2Body.js +289 -0
  47. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  48. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +25 -0
  49. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +13 -50
  50. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +117 -24
  51. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  52. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +150 -199
  53. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  54. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  55. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  56. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  57. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  58. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  59. package/dist/esm/model/chat-v2/llmModelCandidate.js +79 -0
  60. package/dist/esm/model/chat-v2/llmProfile.js +52 -65
  61. package/dist/esm/model/chat-v2/llmProfileBody.js +193 -0
  62. package/dist/esm/model/chat-v2/llmProfileFallback.js +442 -100
  63. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +74 -0
  64. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  65. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +55 -33
  66. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  67. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  68. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  69. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  70. package/dist/esm/model/chat-v2/providerOptions.js +116 -24
  71. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  72. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  73. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  74. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  75. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  76. package/dist/esm/model/nodes/ChatNode.js +6 -0
  77. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  78. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  79. package/dist/esm/model/nodes/CodeNode.js +4 -46
  80. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  81. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  82. package/dist/esm/model/nodes/LLMChatV2Node.js +121 -229
  83. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  84. package/dist/esm/model/nodes/MatchNode.js +86 -41
  85. package/dist/esm/model/nodes/PromptNode.js +7 -0
  86. package/dist/esm/model/nodes/ToolNode.js +7 -0
  87. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  88. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  89. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  90. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  91. package/dist/esm/plugins/gentrace/index.js +0 -1
  92. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  93. package/dist/esm/plugins/google/google.js +5 -9
  94. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  95. package/dist/esm/plugins.js +1 -2
  96. package/dist/esm/recording/ExecutionRecorder.js +62 -13
  97. package/dist/esm/utils/emitDetached.js +6 -3
  98. package/dist/esm/utils/openai.js +60 -16
  99. package/dist/esm/utils/serialization/serialization.js +2 -19
  100. package/dist/esm/webAppRuntime.js +3 -2
  101. package/dist/types/api/createProcessor.d.ts +3 -0
  102. package/dist/types/exports.d.ts +1 -0
  103. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  104. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  105. package/dist/types/model/AgentResponseTrace.d.ts +123 -0
  106. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  107. package/dist/types/model/EditorDefinition.d.ts +16 -0
  108. package/dist/types/model/ExecutorProtocol.d.ts +32 -11
  109. package/dist/types/model/GraphProcessor.d.ts +41 -9
  110. package/dist/types/model/NodeBase.d.ts +0 -10
  111. package/dist/types/model/NodeImpl.d.ts +18 -1
  112. package/dist/types/model/Nodes.d.ts +2 -2
  113. package/dist/types/model/ProcessContext.d.ts +99 -0
  114. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  115. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  116. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  117. package/dist/types/model/UiGraph.d.ts +8 -0
  118. package/dist/types/model/UiGraphActionProtocol.d.ts +3 -0
  119. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  120. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  121. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  122. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  123. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  124. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  125. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +2 -3
  126. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  127. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  128. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +7 -0
  129. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  130. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  131. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +25 -0
  132. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  133. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  134. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  135. package/dist/types/model/chat-v2/chatV2Types.d.ts +44 -10
  136. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  137. package/dist/types/model/chat-v2/customProviderApi.d.ts +22 -0
  138. package/dist/types/model/chat-v2/index.d.ts +15 -0
  139. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  140. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  141. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  142. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +19 -3
  143. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  144. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  145. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  146. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  147. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  148. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  149. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  150. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  151. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +20 -0
  152. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  153. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  154. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +36 -49
  155. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +209 -0
  156. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  157. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  158. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +4 -1
  159. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  160. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  161. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  162. package/dist/types/model/chat-v2/providerOptions.d.ts +12 -0
  163. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  164. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  165. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  166. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  167. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  168. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  169. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  170. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  171. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  172. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  173. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  174. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  175. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  176. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  177. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  178. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  179. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  180. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  181. package/dist/types/plugins/google/google.d.ts +2 -8
  182. package/dist/types/plugins.d.ts +1 -1
  183. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  184. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  185. package/dist/types/utils/emitDetached.d.ts +3 -2
  186. package/dist/types/utils/openai.d.ts +49 -0
  187. package/dist/types/webAppRuntime.d.ts +4 -2
  188. package/package.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import { generateText, NoObjectGeneratedError, streamText } from 'ai';
2
2
  import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
3
+ import { ChatV2ProviderTimeoutError } from './chatV2Types.js';
3
4
  import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
4
5
  function keepPromiseHandled(value) {
5
6
  const promise = Promise.resolve(value);
@@ -153,6 +154,109 @@ function buildTextArgs(options) {
153
154
  args.abortSignal = options.abortSignal;
154
155
  return args;
155
156
  }
157
+ function isUsefulStreamPart(part) {
158
+ const event = part;
159
+ if (event?.type === 'tool-call')
160
+ return true;
161
+ if (event?.type === 'text-delta' || event?.type === 'reasoning-delta') {
162
+ return typeof event.text === 'string' && event.text.length > 0;
163
+ }
164
+ if (event?.type === 'tool-input-delta') {
165
+ return typeof event.delta === 'string' && event.delta.length > 0;
166
+ }
167
+ return false;
168
+ }
169
+ function timeoutPromise(timeoutMs, kind, onTimeout) {
170
+ let timer;
171
+ const promise = new Promise((_resolve, reject) => {
172
+ timer = setTimeout(() => {
173
+ const error = new ChatV2ProviderTimeoutError(kind, timeoutMs);
174
+ reject(error);
175
+ try {
176
+ onTimeout?.(error);
177
+ }
178
+ catch {
179
+ // Timeout notification is cleanup-only and cannot replace the deadline.
180
+ }
181
+ }, timeoutMs);
182
+ });
183
+ return {
184
+ promise,
185
+ cancel: () => {
186
+ if (timer != null)
187
+ clearTimeout(timer);
188
+ },
189
+ };
190
+ }
191
+ async function* streamWithDeadlines(stream, options, firstOutputStartedAt) {
192
+ const iterator = stream[Symbol.asyncIterator]();
193
+ let hasUsefulOutput = false;
194
+ let lastUsefulOutputAt = firstOutputStartedAt;
195
+ try {
196
+ for (;;) {
197
+ const kind = hasUsefulOutput ? 'stream-inactivity' : 'first-output';
198
+ const configuredTimeout = hasUsefulOutput ? options.streamInactivityTimeoutMs : options.firstOutputTimeoutMs;
199
+ const timeoutMs = configuredTimeout == null
200
+ ? undefined
201
+ : Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
202
+ const timeout = timeoutMs == null ? undefined : timeoutPromise(timeoutMs, kind, options.onTimeout);
203
+ let next;
204
+ try {
205
+ next = await (timeout == null ? iterator.next() : Promise.race([iterator.next(), timeout.promise]));
206
+ }
207
+ finally {
208
+ timeout?.cancel();
209
+ }
210
+ if (next.done)
211
+ return;
212
+ if (isUsefulStreamPart(next.value)) {
213
+ hasUsefulOutput = true;
214
+ lastUsefulOutputAt = Date.now();
215
+ try {
216
+ options.onStreamActivity?.();
217
+ }
218
+ catch {
219
+ // Health lease renewal is observational and cannot break the stream.
220
+ }
221
+ }
222
+ yield next.value;
223
+ }
224
+ }
225
+ finally {
226
+ try {
227
+ const cleanup = iterator.return?.();
228
+ if (cleanup != null) {
229
+ void Promise.resolve(cleanup).catch(() => undefined);
230
+ }
231
+ }
232
+ catch {
233
+ // The deadline/consumer error remains authoritative over iterator cleanup.
234
+ }
235
+ }
236
+ }
237
+ async function waitForGeneratedResponse(executorPromise, options) {
238
+ if (options.firstOutputTimeoutMs == null)
239
+ return await executorPromise;
240
+ const timeout = timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
241
+ try {
242
+ return await Promise.race([executorPromise, timeout.promise]);
243
+ }
244
+ finally {
245
+ timeout.cancel();
246
+ }
247
+ }
248
+ async function waitForPostResponseFinalization(finalization, options) {
249
+ const timeoutMs = options.streamInactivityTimeoutMs ?? options.firstOutputTimeoutMs;
250
+ if (timeoutMs == null)
251
+ return await finalization;
252
+ const timeout = timeoutPromise(timeoutMs, options.streamInactivityTimeoutMs == null ? 'first-output' : 'stream-inactivity', options.onTimeout);
253
+ try {
254
+ return await Promise.race([finalization, timeout.promise]);
255
+ }
256
+ finally {
257
+ timeout.cancel();
258
+ }
259
+ }
156
260
  function toStreamedFunctionCalls(toolCalls) {
157
261
  return (toolCalls ?? []).map((toolCall) => ({
158
262
  type: 'function',
@@ -171,14 +275,25 @@ async function resolveGenerateReasoning(result) {
171
275
  }
172
276
  async function executeStream(options, executor) {
173
277
  const args = buildTextArgs(options);
174
- const handle = await executor(args);
278
+ const firstOutputStartedAt = Date.now();
279
+ const handlePromise = Promise.resolve(executor(args));
280
+ const handleTimeout = options.firstOutputTimeoutMs == null
281
+ ? undefined
282
+ : timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
283
+ let handle;
284
+ try {
285
+ handle = await (handleTimeout == null ? handlePromise : Promise.race([handlePromise, handleTimeout.promise]));
286
+ }
287
+ finally {
288
+ handleTimeout?.cancel();
289
+ }
175
290
  markOptionalPromiseHandled(handle.finishReason);
176
291
  markOptionalPromiseHandled(handle.output);
177
292
  markOptionalPromiseHandled(handle.providerMetadata);
178
293
  markOptionalPromiseHandled(handle.requestStatus);
179
294
  markOptionalPromiseHandled(handle.usage);
180
295
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
181
- const streamed = await consumeAiSdkStream(handle.fullStream, (text, functionCalls) => {
296
+ const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls) => {
182
297
  options.onPartialOutput?.({
183
298
  text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
184
299
  functionCalls,
@@ -189,15 +304,22 @@ async function executeStream(options, executor) {
189
304
  const responseText = isStructuredOutput
190
305
  ? collapseRepeatedStructuredJsonText(streamed.responseText)
191
306
  : streamed.responseText;
307
+ const [structuredOutput, usage, finishReason, providerMetadata, requestStatus] = await waitForPostResponseFinalization(Promise.all([
308
+ options.responseOutput != null ? resolveOptionalStructuredOutput(handle.output) : undefined,
309
+ streamed.usage != null ? streamed.usage : resolveOptionalValue(handle.usage),
310
+ resolveOptionalValue(handle.finishReason),
311
+ resolveOptionalValue(handle.providerMetadata),
312
+ resolveOptionalValue(handle.requestStatus),
313
+ ]), options);
192
314
  return {
193
315
  responseText,
194
- structuredOutput: options.responseOutput != null ? await resolveOptionalStructuredOutput(handle.output) : undefined,
316
+ structuredOutput,
195
317
  functionCalls: streamed.functionCalls,
196
- usage: streamed.usage ?? (await resolveOptionalValue(handle.usage)),
318
+ usage,
197
319
  reasoning: streamed.reasoning,
198
- finishReason: await resolveOptionalValue(handle.finishReason),
199
- providerMetadata: await resolveOptionalValue(handle.providerMetadata),
200
- requestStatus: await resolveOptionalValue(handle.requestStatus),
320
+ finishReason,
321
+ providerMetadata,
322
+ requestStatus,
201
323
  };
202
324
  }
203
325
  export async function streamChatV2(options) {
@@ -208,7 +330,7 @@ export async function generateChatV2(options) {
208
330
  const stepToolCalls = attachGenerateStepToolCallCollector(args);
209
331
  let result;
210
332
  try {
211
- result = await (options.executeGenerate ?? defaultGenerateExecutor)(args);
333
+ result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
212
334
  }
213
335
  catch (error) {
214
336
  const recovered = recoverGenerateStructuredOutputError(error, options, stepToolCalls);
@@ -219,15 +341,25 @@ export async function generateChatV2(options) {
219
341
  }
220
342
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
221
343
  const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
222
- const finishReason = await resolveOptionalValue(result.finishReason);
344
+ const [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await waitForPostResponseFinalization((async () => {
345
+ const finishReason = await resolveOptionalValue(result.finishReason);
346
+ const [structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await Promise.all([
347
+ resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
348
+ (async () => (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)))(),
349
+ resolveGenerateReasoning(result),
350
+ resolveOptionalValue(result.providerMetadata),
351
+ resolveOptionalValue(result.requestStatus),
352
+ ]);
353
+ return [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus];
354
+ })(), options);
223
355
  return {
224
356
  responseText,
225
- structuredOutput: await resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
357
+ structuredOutput,
226
358
  functionCalls: toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls),
227
- usage: (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)),
228
- reasoning: await resolveGenerateReasoning(result),
359
+ usage,
360
+ reasoning,
229
361
  finishReason,
230
- providerMetadata: await resolveOptionalValue(result.providerMetadata),
231
- requestStatus: await resolveOptionalValue(result.requestStatus),
362
+ providerMetadata,
363
+ requestStatus,
232
364
  };
233
365
  }
@@ -1,5 +1,5 @@
1
1
  import { nanoid } from 'nanoid/non-secure';
2
- import { calculateChatV2Cost, getChatV2ModelInfo } from './modelRegistry.js';
2
+ import { calculateChatV2UsageCost, getChatV2ModelInfo } from './modelRegistry.js';
3
3
  function toUsageNumber(value) {
4
4
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
5
5
  }
@@ -43,7 +43,7 @@ function normalizeObservedUsage(rawUsage) {
43
43
  (promptTokens != null && completionTokens != null ? promptTokens + completionTokens : undefined);
44
44
  const cacheReadTokens = rawUsage.inputTokenDetails?.cacheReadTokens;
45
45
  const cacheWriteTokens = rawUsage.inputTokenDetails?.cacheWriteTokens;
46
- const cachedTokens = cacheReadTokens != null && cacheWriteTokens != null ? cacheReadTokens + cacheWriteTokens : undefined;
46
+ const cachedTokens = cacheReadTokens == null && cacheWriteTokens == null ? undefined : (cacheReadTokens ?? 0) + (cacheWriteTokens ?? 0);
47
47
  const reasoningTokens = rawUsage.outputTokenDetails?.reasoningTokens;
48
48
  const normalized = {
49
49
  ...(promptTokens == null ? {} : { promptTokens }),
@@ -109,8 +109,9 @@ export function notifyChatV2CallFinished(options, params) {
109
109
  const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
110
  const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
111
  const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
- const calculatedCost = modelInfo != null && normalizedUsage?.promptTokens != null && normalizedUsage.completionTokens != null
113
- ? safelyRead(() => calculateChatV2Cost(options.provider, options.modelId, normalizedUsage.promptTokens, normalizedUsage.completionTokens))
112
+ const hasKnownPricing = modelInfo?.cost != null;
113
+ const calculatedCost = hasKnownPricing
114
+ ? safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage))
114
115
  : undefined;
115
116
  const costUsd = toUsageNumber(calculatedCost);
116
117
  const finishReason = safelyRead(() => params.result?.finishReason) ??
@@ -119,19 +120,24 @@ export function notifyChatV2CallFinished(options, params) {
119
120
  callId: params.callId,
120
121
  attemptIndex: params.attemptIndex,
121
122
  ...(options.profileIndex == null ? {} : { profileIndex: options.profileIndex }),
123
+ ...(options.profileHealthKey == null ? {} : { profileHealthKey: options.profileHealthKey }),
124
+ ...(options.profileHealthState == null ? {} : { profileHealthState: options.profileHealthState }),
122
125
  ...(options.roundIndex == null ? {} : { roundIndex: options.roundIndex }),
123
126
  nodeId,
124
127
  processId,
125
128
  provider: options.provider,
126
129
  model: options.modelId,
130
+ ...(options.customProviderApi == null ? {} : { customProviderApi: options.customProviderApi }),
127
131
  outcome: params.outcome,
128
132
  ...(finishReason == null ? {} : { finishReason }),
129
133
  ...(rawUsage == null ? {} : { rawUsage }),
130
134
  ...(normalizedUsage == null ? {} : { normalizedUsage }),
131
135
  pricing: {
132
- status: modelInfo == null ? 'unknown' : 'known',
136
+ status: hasKnownPricing ? 'known' : 'unknown',
133
137
  ...(costUsd == null ? {} : { costUsd }),
134
138
  },
139
+ ...(params.startedAt == null ? {} : { startedAt: params.startedAt }),
140
+ ...(params.durationMs == null ? {} : { durationMs: params.durationMs }),
135
141
  };
136
142
  try {
137
143
  containUnexpectedObserverPromise(observer(event));
@@ -0,0 +1,93 @@
1
+ export const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {
2
+ openai: {
3
+ programmaticName: 'openAiApiKey',
4
+ environmentVariableName: 'OPENAI_API_KEY',
5
+ },
6
+ anthropic: {
7
+ programmaticName: 'anthropicApiKey',
8
+ environmentVariableName: 'ANTHROPIC_API_KEY',
9
+ },
10
+ google: {
11
+ programmaticName: 'googleApiKey',
12
+ environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',
13
+ },
14
+ };
15
+ const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
16
+ const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
17
+ export function isChatV2BuiltInProvider(provider) {
18
+ return Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider);
19
+ }
20
+ export function isValidChatV2ProgrammaticCredentialName(name) {
21
+ return programmaticNamePattern.test(name);
22
+ }
23
+ export function isValidChatV2EnvironmentCredentialName(name) {
24
+ return environmentVariableNamePattern.test(name);
25
+ }
26
+ export function getChatV2DefaultCredentialNames(provider) {
27
+ return { ...CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider] };
28
+ }
29
+ export function getChatV2CredentialNamesForDisplay(provider, value) {
30
+ try {
31
+ return normalizeChatV2CredentialNames(provider, value);
32
+ }
33
+ catch {
34
+ return getChatV2DefaultCredentialNames(provider);
35
+ }
36
+ }
37
+ export function normalizeChatV2CredentialNames(provider, value) {
38
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
39
+ throw new Error(`${provider} API key names must be an object.`);
40
+ }
41
+ const raw = value;
42
+ if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
43
+ throw new Error(`${provider} programmatic API key name must be a string.`);
44
+ }
45
+ if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
46
+ throw new Error(`${provider} API key environment variable must be a string.`);
47
+ }
48
+ const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
49
+ const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
50
+ const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
51
+ if (!isValidChatV2ProgrammaticCredentialName(programmaticName)) {
52
+ throw new Error(`${provider} programmatic API key name must be a JavaScript-style identifier (letters, digits, _, or $, and not starting with a digit).`);
53
+ }
54
+ if (!isValidChatV2EnvironmentCredentialName(environmentVariableName)) {
55
+ throw new Error(`${provider} API key environment variable must contain only letters, digits, and _, and must not start with a digit.`);
56
+ }
57
+ return { programmaticName, environmentVariableName };
58
+ }
59
+ export function normalizeChatV2CredentialNamesByProvider(value) {
60
+ if (value == null)
61
+ return undefined;
62
+ if (typeof value !== 'object' || Array.isArray(value)) {
63
+ throw new Error('Built-in provider API key names must be an object.');
64
+ }
65
+ const raw = value;
66
+ const unsupportedProvider = Object.keys(raw).find((provider) => !Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider));
67
+ if (unsupportedProvider) {
68
+ throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);
69
+ }
70
+ const normalized = {};
71
+ for (const provider of ['openai', 'anthropic', 'google']) {
72
+ if (raw[provider] != null) {
73
+ normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);
74
+ }
75
+ }
76
+ return Object.keys(normalized).length === 0 ? undefined : normalized;
77
+ }
78
+ export function isDefaultChatV2CredentialNames(provider, names) {
79
+ const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
80
+ return (names.programmaticName === defaults.programmaticName &&
81
+ names.environmentVariableName === defaults.environmentVariableName);
82
+ }
83
+ export function getNonDefaultChatV2CredentialNames(provider, namesByProvider) {
84
+ if (!isChatV2BuiltInProvider(provider) || namesByProvider?.[provider] == null)
85
+ return undefined;
86
+ try {
87
+ const names = normalizeChatV2CredentialNames(provider, namesByProvider[provider]);
88
+ return isDefaultChatV2CredentialNames(provider, names) ? undefined : names;
89
+ }
90
+ catch {
91
+ return undefined;
92
+ }
93
+ }
@@ -1,6 +1,10 @@
1
1
  import stableStringify from 'safe-stable-stringify';
2
+ import CryptoJS from 'crypto-js';
3
+ import { normalizeOpenAICompatibleEndpoint } from './providerOptions.js';
4
+ import { parseCustomProviderApi } from './customProviderApi.js';
2
5
  export function buildLLMChatV2EditorCacheKey(parts) {
3
- return stableStringify(parts) ?? '';
6
+ const { cacheVersion = 3, ...keyParts } = parts;
7
+ return stableStringify({ cacheVersion, ...keyParts }) ?? '';
4
8
  }
5
9
  function cloneEditorCacheValue(value, seen = new WeakMap()) {
6
10
  if (value == null || typeof value !== 'object') {
@@ -41,29 +45,56 @@ function fingerprintSecret(secret) {
41
45
  if (!secret) {
42
46
  return undefined;
43
47
  }
44
- let hash = 2166136261;
45
- for (let i = 0; i < secret.length; i++) {
46
- hash ^= secret.charCodeAt(i);
47
- hash = Math.imul(hash, 16777619);
48
- }
49
- return `${secret.length}:${(hash >>> 0).toString(36)}`;
48
+ // Cache keys stay in-memory, but provider credentials and header values must
49
+ // not be recoverable from them. SHA-256 also avoids FNV's easy collisions.
50
+ return `sha256:${CryptoJS.SHA256(secret).toString(CryptoJS.enc.Hex)}`;
50
51
  }
51
52
  function fingerprintProviderConfigForCache(config) {
52
- if (config.headers == null) {
53
+ if (config.headers == null && config.endpointQuery == null) {
53
54
  return config;
54
55
  }
55
56
  return {
56
57
  ...config,
57
- headers: Object.fromEntries(Object.entries(config.headers).map(([key, value]) => [key, fingerprintSecret(value) ?? ''])),
58
+ ...(config.headers == null
59
+ ? {}
60
+ : {
61
+ headers: Object.fromEntries(Object.entries(config.headers).map(([key, value]) => [key, fingerprintSecret(value) ?? ''])),
62
+ }),
63
+ ...(config.endpointQuery == null
64
+ ? {}
65
+ : {
66
+ endpointQuery: config.endpointQuery.map(([key, value]) => [key, fingerprintSecret(value) ?? '']),
67
+ }),
58
68
  };
59
69
  }
70
+ function fingerprintCustomProviderBaseURL(value) {
71
+ if (!value.trim()) {
72
+ return '';
73
+ }
74
+ try {
75
+ const endpoint = normalizeOpenAICompatibleEndpoint(value);
76
+ return (stableStringify({
77
+ baseURL: endpoint.baseURL,
78
+ endpointQuery: endpoint.endpointQuery.map(([key, queryValue]) => [key, fingerprintSecret(queryValue) ?? '']),
79
+ }) ?? '');
80
+ }
81
+ catch {
82
+ // Profile candidates are resolved lazily so a malformed primary URL can
83
+ // fall through to the next profile. Cache fingerprinting must neither
84
+ // pre-empt that recovery nor retain the malformed URL verbatim.
85
+ return `invalid-url:${fingerprintSecret(value)}`;
86
+ }
87
+ }
60
88
  function fingerprintNodeDataForCache(data) {
61
89
  const isCustomProvider = data.provider === 'custom';
62
90
  return {
63
91
  ...data,
64
92
  baseURL: '',
65
93
  useBaseURLInput: false,
66
- customProviderBaseURL: isCustomProvider ? data.customProviderBaseURL : '',
94
+ customProviderApi: isCustomProvider ? parseCustomProviderApi(data.customProviderApi) : 'completions',
95
+ customProviderBaseURL: isCustomProvider && !data.useCustomProviderBaseURLInput
96
+ ? fingerprintCustomProviderBaseURL(data.customProviderBaseURL)
97
+ : '',
67
98
  useCustomProviderBaseURLInput: isCustomProvider ? data.useCustomProviderBaseURLInput : false,
68
99
  extraProviderOptions: data.useExtraProviderOptionsInput ? '' : fingerprintSecret(data.extraProviderOptions) ?? '',
69
100
  headers: (data.headers ?? []).map(({ key, value }) => ({
@@ -72,11 +103,11 @@ function fingerprintNodeDataForCache(data) {
72
103
  })),
73
104
  };
74
105
  }
75
- function fingerprintProviderOptionsForCache(providerOptions) {
76
- if (providerOptions == null) {
106
+ function fingerprintRuntimeValueForCache(value) {
107
+ if (value == null) {
77
108
  return undefined;
78
109
  }
79
- return fingerprintSecret(stableStringify(providerOptions) ?? '');
110
+ return fingerprintSecret(stableStringify(value) ?? '');
80
111
  }
81
112
  function fingerprintProfileChainForCache(data, profiles) {
82
113
  if (profiles == null) {
@@ -111,14 +142,10 @@ export function resolveLLMChatV2EditorCache(params) {
111
142
  functions: params.functions,
112
143
  generationParameters: params.generationParameters,
113
144
  responseFormatParameters: params.responseFormatParameters,
114
- providerOptions: fingerprintProviderOptionsForCache(params.providerOptions),
145
+ providerOptions: fingerprintRuntimeValueForCache(params.providerOptions),
146
+ requestBodyOverlay: fingerprintRuntimeValueForCache(params.requestBodyOverlay),
115
147
  toolChoice: params.toolChoice,
116
- profileChain: params.profileChain == null
117
- ? undefined
118
- : {
119
- inputWasArray: params.profileChainUsesArray ?? false,
120
- profiles: fingerprintProfileChainForCache(params.data, params.profileChain),
121
- },
148
+ profileChain: params.profileChain == null ? undefined : fingerprintProfileChainForCache(params.data, params.profileChain),
122
149
  });
123
150
  return {
124
151
  cacheKey,
@@ -9,10 +9,6 @@ const STATUS_TEXT = {
9
9
  422: 'Unprocessable Entity',
10
10
  429: 'Rate Limited',
11
11
  };
12
- function compact(value, maxLength = 500) {
13
- const normalized = value.replace(/\s+/g, ' ').trim();
14
- return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 3)}...` : normalized;
15
- }
16
12
  function isRecord(value) {
17
13
  if (value == null || typeof value !== 'object') {
18
14
  return false;
@@ -37,13 +33,13 @@ function stringifyProviderValue(value) {
37
33
  return undefined;
38
34
  }
39
35
  if (typeof value === 'string') {
40
- return compact(value);
36
+ return value;
41
37
  }
42
38
  if (typeof value === 'number' || typeof value === 'boolean') {
43
39
  return String(value);
44
40
  }
45
41
  try {
46
- return compact(JSON.stringify(value));
42
+ return JSON.stringify(value);
47
43
  }
48
44
  catch {
49
45
  return undefined;
@@ -71,7 +67,7 @@ function parseResponseBodyMessage(responseBody) {
71
67
  return findProviderMessage(JSON.parse(responseBody));
72
68
  }
73
69
  catch {
74
- return compact(responseBody);
70
+ return responseBody;
75
71
  }
76
72
  }
77
73
  function getProviderMessage(error, seen = new Set()) {
@@ -108,15 +104,7 @@ function getProviderMessage(error, seen = new Set()) {
108
104
  return findProviderMessage(error);
109
105
  }
110
106
  function formatEndpoint(url) {
111
- try {
112
- const parsed = new URL(url);
113
- parsed.search = '';
114
- parsed.hash = '';
115
- return parsed.toString();
116
- }
117
- catch {
118
- return compact(url.split(/[?#]/, 1)[0] ?? url);
119
- }
107
+ return url;
120
108
  }
121
109
  function getApiCallRecommendation(statusCode, context) {
122
110
  switch (statusCode) {
@@ -224,7 +212,7 @@ function formatProviderFetchError(error, context) {
224
212
  `Model: ${context.modelId}`,
225
213
  'The browser/runtime fetch layer hid the provider response. In Browser executor mode this commonly happens because of CORS or a provider-side request rejection.',
226
214
  'Check the API key source, provider URL, and network access. Use the Node executor when you need the exact provider HTTP status.',
227
- compact(error.message),
215
+ error.message,
228
216
  ].join('\n');
229
217
  }
230
218
  function formatApiCallError(error, context) {
@@ -259,7 +247,7 @@ function formatKnownSdkError(error, context) {
259
247
  'LLM API key could not be loaded.',
260
248
  `Provider: ${getChatV2ProviderLabel(context.provider)}`,
261
249
  'Check the API key source and configured provider credentials.',
262
- compact(error.message),
250
+ error.message,
263
251
  ].join('\n');
264
252
  }
265
253
  if (hasSdkErrorName(error, 'UnsupportedFunctionalityError')) {
@@ -277,7 +265,7 @@ function formatKnownSdkError(error, context) {
277
265
  `Provider: ${getChatV2ProviderLabel(context.provider)}`,
278
266
  `Model: ${context.modelId}`,
279
267
  'Check the response format settings and provider response.',
280
- compact(error.message),
268
+ error.message,
281
269
  ].join('\n');
282
270
  }
283
271
  return undefined;
@@ -1,4 +1,4 @@
1
- import { isChatV2StructuredResponseFormat, } from './chatV2ResponseFormat.js';
1
+ import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
2
2
  export const LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY = {
3
3
  title: '"Tool use" conflicts with "Structured outputs"',
4
4
  paragraphs: [