@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,11 +1,11 @@
1
1
  import { inferType } from '../../utils/coerceType.js';
2
2
  import { createAssistantMessagesOutput } from '../chat/streamChatResponse.js';
3
- import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
4
- import { calculateChatV2Cost } from './modelRegistry.js';
5
- import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError, } from './chatV2Types.js';
6
- const CHAT_V2_REQUEST_STATUS_PORT_ID = 'requestStatus';
7
- const CHAT_V2_REQUEST_ERROR_PORT_ID = 'requestError';
3
+ import { materializeLLMResponse } from './llmResponseMaterializer.js';
4
+ import { calculateChatV2UsageCost } from './modelRegistry.js';
5
+ import { isChatV2FiniteNonNegativeNumber } from './chatV2UsageAccounting.js';
6
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2ResponseBody, } from './chatV2Types.js';
8
7
  const CHAT_V2_REQUEST_BODY_PORT_ID = 'requestBody';
8
+ const CHAT_V2_RESPONSE_BODY_PORT_ID = 'responseBody';
9
9
  function toFunctionCallOutputValue(functionCall) {
10
10
  let argumentsValue = functionCall.lastParsedArguments;
11
11
  if (argumentsValue == null) {
@@ -32,34 +32,38 @@ export function normalizeChatV2Usage(usage, options) {
32
32
  if (usage == null) {
33
33
  return undefined;
34
34
  }
35
- const promptTokens = usage.inputTokens ?? 0;
36
- const completionTokens = usage.outputTokens ?? 0;
37
- const totalTokens = usage.totalTokens ?? promptTokens + completionTokens;
38
- const cachedTokens = (usage.inputTokenDetails?.cacheReadTokens ?? 0) + (usage.inputTokenDetails?.cacheWriteTokens ?? 0);
39
- const reasoningTokens = usage.outputTokenDetails?.reasoningTokens ?? 0;
35
+ // Provider usage metadata crosses a runtime boundary and can be malformed.
36
+ // Keep the node's portable Usage output aligned with the physical-call
37
+ // observer: only finite, non-negative token counts are meaningful.
38
+ const promptTokens = isChatV2FiniteNonNegativeNumber(usage.inputTokens) ? usage.inputTokens : 0;
39
+ const completionTokens = isChatV2FiniteNonNegativeNumber(usage.outputTokens) ? usage.outputTokens : 0;
40
+ const totalTokens = isChatV2FiniteNonNegativeNumber(usage.totalTokens)
41
+ ? usage.totalTokens
42
+ : promptTokens + completionTokens;
43
+ const cachedTokens = (isChatV2FiniteNonNegativeNumber(usage.inputTokenDetails?.cacheReadTokens)
44
+ ? usage.inputTokenDetails.cacheReadTokens
45
+ : 0) +
46
+ (isChatV2FiniteNonNegativeNumber(usage.inputTokenDetails?.cacheWriteTokens)
47
+ ? usage.inputTokenDetails.cacheWriteTokens
48
+ : 0);
49
+ const reasoningTokens = isChatV2FiniteNonNegativeNumber(usage.outputTokenDetails?.reasoningTokens)
50
+ ? usage.outputTokenDetails.reasoningTokens
51
+ : 0;
40
52
  return {
41
53
  promptTokens,
42
54
  completionTokens,
43
55
  totalTokens,
44
56
  cachedTokens,
45
57
  reasoningTokens,
46
- totalCost: calculateChatV2Cost(options.provider, options.modelId, promptTokens, completionTokens),
58
+ totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage),
47
59
  };
48
60
  }
49
- function tryParseStructuredResponseText(response) {
50
- try {
51
- return JSON.parse(response);
52
- }
53
- catch {
54
- return undefined;
55
- }
56
- }
57
- function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
58
- if (!isChatV2StructuredResponseFormat(responseFormat)) {
59
- return { type: 'string', value: response };
60
- }
61
- const parsedOutput = structuredOutput !== undefined ? structuredOutput : tryParseStructuredResponseText(response);
62
- return parsedOutput !== undefined ? inferType(parsedOutput) : { type: 'string', value: response };
61
+ export function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
62
+ return materializeLLMResponse({
63
+ rawText: response,
64
+ structuredOutput,
65
+ responseFormat,
66
+ }).value;
63
67
  }
64
68
  function createChatV2ReasoningOutput(reasoning) {
65
69
  if (Array.isArray(reasoning)) {
@@ -79,21 +83,23 @@ function createChatV2ReasoningOutput(reasoning) {
79
83
  }
80
84
  : createControlFlowExcludedOutput();
81
85
  }
82
- function createChatV2RequestBodyOutput(requestBodies) {
83
- if (requestBodies == null || requestBodies.length === 0) {
86
+ function createChatV2CapturedBodiesOutput(bodies) {
87
+ if (bodies == null || bodies.length === 0) {
84
88
  return createControlFlowExcludedOutput();
85
89
  }
86
- return inferType(requestBodies.length === 1 ? requestBodies[0] : requestBodies);
90
+ return inferType(bodies.length === 1 ? bodies[0] : bodies);
87
91
  }
88
- function createChatV2RetryAttemptOutput(type, values) {
89
- return values.length > 0
90
- ? {
91
- type,
92
- value: values,
93
- }
94
- : createControlFlowExcludedOutput();
92
+ export function createChatV2CapturedBodyOutputs(options) {
93
+ const outputs = {};
94
+ if (shouldOutputChatV2RequestBody(options)) {
95
+ outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2CapturedBodiesOutput(options.requestBodies);
96
+ }
97
+ if (shouldOutputChatV2ResponseBody(options)) {
98
+ outputs[CHAT_V2_RESPONSE_BODY_PORT_ID] = createChatV2CapturedBodiesOutput(options.responseBodies);
99
+ }
100
+ return outputs;
95
101
  }
96
- export function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, outputRequestStatus, outputRequestError, outputRequestBody, includeFunctionCalls, functionCallMode, retryOnNon200, responseFormat, }) {
102
+ export function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestBodies, responseBodies, outputUsage, outputReasoning, outputRequestBody, outputResponseBody, includeFunctionCalls, functionCallMode, responseFormat, }) {
97
103
  const outputs = {
98
104
  ['response']: createChatV2ResponseOutput(response, structuredOutput, responseFormat),
99
105
  ['in-messages']: { type: 'chat-message[]', value: requestMessages },
@@ -126,77 +132,11 @@ export function createChatV2CommonOutputs({ requestMessages, response, structure
126
132
  if (outputReasoning) {
127
133
  outputs['reasoning'] = createChatV2ReasoningOutput(reasoning);
128
134
  }
129
- if (outputRequestStatus) {
130
- if (retryOnNon200) {
131
- outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = createChatV2RetryAttemptOutput('number[]', requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]);
132
- }
133
- else {
134
- outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = {
135
- type: 'number',
136
- value: requestStatus ?? 200,
137
- };
138
- }
139
- }
140
- if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
141
- if (retryOnNon200) {
142
- outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput('string[]', requestErrors);
143
- }
144
- else {
145
- outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] =
146
- responseError != null
147
- ? {
148
- type: 'string',
149
- value: responseError,
150
- }
151
- : createControlFlowExcludedOutput();
152
- }
153
- }
154
- if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
155
- outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
156
- }
157
- return outputs;
158
- }
159
- export function createChatV2ProviderFailureOutputs({ requestMessages, responseStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, outputRequestStatus, outputRequestError, outputRequestBody, includeFunctionCalls, retryOnNon200, }) {
160
- const outputs = {
161
- ['response']: createControlFlowExcludedOutput(),
162
- ['in-messages']: {
163
- type: 'chat-message[]',
164
- value: requestMessages,
165
- },
166
- ['all-messages']: {
167
- type: 'chat-message[]',
168
- value: requestMessages,
169
- },
170
- };
171
- if (outputRequestStatus) {
172
- outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = retryOnNon200
173
- ? createChatV2RetryAttemptOutput('number[]', requestStatuses)
174
- : responseStatus == null
175
- ? createControlFlowExcludedOutput()
176
- : {
177
- type: 'number',
178
- value: responseStatus,
179
- };
180
- }
181
- if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
182
- outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = retryOnNon200
183
- ? createChatV2RetryAttemptOutput('string[]', requestErrors)
184
- : {
185
- type: 'string',
186
- value: responseError,
187
- };
188
- }
189
- if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
190
- outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
191
- }
192
- if (includeFunctionCalls) {
193
- outputs['function-calls'] = createControlFlowExcludedOutput();
194
- }
195
- if (outputUsage) {
196
- outputs['usage'] = createControlFlowExcludedOutput();
197
- }
198
- if (outputReasoning) {
199
- outputs['reasoning'] = createControlFlowExcludedOutput();
200
- }
135
+ Object.assign(outputs, createChatV2CapturedBodyOutputs({
136
+ requestBodies,
137
+ responseBodies,
138
+ outputRequestBody,
139
+ outputResponseBody,
140
+ }));
201
141
  return outputs;
202
142
  }
@@ -2,51 +2,39 @@ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMes
2
2
  import { generateChatV2, streamChatV2 } from './aiSdkBridge.js';
3
3
  import { createObservedChatV2CallId, notifyChatV2CallFinished } from './chatV2CallObserver.js';
4
4
  import { chatMessagesToModelMessages } from './messageConverter.js';
5
+ import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
5
6
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
6
7
  import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
7
- import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
- import { waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
9
- import { createChatV2CommonOutputs, createChatV2ProviderFailureOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
10
- class ChatV2RetryFailure extends Error {
11
- error;
12
- requestStatuses;
13
- requestErrors;
14
- constructor(error, requestStatuses, requestErrors) {
15
- super('Chat v2 retry attempts failed');
16
- this.error = error;
17
- this.requestStatuses = requestStatuses;
18
- this.requestErrors = requestErrors;
19
- this.name = 'ChatV2RetryFailure';
20
- }
21
- }
22
- function isChatV2RetryFailure(error) {
23
- return error instanceof ChatV2RetryFailure;
8
+ import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
9
+ import { createLLMChatV2RetryAbortError, waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
10
+ import { createChatV2CommonOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
11
+ import { materializeLLMResponse } from './llmResponseMaterializer.js';
12
+ /** Identifies legacy pipeline results that represent a terminal provider failure. */
13
+ export function isChatV2PipelineProviderFailureResult(result) {
14
+ return result.terminalOutcome === 'provider-failure';
24
15
  }
25
- function getProviderFailureMessage(error) {
26
- try {
27
- if (error instanceof Error && typeof error.message === 'string') {
28
- return error.message;
29
- }
30
- }
31
- catch {
32
- return 'Provider request failed with unreadable error metadata.';
33
- }
34
- try {
35
- return String(error);
36
- }
37
- catch {
38
- return 'Provider request failed with unreadable error metadata.';
16
+ export class ChatV2ResponseValidationError extends Error {
17
+ responseDataType;
18
+ constructor(responseDataType) {
19
+ super('LLM profile response validation failed.\n' +
20
+ 'Response format: JSON schema\n' +
21
+ `Parsed Response type: ${responseDataType}\n` +
22
+ 'The provider request succeeded, but the final value prepared for the Response port is not an object. ' +
23
+ 'JSON schema response format requires an object, so Rivet rejected this LLM profile. ' +
24
+ 'Retry on non-200 does not apply to this validation failure.');
25
+ this.responseDataType = responseDataType;
26
+ this.name = 'ChatV2ResponseValidationError';
39
27
  }
40
28
  }
29
+ export function isChatV2ResponseValidationError(error) {
30
+ return error instanceof ChatV2ResponseValidationError;
31
+ }
41
32
  function buildNon200StatusError(statusCode) {
42
33
  const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
43
34
  error.name = 'AI_APICallError';
44
35
  error.statusCode = statusCode;
45
36
  return error;
46
37
  }
47
- function normalizeProviderFailureMessage(error, options) {
48
- return getProviderFailureMessage(normalizeProviderFailure(error, options));
49
- }
50
38
  function normalizeProviderFailure(error, options) {
51
39
  try {
52
40
  return normalizeChatV2ProviderError(error, {
@@ -58,9 +46,6 @@ function normalizeProviderFailure(error, options) {
58
46
  return error;
59
47
  }
60
48
  }
61
- function normalizeProviderFailureMessages(errors, options) {
62
- return errors.map((error) => normalizeProviderFailureMessage(error, options));
63
- }
64
49
  function notifyProviderAttempt(options, attempt) {
65
50
  try {
66
51
  options.onProviderAttempt?.(attempt);
@@ -70,19 +55,47 @@ function notifyProviderAttempt(options, attempt) {
70
55
  }
71
56
  }
72
57
  async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
73
- const requestStatuses = [];
74
- const requestErrors = [];
58
+ const prepareProviderRetry = async () => {
59
+ try {
60
+ await options.onBeforeProviderRetry?.(retryPlan.cooldownMs);
61
+ }
62
+ catch {
63
+ // Circuit-health persistence is observational and must fail open.
64
+ }
65
+ };
75
66
  for (let attempt = 0;; attempt++) {
76
67
  const callId = createObservedChatV2CallId(options);
68
+ const callStartedAt = Date.now();
77
69
  let callWasObserved = false;
70
+ const attemptController = new AbortController();
71
+ const abortAttemptFromCaller = () => attemptController.abort(signal.reason);
72
+ if (signal.aborted) {
73
+ abortAttemptFromCaller();
74
+ }
75
+ else {
76
+ signal.addEventListener('abort', abortAttemptFromCaller, { once: true });
77
+ }
78
78
  try {
79
- const result = transportMode === 'generate' ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
79
+ const attemptChatOptions = {
80
+ ...chatOptions,
81
+ abortSignal: attemptController.signal,
82
+ firstOutputTimeoutMs: options.firstOutputTimeoutMs,
83
+ streamInactivityTimeoutMs: options.streamInactivityTimeoutMs,
84
+ onStreamActivity: options.onStreamActivity,
85
+ onTimeout: (error) => attemptController.abort(error),
86
+ };
87
+ const result = transportMode === 'generate'
88
+ ? await generateChatV2(attemptChatOptions)
89
+ : await streamChatV2(attemptChatOptions);
90
+ await options.responseBodyCapture?.flush();
80
91
  const statusCode = result.requestStatus ?? 200;
81
92
  notifyChatV2CallFinished(options, {
82
93
  callId,
83
94
  attemptIndex: attempt,
84
95
  outcome: statusCode === 200 ? 'success' : 'provider-failure',
85
96
  result,
97
+ startedAt: callStartedAt,
98
+ durationMs: Math.max(0, Date.now() - callStartedAt),
86
99
  });
87
100
  callWasObserved = true;
88
101
  notifyProviderAttempt(options, {
@@ -91,102 +104,64 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
91
104
  status: statusCode,
92
105
  ...(statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }),
93
106
  });
94
- if (retryPlan.enabled) {
95
- requestStatuses.push(statusCode);
96
- }
97
107
  if (!retryPlan.enabled || statusCode === 200) {
98
- return { result, requestStatuses, requestErrors };
108
+ return { result };
99
109
  }
100
110
  const responseError = buildNon200StatusError(statusCode);
101
- requestErrors.push(responseError);
102
111
  if (attempt >= retryPlan.repeatTimes) {
103
- return { result, requestStatuses, requestErrors, responseError };
112
+ return { result, responseError };
104
113
  }
114
+ await prepareProviderRetry();
105
115
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
106
116
  }
107
- catch (error) {
117
+ catch (caughtError) {
118
+ const error = !signal.aborted && isChatV2ProviderTimeoutError(attemptController.signal.reason)
119
+ ? attemptController.signal.reason
120
+ : caughtError;
121
+ await options.responseBodyCapture?.flush({
122
+ waitForPending: !signal.aborted && !isChatV2ProviderTimeoutError(error),
123
+ });
108
124
  if (!callWasObserved) {
109
125
  notifyChatV2CallFinished(options, {
110
126
  callId,
111
127
  attemptIndex: attempt,
112
128
  outcome: signal.aborted ? 'aborted' : 'provider-failure',
113
129
  error,
130
+ startedAt: callStartedAt,
131
+ durationMs: Math.max(0, Date.now() - callStartedAt),
114
132
  });
115
133
  }
116
134
  const statusCode = getChatV2ProviderErrorStatusCode(error);
117
135
  notifyProviderAttempt(options, {
118
136
  attemptIndex: attempt,
119
- outcome: 'provider-failure',
137
+ outcome: signal.aborted ? 'aborted' : 'provider-failure',
120
138
  ...(statusCode == null ? {} : { status: statusCode }),
121
139
  error,
122
140
  });
123
- if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
141
+ if (signal.aborted) {
142
+ // The provider may reject concurrently with graph cancellation. The
143
+ // cancellation wins: it must neither retry nor masquerade as a
144
+ // provider failure to profile fallback and run activity.
145
+ throw createLLMChatV2RetryAbortError();
146
+ }
147
+ if (isChatV2ProviderTimeoutError(error) || !retryPlan.enabled || statusCode == null || statusCode === 200) {
124
148
  throw error;
125
149
  }
126
- requestStatuses.push(statusCode);
127
- requestErrors.push(error);
128
150
  if (attempt >= retryPlan.repeatTimes) {
129
- throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
151
+ throw error;
130
152
  }
153
+ await prepareProviderRetry();
131
154
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
132
155
  }
156
+ finally {
157
+ signal.removeEventListener('abort', abortAttemptFromCaller);
158
+ }
133
159
  }
134
160
  }
135
- function buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors) {
136
- if (!plan.output.outputRequestStatus && !plan.output.outputRequestError) {
137
- return undefined;
138
- }
139
- const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
140
- if (statusCode == null && !isChatV2ProviderApiCallError(rawError) && !isChatV2ProviderFetchError(rawError)) {
141
- return undefined;
142
- }
143
- const responseError = getProviderFailureMessage(normalizedError);
144
- const retryRequestStatuses = plan.retry.enabled
145
- ? requestStatuses.length > 0
146
- ? requestStatuses
147
- : statusCode == null
148
- ? []
149
- : [statusCode]
150
- : [];
151
- const retryRequestErrors = plan.retry.enabled ? (requestErrors.length > 0 ? requestErrors : [responseError]) : [];
152
- const commonOutputs = createChatV2ProviderFailureOutputs({
153
- requestMessages,
154
- responseStatus: statusCode,
155
- responseError,
156
- requestStatuses: retryRequestStatuses,
157
- requestErrors: retryRequestErrors,
158
- requestBodies: options.requestBodies,
159
- outputUsage: plan.output.outputUsage,
160
- outputReasoning: plan.output.outputReasoning,
161
- outputRequestStatus: plan.output.outputRequestStatus,
162
- outputRequestError: plan.output.outputRequestError,
163
- outputRequestBody: plan.output.outputRequestBody,
164
- includeFunctionCalls: plan.output.includeFunctionCalls,
165
- retryOnNon200: plan.retry.enabled,
166
- });
167
- const allMessagesOutput = commonOutputs['all-messages'];
168
- if (allMessagesOutput?.type !== 'chat-message[]') {
169
- throw new Error('Chat v2 provider failure expected all-messages output to be chat-message[].');
170
- }
171
- return {
172
- commonOutputs,
173
- requestMessages,
174
- allMessages: allMessagesOutput.value,
175
- response: '',
176
- functionCalls: [],
177
- reasoning: '',
178
- usage: undefined,
179
- rawUsage: undefined,
180
- finishReason: undefined,
181
- providerMetadata: undefined,
182
- requestStatus: statusCode,
183
- };
184
- }
185
161
  /**
186
- * Runs one provider/model round without deciding whether a provider failure
187
- * should become diagnostic outputs or should advance an LLM Profile fallback
188
- * chain. Shared prompt/schema/tool construction errors deliberately continue
189
- * to throw: they are graph configuration errors, not a profile failure.
162
+ * Runs one provider/model round. Provider failures stay distinct from shared
163
+ * graph configuration errors so an LLM Profile fallback chain can advance to
164
+ * its next candidate; terminal failures always remain node errors.
190
165
  */
191
166
  export async function runChatV2PipelineExecution(options) {
192
167
  const requestMessages = prependSystemPrompt(coercePromptToChatMessages(options.prompt, { requirePrompt: true }), options.systemPrompt);
@@ -223,19 +198,14 @@ export async function runChatV2PipelineExecution(options) {
223
198
  functionCalls,
224
199
  usage: undefined,
225
200
  reasoning: '',
226
- requestStatus: undefined,
227
- responseError: undefined,
228
- requestStatuses: [],
229
- requestErrors: [],
230
201
  requestBodies: undefined,
202
+ responseBodies: undefined,
231
203
  outputUsage: false,
232
204
  outputReasoning: false,
233
- outputRequestStatus: false,
234
- outputRequestError: false,
235
205
  outputRequestBody: false,
206
+ outputResponseBody: false,
236
207
  includeFunctionCalls: plan.output.includeFunctionCalls,
237
208
  functionCallMode: plan.output.functionCallMode,
238
- retryOnNon200: false,
239
209
  responseFormat: undefined,
240
210
  }));
241
211
  },
@@ -245,28 +215,16 @@ export async function runChatV2PipelineExecution(options) {
245
215
  if (options.context.signal.aborted) {
246
216
  throw caughtError;
247
217
  }
248
- const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : undefined;
249
- const rawError = retryFailure?.error ?? caughtError;
250
218
  return {
251
219
  outcome: 'provider-failure',
252
220
  failure: {
253
- requestMessages,
254
221
  options,
255
- plan,
256
- normalizedError: normalizeProviderFailure(rawError, options),
257
- rawError,
258
- requestStatuses: retryFailure?.requestStatuses ?? [],
259
- requestErrors: normalizeProviderFailureMessages(retryFailure?.requestErrors ?? [], options),
222
+ normalizedError: normalizeProviderFailure(caughtError, options),
260
223
  },
261
224
  };
262
225
  }
263
226
  const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
264
- const requestStatuses = chatResponse.requestStatuses;
265
227
  const requestStatus = chatResponse.result.requestStatus ?? 200;
266
- const requestErrors = normalizeProviderFailureMessages(chatResponse.requestErrors, options);
267
- const responseError = chatResponse.responseError
268
- ? normalizeProviderFailureMessage(chatResponse.responseError, options)
269
- : undefined;
270
228
  const commonOutputs = createChatV2CommonOutputs({
271
229
  requestMessages,
272
230
  response: chatResponse.result.responseText,
@@ -274,19 +232,14 @@ export async function runChatV2PipelineExecution(options) {
274
232
  functionCalls: chatResponse.result.functionCalls,
275
233
  usage,
276
234
  reasoning: chatResponse.result.reasoning,
277
- requestStatus,
278
- responseError,
279
- requestStatuses,
280
- requestErrors,
281
235
  requestBodies: options.requestBodies,
236
+ responseBodies: options.responseBodies,
282
237
  outputUsage: plan.output.outputUsage,
283
238
  outputReasoning: plan.output.outputReasoning,
284
- outputRequestStatus: plan.output.outputRequestStatus,
285
- outputRequestError: plan.output.outputRequestError,
286
239
  outputRequestBody: plan.output.outputRequestBody,
240
+ outputResponseBody: plan.output.outputResponseBody,
287
241
  includeFunctionCalls: plan.output.includeFunctionCalls,
288
242
  functionCallMode: plan.output.functionCallMode,
289
- retryOnNon200: plan.retry.enabled,
290
243
  responseFormat: plan.request.responseFormat,
291
244
  });
292
245
  const allMessagesOutput = commonOutputs['all-messages'];
@@ -312,32 +265,31 @@ export async function runChatV2PipelineExecution(options) {
312
265
  return {
313
266
  outcome: 'provider-failure',
314
267
  failure: {
315
- requestMessages,
316
268
  options,
317
- plan,
318
269
  normalizedError: normalizeProviderFailure(rawError, options),
319
- rawError,
320
- requestStatuses: chatResponse.requestStatuses,
321
- requestErrors: normalizeProviderFailureMessages(chatResponse.requestErrors, options),
322
- diagnosticResult: result,
323
270
  },
324
271
  };
325
272
  }
273
+ // A tool-request round is not a terminal Response value. Auto-continuation
274
+ // will make another model call after delegated tools finish, so validate the
275
+ // value only once a provider round actually produces the final response.
276
+ if (plan.request.responseFormat === 'json_schema' && chatResponse.result.functionCalls.length === 0) {
277
+ const materialized = materializeLLMResponse({
278
+ rawText: chatResponse.result.responseText,
279
+ structuredOutput: chatResponse.result.structuredOutput,
280
+ responseFormat: plan.request.responseFormat,
281
+ });
282
+ if (materialized.validation === 'invalid') {
283
+ throw new ChatV2ResponseValidationError(materialized.value.type);
284
+ }
285
+ }
326
286
  return { outcome: 'success', result };
327
287
  }
328
288
  /**
329
- * Retains the established single-profile behavior: request-detail mode can
330
- * turn a provider failure into normal excluded outputs; otherwise it remains
331
- * a thrown normalized provider error.
289
+ * Terminal provider failures are node errors. The fallback coordinator may
290
+ * still catch this decision boundary and advance to a later LLM Profile.
332
291
  */
333
292
  export function materializeChatV2PipelineFailure(failure) {
334
- if (failure.diagnosticResult != null) {
335
- return failure.diagnosticResult;
336
- }
337
- const failureResult = buildProviderFailureResult(failure.requestMessages, failure.options, failure.plan, failure.normalizedError, failure.rawError, failure.requestStatuses, failure.requestErrors);
338
- if (failureResult != null) {
339
- return failureResult;
340
- }
341
293
  throw failure.normalizedError;
342
294
  }
343
295
  export async function runChatV2Pipeline(options) {
@@ -1,10 +1,39 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { createChatV2Model, resolveChatV2ProviderConfig, } from './providerOptions.js';
3
- function getStringSetting(settings, key) {
4
- const value = settings[key];
3
+ import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
4
+ import { isChatV2BuiltInProvider, normalizeChatV2CredentialNames, } from './chatV2CredentialNames.js';
5
+ function getNonEmptyString(value) {
5
6
  return typeof value === 'string' && value.trim() ? value : undefined;
6
7
  }
8
+ function getStringSetting(settings, key) {
9
+ return getNonEmptyString(settings[key]);
10
+ }
7
11
  function resolveConfiguredCredential(provider, context, options) {
12
+ if (isChatV2BuiltInProvider(provider) && options.providerApiKeyNames?.[provider] != null) {
13
+ const names = normalizeChatV2CredentialNames(provider, options.providerApiKeyNames[provider]);
14
+ const programmaticValue = getStringSetting(context.settings, names.programmaticName);
15
+ if (programmaticValue) {
16
+ return {
17
+ value: programmaticValue,
18
+ reference: { source: 'programmatic', name: names.programmaticName },
19
+ };
20
+ }
21
+ const pluginEnvValue = getNonEmptyString(context.settings.pluginEnv?.[names.environmentVariableName]);
22
+ if (pluginEnvValue) {
23
+ return {
24
+ value: pluginEnvValue,
25
+ reference: { source: 'environment', name: names.environmentVariableName },
26
+ };
27
+ }
28
+ const processValue = getNonEmptyString(globalThis.process?.env?.[names.environmentVariableName]);
29
+ if (processValue) {
30
+ return {
31
+ value: processValue,
32
+ reference: { source: 'environment', name: names.environmentVariableName },
33
+ };
34
+ }
35
+ throw new Error(`${provider} API key is not set. Pass ${names.programmaticName} programmatically or configure ${names.environmentVariableName}.`);
36
+ }
8
37
  switch (provider) {
9
38
  case 'openai': {
10
39
  const value = context.settings.openAiApiKey || context.settings.openAiKey || undefined;
@@ -79,18 +108,24 @@ export async function createResolvedChatV2Provider(options) {
79
108
  ...config,
80
109
  apiKey: options.credential.value,
81
110
  onRequestBody: options.onRequestBody,
111
+ onResponseBody: options.onResponseBody,
82
112
  transformRequestBody: options.transformRequestBody,
113
+ requestBodyOverlay: options.requestBodyOverlay,
114
+ customProviderApi: options.customProviderApi,
83
115
  });
84
116
  return {
85
117
  profile: {
86
118
  provider: options.provider,
87
119
  modelId: options.modelId,
120
+ ...(options.provider === 'custom' && options.customProviderApi != null
121
+ ? { customProviderApi: options.customProviderApi }
122
+ : {}),
88
123
  baseURL: config.baseURL,
89
124
  hasCustomHeaders: Object.keys(config.headers ?? {}).length > 0,
90
125
  credential: options.credential.reference,
91
126
  capabilities: {
92
- builtInTools: options.provider === 'openai' || options.provider === 'google',
93
- structuredOutput: true,
127
+ builtInTools: getChatV2ProviderCapabilities(options.provider).builtInTools,
128
+ structuredOutput: getChatV2ProviderCapabilities(options.provider).structuredOutput,
94
129
  },
95
130
  },
96
131
  model,
@@ -0,0 +1,9 @@
1
+ const providerCapabilities = {
2
+ openai: { builtInTools: true, parallelToolCalls: true, structuredOutput: true },
3
+ anthropic: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
4
+ google: { builtInTools: true, parallelToolCalls: false, structuredOutput: true },
5
+ custom: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
6
+ };
7
+ export function getChatV2ProviderCapabilities(provider) {
8
+ return providerCapabilities[provider];
9
+ }