@valerypopoff/rivet2-core 2.1.9 → 2.1.10

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 (155) hide show
  1. package/dist/cjs/bundle.cjs +3596 -1745
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +298 -21
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/AgentResponseTrace.js +448 -0
  7. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  8. package/dist/esm/model/GraphProcessor.js +151 -74
  9. package/dist/esm/model/NodeImpl.js +6 -0
  10. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  11. package/dist/esm/model/RecordingPlayer.js +164 -22
  12. package/dist/esm/model/SplitRunProcessor.js +49 -8
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  15. package/dist/esm/model/UiGraph.js +21 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +2 -0
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  18. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  19. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  20. package/dist/esm/model/UiGraphSchema.js +7 -1
  21. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  22. package/dist/esm/model/chat-v2/chatV2CallObserver.js +9 -5
  23. package/dist/esm/model/chat-v2/chatV2EditorCache.js +42 -16
  24. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  25. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  26. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  27. package/dist/esm/model/chat-v2/chatV2Pipeline.js +61 -146
  28. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +8 -2
  29. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  30. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  31. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  32. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  33. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  34. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  35. package/dist/esm/model/chat-v2/chatV2Types.js +5 -9
  36. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  37. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  38. package/dist/esm/model/chat-v2/index.js +12 -0
  39. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  40. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  41. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  42. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +6 -50
  43. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -13
  44. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +121 -193
  46. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  47. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  48. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  49. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  50. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  51. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  52. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  53. package/dist/esm/model/chat-v2/llmProfile.js +10 -65
  54. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  55. package/dist/esm/model/chat-v2/llmProfileFallback.js +55 -99
  56. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  57. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  58. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  59. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  60. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  61. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  62. package/dist/esm/model/chat-v2/providerOptions.js +86 -20
  63. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  64. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  65. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  66. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  67. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  68. package/dist/esm/model/nodes/ChatNode.js +6 -0
  69. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  70. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  71. package/dist/esm/model/nodes/LLMChatV2Node.js +112 -229
  72. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  73. package/dist/esm/model/nodes/PromptNode.js +7 -0
  74. package/dist/esm/model/nodes/ToolNode.js +7 -0
  75. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  76. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  77. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  78. package/dist/esm/plugins/google/google.js +5 -9
  79. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  80. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  81. package/dist/esm/utils/emitDetached.js +6 -3
  82. package/dist/esm/utils/openai.js +60 -16
  83. package/dist/esm/utils/serialization/serialization.js +2 -19
  84. package/dist/esm/webAppRuntime.js +3 -2
  85. package/dist/types/exports.d.ts +1 -0
  86. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  87. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  88. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  89. package/dist/types/model/GraphProcessor.d.ts +27 -5
  90. package/dist/types/model/NodeImpl.d.ts +18 -1
  91. package/dist/types/model/Nodes.d.ts +2 -2
  92. package/dist/types/model/ProcessContext.d.ts +47 -0
  93. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  94. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  95. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  96. package/dist/types/model/UiGraph.d.ts +8 -0
  97. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  98. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  99. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  100. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  101. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  102. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  103. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -3
  104. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  105. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  106. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +4 -0
  107. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  108. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  109. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  110. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  111. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  112. package/dist/types/model/chat-v2/chatV2Types.d.ts +20 -10
  113. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  114. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  115. package/dist/types/model/chat-v2/index.d.ts +12 -0
  116. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  117. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  118. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  119. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -3
  120. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  121. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  122. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  123. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  124. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  125. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  126. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  127. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  128. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  129. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  130. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +17 -49
  131. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  132. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  133. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  134. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  135. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  136. package/dist/types/model/chat-v2/providerOptions.d.ts +10 -0
  137. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  138. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  139. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  140. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  141. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  142. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  143. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  144. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  145. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  146. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  147. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  148. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  149. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  150. package/dist/types/plugins/google/google.d.ts +2 -8
  151. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  152. package/dist/types/utils/emitDetached.d.ts +3 -2
  153. package/dist/types/utils/openai.d.ts +49 -0
  154. package/dist/types/webAppRuntime.d.ts +4 -2
  155. package/package.json +2 -2
@@ -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: [
@@ -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
  }
@@ -4,49 +4,36 @@ import { createObservedChatV2CallId, notifyChatV2CallFinished } from './chatV2Ca
4
4
  import { chatMessagesToModelMessages } from './messageConverter.js';
5
5
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
6
6
  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;
7
+ import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
+ import { createLLMChatV2RetryAbortError, waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
9
+ import { createChatV2CommonOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
10
+ import { materializeLLMResponse } from './llmResponseMaterializer.js';
11
+ /** Identifies legacy pipeline results that represent a terminal provider failure. */
12
+ export function isChatV2PipelineProviderFailureResult(result) {
13
+ return result.terminalOutcome === 'provider-failure';
24
14
  }
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.';
15
+ export class ChatV2ResponseValidationError extends Error {
16
+ responseDataType;
17
+ constructor(responseDataType) {
18
+ super('LLM profile response validation failed.\n' +
19
+ 'Response format: JSON schema\n' +
20
+ `Parsed Response type: ${responseDataType}\n` +
21
+ 'The provider request succeeded, but the final value prepared for the Response port is not an object. ' +
22
+ 'JSON schema response format requires an object, so Rivet rejected this LLM profile. ' +
23
+ 'Retry on non-200 does not apply to this validation failure.');
24
+ this.responseDataType = responseDataType;
25
+ this.name = 'ChatV2ResponseValidationError';
39
26
  }
40
27
  }
28
+ export function isChatV2ResponseValidationError(error) {
29
+ return error instanceof ChatV2ResponseValidationError;
30
+ }
41
31
  function buildNon200StatusError(statusCode) {
42
32
  const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
43
33
  error.name = 'AI_APICallError';
44
34
  error.statusCode = statusCode;
45
35
  return error;
46
36
  }
47
- function normalizeProviderFailureMessage(error, options) {
48
- return getProviderFailureMessage(normalizeProviderFailure(error, options));
49
- }
50
37
  function normalizeProviderFailure(error, options) {
51
38
  try {
52
39
  return normalizeChatV2ProviderError(error, {
@@ -58,9 +45,6 @@ function normalizeProviderFailure(error, options) {
58
45
  return error;
59
46
  }
60
47
  }
61
- function normalizeProviderFailureMessages(errors, options) {
62
- return errors.map((error) => normalizeProviderFailureMessage(error, options));
63
- }
64
48
  function notifyProviderAttempt(options, attempt) {
65
49
  try {
66
50
  options.onProviderAttempt?.(attempt);
@@ -70,19 +54,21 @@ function notifyProviderAttempt(options, attempt) {
70
54
  }
71
55
  }
72
56
  async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
73
- const requestStatuses = [];
74
- const requestErrors = [];
75
57
  for (let attempt = 0;; attempt++) {
76
58
  const callId = createObservedChatV2CallId(options);
59
+ const callStartedAt = Date.now();
77
60
  let callWasObserved = false;
78
61
  try {
79
62
  const result = transportMode === 'generate' ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
63
+ await options.responseBodyCapture?.flush();
80
64
  const statusCode = result.requestStatus ?? 200;
81
65
  notifyChatV2CallFinished(options, {
82
66
  callId,
83
67
  attemptIndex: attempt,
84
68
  outcome: statusCode === 200 ? 'success' : 'provider-failure',
85
69
  result,
70
+ startedAt: callStartedAt,
71
+ durationMs: Math.max(0, Date.now() - callStartedAt),
86
72
  });
87
73
  callWasObserved = true;
88
74
  notifyProviderAttempt(options, {
@@ -91,102 +77,54 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
91
77
  status: statusCode,
92
78
  ...(statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }),
93
79
  });
94
- if (retryPlan.enabled) {
95
- requestStatuses.push(statusCode);
96
- }
97
80
  if (!retryPlan.enabled || statusCode === 200) {
98
- return { result, requestStatuses, requestErrors };
81
+ return { result };
99
82
  }
100
83
  const responseError = buildNon200StatusError(statusCode);
101
- requestErrors.push(responseError);
102
84
  if (attempt >= retryPlan.repeatTimes) {
103
- return { result, requestStatuses, requestErrors, responseError };
85
+ return { result, responseError };
104
86
  }
105
87
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
106
88
  }
107
89
  catch (error) {
90
+ await options.responseBodyCapture?.flush();
108
91
  if (!callWasObserved) {
109
92
  notifyChatV2CallFinished(options, {
110
93
  callId,
111
94
  attemptIndex: attempt,
112
95
  outcome: signal.aborted ? 'aborted' : 'provider-failure',
113
96
  error,
97
+ startedAt: callStartedAt,
98
+ durationMs: Math.max(0, Date.now() - callStartedAt),
114
99
  });
115
100
  }
116
101
  const statusCode = getChatV2ProviderErrorStatusCode(error);
117
102
  notifyProviderAttempt(options, {
118
103
  attemptIndex: attempt,
119
- outcome: 'provider-failure',
104
+ outcome: signal.aborted ? 'aborted' : 'provider-failure',
120
105
  ...(statusCode == null ? {} : { status: statusCode }),
121
106
  error,
122
107
  });
108
+ if (signal.aborted) {
109
+ // The provider may reject concurrently with graph cancellation. The
110
+ // cancellation wins: it must neither retry nor masquerade as a
111
+ // provider failure to profile fallback and run activity.
112
+ throw createLLMChatV2RetryAbortError();
113
+ }
123
114
  if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
124
115
  throw error;
125
116
  }
126
- requestStatuses.push(statusCode);
127
- requestErrors.push(error);
128
117
  if (attempt >= retryPlan.repeatTimes) {
129
- throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
118
+ throw error;
130
119
  }
131
120
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
132
121
  }
133
122
  }
134
123
  }
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
124
  /**
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.
125
+ * Runs one provider/model round. Provider failures stay distinct from shared
126
+ * graph configuration errors so an LLM Profile fallback chain can advance to
127
+ * its next candidate; terminal failures always remain node errors.
190
128
  */
191
129
  export async function runChatV2PipelineExecution(options) {
192
130
  const requestMessages = prependSystemPrompt(coercePromptToChatMessages(options.prompt, { requirePrompt: true }), options.systemPrompt);
@@ -223,19 +161,14 @@ export async function runChatV2PipelineExecution(options) {
223
161
  functionCalls,
224
162
  usage: undefined,
225
163
  reasoning: '',
226
- requestStatus: undefined,
227
- responseError: undefined,
228
- requestStatuses: [],
229
- requestErrors: [],
230
164
  requestBodies: undefined,
165
+ responseBodies: undefined,
231
166
  outputUsage: false,
232
167
  outputReasoning: false,
233
- outputRequestStatus: false,
234
- outputRequestError: false,
235
168
  outputRequestBody: false,
169
+ outputResponseBody: false,
236
170
  includeFunctionCalls: plan.output.includeFunctionCalls,
237
171
  functionCallMode: plan.output.functionCallMode,
238
- retryOnNon200: false,
239
172
  responseFormat: undefined,
240
173
  }));
241
174
  },
@@ -245,28 +178,16 @@ export async function runChatV2PipelineExecution(options) {
245
178
  if (options.context.signal.aborted) {
246
179
  throw caughtError;
247
180
  }
248
- const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : undefined;
249
- const rawError = retryFailure?.error ?? caughtError;
250
181
  return {
251
182
  outcome: 'provider-failure',
252
183
  failure: {
253
- requestMessages,
254
184
  options,
255
- plan,
256
- normalizedError: normalizeProviderFailure(rawError, options),
257
- rawError,
258
- requestStatuses: retryFailure?.requestStatuses ?? [],
259
- requestErrors: normalizeProviderFailureMessages(retryFailure?.requestErrors ?? [], options),
185
+ normalizedError: normalizeProviderFailure(caughtError, options),
260
186
  },
261
187
  };
262
188
  }
263
189
  const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
264
- const requestStatuses = chatResponse.requestStatuses;
265
190
  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
191
  const commonOutputs = createChatV2CommonOutputs({
271
192
  requestMessages,
272
193
  response: chatResponse.result.responseText,
@@ -274,19 +195,14 @@ export async function runChatV2PipelineExecution(options) {
274
195
  functionCalls: chatResponse.result.functionCalls,
275
196
  usage,
276
197
  reasoning: chatResponse.result.reasoning,
277
- requestStatus,
278
- responseError,
279
- requestStatuses,
280
- requestErrors,
281
198
  requestBodies: options.requestBodies,
199
+ responseBodies: options.responseBodies,
282
200
  outputUsage: plan.output.outputUsage,
283
201
  outputReasoning: plan.output.outputReasoning,
284
- outputRequestStatus: plan.output.outputRequestStatus,
285
- outputRequestError: plan.output.outputRequestError,
286
202
  outputRequestBody: plan.output.outputRequestBody,
203
+ outputResponseBody: plan.output.outputResponseBody,
287
204
  includeFunctionCalls: plan.output.includeFunctionCalls,
288
205
  functionCallMode: plan.output.functionCallMode,
289
- retryOnNon200: plan.retry.enabled,
290
206
  responseFormat: plan.request.responseFormat,
291
207
  });
292
208
  const allMessagesOutput = commonOutputs['all-messages'];
@@ -312,32 +228,31 @@ export async function runChatV2PipelineExecution(options) {
312
228
  return {
313
229
  outcome: 'provider-failure',
314
230
  failure: {
315
- requestMessages,
316
231
  options,
317
- plan,
318
232
  normalizedError: normalizeProviderFailure(rawError, options),
319
- rawError,
320
- requestStatuses: chatResponse.requestStatuses,
321
- requestErrors: normalizeProviderFailureMessages(chatResponse.requestErrors, options),
322
- diagnosticResult: result,
323
233
  },
324
234
  };
325
235
  }
236
+ // A tool-request round is not a terminal Response value. Auto-continuation
237
+ // will make another model call after delegated tools finish, so validate the
238
+ // value only once a provider round actually produces the final response.
239
+ if (plan.request.responseFormat === 'json_schema' && chatResponse.result.functionCalls.length === 0) {
240
+ const materialized = materializeLLMResponse({
241
+ rawText: chatResponse.result.responseText,
242
+ structuredOutput: chatResponse.result.structuredOutput,
243
+ responseFormat: plan.request.responseFormat,
244
+ });
245
+ if (materialized.validation === 'invalid') {
246
+ throw new ChatV2ResponseValidationError(materialized.value.type);
247
+ }
248
+ }
326
249
  return { outcome: 'success', result };
327
250
  }
328
251
  /**
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.
252
+ * Terminal provider failures are node errors. The fallback coordinator may
253
+ * still catch this decision boundary and advance to a later LLM Profile.
332
254
  */
333
255
  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
256
  throw failure.normalizedError;
342
257
  }
343
258
  export async function runChatV2Pipeline(options) {
@@ -1,5 +1,6 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { createChatV2Model, resolveChatV2ProviderConfig, } from './providerOptions.js';
3
+ import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
3
4
  function getStringSetting(settings, key) {
4
5
  const value = settings[key];
5
6
  return typeof value === 'string' && value.trim() ? value : undefined;
@@ -79,18 +80,23 @@ export async function createResolvedChatV2Provider(options) {
79
80
  ...config,
80
81
  apiKey: options.credential.value,
81
82
  onRequestBody: options.onRequestBody,
83
+ onResponseBody: options.onResponseBody,
82
84
  transformRequestBody: options.transformRequestBody,
85
+ customProviderApi: options.customProviderApi,
83
86
  });
84
87
  return {
85
88
  profile: {
86
89
  provider: options.provider,
87
90
  modelId: options.modelId,
91
+ ...(options.provider === 'custom' && options.customProviderApi != null
92
+ ? { customProviderApi: options.customProviderApi }
93
+ : {}),
88
94
  baseURL: config.baseURL,
89
95
  hasCustomHeaders: Object.keys(config.headers ?? {}).length > 0,
90
96
  credential: options.credential.reference,
91
97
  capabilities: {
92
- builtInTools: options.provider === 'openai' || options.provider === 'google',
93
- structuredOutput: true,
98
+ builtInTools: getChatV2ProviderCapabilities(options.provider).builtInTools,
99
+ structuredOutput: getChatV2ProviderCapabilities(options.provider).structuredOutput,
94
100
  },
95
101
  },
96
102
  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
+ }