@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,6 +1,8 @@
1
- export const LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE = 'Supported by OpenAI, Anthropic, and compatible Custom providers. Custom providers receive parallel_tool_calls only when enabled; otherwise their default applies unless Extra provider options supplies the field.';
1
+ import { getCustomProviderApiContract } from './customProviderApi.js';
2
+ import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
3
+ export const LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE = 'Allows the model to request multiple tool calls in one round.';
2
4
  export function supportsLLMChatV2ParallelToolCalls(provider) {
3
- return provider === 'openai' || provider === 'anthropic' || provider === 'custom';
5
+ return getChatV2ProviderCapabilities(provider).parallelToolCalls;
4
6
  }
5
7
  function mergeProviderOptions(providerOptions, provider, options) {
6
8
  return {
@@ -26,6 +28,11 @@ export function applyLLMChatV2ParallelToolCallProviderOptions(params) {
26
28
  disableParallelToolUse: !parallelToolCalls,
27
29
  });
28
30
  case 'custom':
31
+ if (getCustomProviderApiContract(params.customProviderApi).parallelToolCalls === 'openai-option') {
32
+ return mergeProviderOptions(providerOptions, 'openai', {
33
+ parallelToolCalls: !!parallelToolCalls,
34
+ });
35
+ }
29
36
  // OpenAI-compatible endpoints vary widely. Do not send an unsupported
30
37
  // field to existing/default Custom-provider graphs unless the user
31
38
  // explicitly opts in to requesting parallel calls.
@@ -3,7 +3,9 @@ import { createGoogleGenerativeAI } from '@ai-sdk/google';
3
3
  import { createOpenAI } from '@ai-sdk/openai';
4
4
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
5
5
  import { cleanHeaders } from '../../utils/inputs.js';
6
+ import { getCustomProviderApiContract } from './customProviderApi.js';
6
7
  import { getChatV2ModelRegistry } from './modelRegistry.js';
8
+ export { customProviderApiOptions, getCustomProviderApiContract, parseCustomProviderApi, } from './customProviderApi.js';
7
9
  export const chatV2ProviderOptions = [
8
10
  { value: 'openai', label: 'OpenAI' },
9
11
  { value: 'anthropic', label: 'Anthropic' },
@@ -84,20 +86,30 @@ export function parseChatV2Provider(value) {
84
86
  throw new Error(`Unsupported LLM Chat provider: ${value}`);
85
87
  }
86
88
  }
87
- function removeTrailingSlash(value) {
88
- return value.endsWith('/') ? value.slice(0, -1) : value;
89
- }
90
- function openAIEndpointToBaseURL(endpoint) {
91
- const normalized = endpoint.replace(/\/(chat\/completions|responses)\/?$/i, '');
89
+ export function normalizeOpenAICompatibleEndpoint(endpoint) {
90
+ let url;
92
91
  try {
93
- return removeTrailingSlash(new URL(normalized).toString());
92
+ url = new URL(endpoint);
94
93
  }
95
- catch {
96
- return removeTrailingSlash(normalized);
94
+ catch (cause) {
95
+ throw new Error('Custom provider base URL must be a valid absolute HTTP or HTTPS URL.', { cause });
96
+ }
97
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
98
+ throw new Error('Custom provider base URL must use HTTP or HTTPS.');
97
99
  }
100
+ const endpointQuery = [...url.searchParams.entries()];
101
+ const pathWithoutTrailingSlashes = url.pathname.replace(/\/+$/, '');
102
+ const basePath = pathWithoutTrailingSlashes.replace(/\/(?:chat\/completions|responses)$/i, '').replace(/\/+$/, '');
103
+ url.pathname = basePath || '/';
104
+ url.search = '';
105
+ url.hash = '';
106
+ return {
107
+ baseURL: url.toString().replace(/\/+$/, ''),
108
+ endpointQuery,
109
+ };
98
110
  }
99
111
  export function openAICompatibleEndpointToBaseURL(endpoint) {
100
- return openAIEndpointToBaseURL(endpoint);
112
+ return normalizeOpenAICompatibleEndpoint(endpoint).baseURL;
101
113
  }
102
114
  function parseBodyText(text) {
103
115
  try {
@@ -125,6 +137,19 @@ function parseFetchBody(body) {
125
137
  }
126
138
  return undefined;
127
139
  }
140
+ async function resolveProviderFetchBody(input, init) {
141
+ if (init?.body != null) {
142
+ return { originalBody: init.body, parsedBody: parseFetchBody(init.body) };
143
+ }
144
+ if (!(input instanceof Request) || input.body == null) {
145
+ return { originalBody: undefined, parsedBody: undefined };
146
+ }
147
+ // Fetch implementations may provide the complete request as a Request
148
+ // object rather than as URL + init. Read a clone so diagnostics and raw
149
+ // overlays do not consume the body that will be sent.
150
+ const bodyText = await input.clone().text();
151
+ return { originalBody: bodyText, parsedBody: parseBodyText(bodyText) };
152
+ }
128
153
  function cloneCapturedRequestBody(body) {
129
154
  if (typeof structuredClone === 'function') {
130
155
  try {
@@ -154,6 +179,15 @@ function serializeTransformedFetchBody(originalBody, transformedBody) {
154
179
  }
155
180
  return serialized;
156
181
  }
182
+ export function applyChatV2RequestBodyOverlay(body, overlay) {
183
+ if (overlay == null) {
184
+ return body;
185
+ }
186
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
187
+ throw new Error('Extra provider options could not be applied because the provider request body is not a JSON object.');
188
+ }
189
+ return { ...body, ...overlay };
190
+ }
157
191
  function removeStaleContentLength(headers) {
158
192
  if (headers == null) {
159
193
  return undefined;
@@ -162,30 +196,70 @@ function removeStaleContentLength(headers) {
162
196
  nextHeaders.delete('content-length');
163
197
  return nextHeaders;
164
198
  }
165
- function createRequestBodyProcessingFetch(options) {
199
+ function applyEndpointQuery(input, endpointQuery) {
200
+ if (endpointQuery.length === 0) {
201
+ return input;
202
+ }
203
+ const originalURL = input instanceof Request ? input.url : input instanceof URL ? input.toString() : input;
204
+ const url = new URL(originalURL);
205
+ const configuredKeys = new Set(endpointQuery.map(([key]) => key));
206
+ for (const key of configuredKeys) {
207
+ url.searchParams.delete(key);
208
+ }
209
+ for (const [key, value] of endpointQuery) {
210
+ url.searchParams.append(key, value);
211
+ }
212
+ return input instanceof Request ? new Request(url, input) : input instanceof URL ? url : url.toString();
213
+ }
214
+ function createProviderProcessingFetch(options, processing) {
166
215
  return async (input, init) => {
167
- const parsedBody = parseFetchBody(init?.body);
168
- const processedBody = parsedBody !== undefined && options.transformRequestBody != null
216
+ const { originalBody, parsedBody } = await resolveProviderFetchBody(input, init);
217
+ const transformedBody = parsedBody !== undefined && options.transformRequestBody != null
169
218
  ? options.transformRequestBody(parsedBody)
170
219
  : parsedBody;
220
+ const processedBody = applyChatV2RequestBodyOverlay(transformedBody, options.requestBodyOverlay);
221
+ const shouldSerializeProcessedBody = parsedBody !== undefined && (options.transformRequestBody != null || options.requestBodyOverlay != null);
171
222
  if (processedBody !== undefined) {
172
223
  options.onRequestBody?.(cloneCapturedRequestBody(processedBody));
173
224
  }
174
225
  const nativeFetch = globalThis.fetch;
175
- const processedInit = processedBody !== parsedBody
226
+ let processedInit = shouldSerializeProcessedBody
176
227
  ? {
177
228
  ...init,
178
- body: serializeTransformedFetchBody(init?.body, processedBody),
179
- headers: removeStaleContentLength(init?.headers),
229
+ body: serializeTransformedFetchBody(originalBody, processedBody),
230
+ headers: removeStaleContentLength(init?.headers ?? (input instanceof Request ? input.headers : undefined)),
180
231
  }
181
232
  : init;
182
- return nativeFetch(input, processedInit);
233
+ const effectiveHeaders = processedInit?.headers ?? (input instanceof Request ? input.headers : undefined);
234
+ if (processing.omitGeneratedEmptyBearer && effectiveHeaders != null) {
235
+ const headers = new Headers(effectiveHeaders);
236
+ if (headers.get('authorization')?.trim().toLowerCase() === 'bearer') {
237
+ headers.delete('authorization');
238
+ processedInit = { ...processedInit, headers };
239
+ }
240
+ }
241
+ const processedInput = applyEndpointQuery(input, processing.endpointQuery);
242
+ const response = await nativeFetch(processedInput, processedInit);
243
+ try {
244
+ options.onResponseBody?.(response);
245
+ }
246
+ catch {
247
+ // Diagnostic capture is observational and must never change a provider call.
248
+ }
249
+ return response;
183
250
  };
184
251
  }
185
- function maybeCreateRequestBodyProcessingFetch(options) {
186
- return options.onRequestBody == null && options.transformRequestBody == null
252
+ function maybeCreateProviderProcessingFetch(options, processing = {}) {
253
+ const omitGeneratedEmptyBearer = processing.omitGeneratedEmptyBearer === true;
254
+ const endpointQuery = options.endpointQuery ?? [];
255
+ return options.onRequestBody == null &&
256
+ options.onResponseBody == null &&
257
+ options.transformRequestBody == null &&
258
+ options.requestBodyOverlay == null &&
259
+ !omitGeneratedEmptyBearer &&
260
+ endpointQuery.length === 0
187
261
  ? undefined
188
- : createRequestBodyProcessingFetch(options);
262
+ : createProviderProcessingFetch(options, { omitGeneratedEmptyBearer, endpointQuery });
189
263
  }
190
264
  export async function resolveChatV2ProviderConfig(provider, _modelId, context, options = {}) {
191
265
  const headers = cleanHeaders({
@@ -213,8 +287,9 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
213
287
  if (!configuredBaseURL) {
214
288
  throw new Error('Provider base URL is required when provider is Custom provider.');
215
289
  }
290
+ const endpoint = normalizeOpenAICompatibleEndpoint(configuredBaseURL);
216
291
  return {
217
- baseURL: openAICompatibleEndpointToBaseURL(configuredBaseURL),
292
+ ...endpoint,
218
293
  headers: Object.keys(headers).length > 0 ? headers : undefined,
219
294
  };
220
295
  }
@@ -228,7 +303,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
228
303
  organization: context.settings.openAiOrganization || undefined,
229
304
  baseURL: undefined,
230
305
  headers: options.headers,
231
- fetch: maybeCreateRequestBodyProcessingFetch(options),
306
+ fetch: maybeCreateProviderProcessingFetch(options),
232
307
  });
233
308
  return providerInstance.responses(modelId);
234
309
  }
@@ -237,7 +312,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
237
312
  apiKey: options.apiKey || context.settings.anthropicApiKey || context.getPluginConfig('anthropicApiKey') || undefined,
238
313
  baseURL: undefined,
239
314
  headers: options.headers,
240
- fetch: maybeCreateRequestBodyProcessingFetch(options),
315
+ fetch: maybeCreateProviderProcessingFetch(options),
241
316
  });
242
317
  return providerInstance.messages(modelId);
243
318
  }
@@ -246,7 +321,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
246
321
  apiKey: options.apiKey || context.settings.googleApiKey || context.getPluginConfig('googleApiKey') || undefined,
247
322
  baseURL: undefined,
248
323
  headers: options.headers,
249
- fetch: maybeCreateRequestBodyProcessingFetch(options),
324
+ fetch: maybeCreateProviderProcessingFetch(options),
250
325
  });
251
326
  return providerInstance.chat(modelId);
252
327
  }
@@ -254,13 +329,30 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
254
329
  if (!options.baseURL) {
255
330
  throw new Error('Provider base URL is required when provider is Custom provider.');
256
331
  }
332
+ const apiContract = getCustomProviderApiContract(options.customProviderApi);
333
+ if (apiContract.adapter === 'openai-responses') {
334
+ const hasExplicitAuthorizationHeader = Object.keys(options.headers ?? {}).some((header) => header.toLowerCase() === 'authorization');
335
+ const providerInstance = createOpenAI({
336
+ name: 'custom',
337
+ // Prevent the OpenAI adapter from falling back to OPENAI_API_KEY for
338
+ // a Custom provider. A configured Authorization header can still
339
+ // override this placeholder for non-Bearer authentication schemes.
340
+ apiKey: options.apiKey ?? '',
341
+ baseURL: options.baseURL,
342
+ headers: options.headers,
343
+ fetch: maybeCreateProviderProcessingFetch(options, {
344
+ omitGeneratedEmptyBearer: !options.apiKey && !hasExplicitAuthorizationHeader,
345
+ }),
346
+ });
347
+ return providerInstance.responses(modelId);
348
+ }
257
349
  const providerInstance = createOpenAICompatible({
258
350
  name: 'custom',
259
351
  apiKey: options.apiKey,
260
352
  baseURL: options.baseURL,
261
353
  headers: options.headers,
262
354
  includeUsage: false,
263
- fetch: maybeCreateRequestBodyProcessingFetch(options),
355
+ fetch: maybeCreateProviderProcessingFetch(options),
264
356
  });
265
357
  const model = providerInstance.chatModel(modelId);
266
358
  // The installed OpenAI-compatible provider reads this from the model instance,
@@ -0,0 +1,9 @@
1
+ export function createRivetToolRegistry(functions) {
2
+ const byName = new Map();
3
+ for (const tool of functions ?? []) {
4
+ if (typeof tool.name === 'string' && tool.name.trim().length > 0) {
5
+ byName.set(tool.name, tool);
6
+ }
7
+ }
8
+ return { byName, names: new Set(byName.keys()) };
9
+ }
@@ -0,0 +1,52 @@
1
+ /** Provider/tool boundary codec shared by internal and connected delegation. */
2
+ export function normalizeToolCall(input) {
3
+ if (Array.isArray(input)) {
4
+ if (input.length !== 1) {
5
+ throw new Error(`Delegate Tool Call expected a single tool call, but received ${input.length}. Use Run per item or select one tool call before delegating.`);
6
+ }
7
+ return normalizeToolCall(input[0]);
8
+ }
9
+ if (typeof input !== 'object' || input == null) {
10
+ throw new Error('Delegate Tool Call expected a tool call object.');
11
+ }
12
+ const raw = input;
13
+ if (typeof raw.name !== 'string' || raw.name.length === 0) {
14
+ throw new Error('Delegate Tool Call expected the tool call to include a name.');
15
+ }
16
+ const id = typeof raw.id === 'string' ? raw.id : undefined;
17
+ if (raw.arguments == null)
18
+ return { id, name: raw.name, arguments: {} };
19
+ if (typeof raw.arguments === 'string') {
20
+ try {
21
+ const parsed = JSON.parse(raw.arguments);
22
+ if (typeof parsed === 'object' && parsed != null && !Array.isArray(parsed)) {
23
+ return { id, name: raw.name, arguments: parsed };
24
+ }
25
+ }
26
+ catch {
27
+ // Fall through to the explicit handler-facing error.
28
+ }
29
+ throw new Error(`Delegate Tool Call expected "${raw.name}" arguments to be a JSON object.`);
30
+ }
31
+ if (typeof raw.arguments === 'object' && !Array.isArray(raw.arguments)) {
32
+ return { id, name: raw.name, arguments: raw.arguments };
33
+ }
34
+ throw new Error(`Delegate Tool Call expected "${raw.name}" arguments to be an object.`);
35
+ }
36
+ export function createToolResultMessage(toolCall, output) {
37
+ return { type: 'function', message: output, name: toolCall.id ?? '', toolName: toolCall.name };
38
+ }
39
+ export function createDelegatedToolCallRecord(toolCall, output, executionTimeMs) {
40
+ return {
41
+ delegatedToolCall: true,
42
+ name: toolCall.name,
43
+ arguments: toolCall.arguments,
44
+ id: toolCall.id,
45
+ output,
46
+ ...(executionTimeMs == null ? {} : { executionTimeMs }),
47
+ message: createToolResultMessage(toolCall, output),
48
+ };
49
+ }
50
+ export function stringifyToolResult(output) {
51
+ return typeof output === 'string' ? output : JSON.stringify(output) ?? String(output);
52
+ }
@@ -1,22 +1,13 @@
1
- import { runChatV2Pipeline } from './chatV2Pipeline.js';
2
- function getToolNames(functions) {
3
- return new Set((functions ?? []).map((fn) => fn.name).filter((name) => name.trim().length > 0));
4
- }
5
- function canAutoContinue(functionCalls, toolNames) {
6
- return functionCalls.length > 0 && functionCalls.every((call) => toolNames.has(call.name));
7
- }
8
- function shouldReturnToolResultDirectly(functionCalls, functions) {
1
+ import { createRivetToolRegistry } from './rivetToolRegistry.js';
2
+ import { materializeLLMResponse } from './llmResponseMaterializer.js';
3
+ import { createCallbackToolRoundExecutor } from './toolRoundExecutor.js';
4
+ import { decideLLMInvocationRound } from './llmInvocationDecision.js';
5
+ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
6
+ function shouldReturnToolResultDirectly(functionCalls, registry) {
9
7
  if (functionCalls.length !== 1) {
10
8
  return false;
11
9
  }
12
- let tool;
13
- for (const candidate of functions ?? []) {
14
- if (candidate.name === functionCalls[0].name) {
15
- // Provider tool maps use the last declaration for duplicate names.
16
- tool = candidate;
17
- }
18
- }
19
- return tool?.resultHandling === 'return-direct';
10
+ return registry.byName.get(functionCalls[0].name)?.resultHandling === 'return-direct';
20
11
  }
21
12
  function addUsage(accumulated, usage) {
22
13
  if (usage == null) {
@@ -70,9 +61,25 @@ function applyAccumulatedReasoning(result, reasoningRounds, outputReasoning) {
70
61
  };
71
62
  }
72
63
  }
64
+ function applyTerminalContinuationOutputs(result, delegatedToolCalls, accumulatedUsage, reasoningRounds, options) {
65
+ if (result.functionCalls.length === 0 && delegatedToolCalls.length > 0 && options.includeFunctionCalls) {
66
+ result.commonOutputs['function-calls'] = {
67
+ type: 'object[]',
68
+ value: [...delegatedToolCalls],
69
+ };
70
+ }
71
+ if (options.autoContinue) {
72
+ applyAccumulatedUsage(result, accumulatedUsage, options.outputUsage);
73
+ applyAccumulatedReasoning(result, reasoningRounds, options.outputReasoning);
74
+ }
75
+ }
73
76
  export async function runChatV2PipelineWithToolContinuation(options) {
74
- const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline = runChatV2Pipeline, ...pipelineOptions } = options;
75
- const toolNames = getToolNames(functions);
77
+ const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline, ...pipelineOptions } = options;
78
+ const toolRegistry = createRivetToolRegistry(functions);
79
+ const toolRoundExecutor = createCallbackToolRoundExecutor({
80
+ delegateOne: delegateToolCall,
81
+ delegateRound: delegateToolCallRound,
82
+ });
76
83
  const maxRounds = Math.max(1, Math.floor(Number.isFinite(maxToolRounds) ? maxToolRounds : 1));
77
84
  let currentPrompt = pipelineOptions.prompt;
78
85
  let currentSystemPrompt = pipelineOptions.systemPrompt;
@@ -84,42 +91,72 @@ export async function runChatV2PipelineWithToolContinuation(options) {
84
91
  ...pipelineOptions,
85
92
  functions,
86
93
  prompt: currentPrompt,
94
+ roundIndex: completedRounds,
87
95
  systemPrompt: currentSystemPrompt,
88
96
  });
89
97
  accumulatedUsage = autoContinue ? addUsage(accumulatedUsage, result.usage) : undefined;
90
98
  if (autoContinue) {
91
99
  appendReasoningRound(reasoningRounds, result.reasoning);
92
100
  }
93
- if (!autoContinue || completedRounds >= maxRounds || !canAutoContinue(result.functionCalls, toolNames)) {
94
- if (result.functionCalls.length === 0 && delegatedToolCalls.length > 0 && pipelineOptions.includeFunctionCalls) {
95
- result.commonOutputs['function-calls'] = {
96
- type: 'object[]',
97
- value: delegatedToolCalls,
98
- };
99
- }
100
- if (autoContinue) {
101
- applyAccumulatedUsage(result, accumulatedUsage, pipelineOptions.outputUsage);
102
- applyAccumulatedReasoning(result, reasoningRounds, pipelineOptions.outputReasoning);
103
- }
101
+ // Request diagnostics can preserve partial provider content on a failed
102
+ // HTTP response. That content is for inspection only: it is not a valid
103
+ // assistant tool request and must never trigger a handler side effect.
104
+ if (isChatV2PipelineProviderFailureResult(result)) {
105
+ applyTerminalContinuationOutputs(result, delegatedToolCalls, accumulatedUsage, reasoningRounds, {
106
+ autoContinue,
107
+ outputUsage: pipelineOptions.outputUsage,
108
+ outputReasoning: pipelineOptions.outputReasoning,
109
+ includeFunctionCalls: pipelineOptions.includeFunctionCalls,
110
+ });
104
111
  return result;
105
112
  }
106
- const toolResultMessages = delegateToolCallRound
107
- ? await delegateToolCallRound(result.functionCalls, result.response)
108
- : await Promise.all(result.functionCalls.map(delegateToolCall));
113
+ const decision = decideLLMInvocationRound({
114
+ autoContinue,
115
+ completedRounds,
116
+ maxToolRounds: maxRounds,
117
+ calls: result.functionCalls,
118
+ knownToolNames: toolRegistry.names,
119
+ isDirectReturn: shouldReturnToolResultDirectly(result.functionCalls, toolRegistry),
120
+ });
121
+ if (decision.kind === 'final-model-answer' ||
122
+ decision.kind === 'release-unresolved-calls' ||
123
+ decision.kind === 'max-rounds-reached') {
124
+ applyTerminalContinuationOutputs(result, delegatedToolCalls, accumulatedUsage, reasoningRounds, {
125
+ autoContinue,
126
+ outputUsage: pipelineOptions.outputUsage,
127
+ outputReasoning: pipelineOptions.outputReasoning,
128
+ includeFunctionCalls: pipelineOptions.includeFunctionCalls,
129
+ });
130
+ return result;
131
+ }
132
+ const toolResultMessages = await toolRoundExecutor.executeRound({
133
+ calls: result.functionCalls,
134
+ assistantMessage: result.response,
135
+ });
109
136
  delegatedToolCalls.push(...toolResultMessages
110
137
  .map((message) => message.delegatedToolCall)
111
138
  .filter((record) => record != null));
112
- if (shouldReturnToolResultDirectly(result.functionCalls, functions)) {
139
+ if (decision.kind === 'direct-tool-response') {
113
140
  const directResultMessage = toolResultMessages[0]?.value;
114
141
  if (directResultMessage?.type !== 'function' || typeof directResultMessage.message !== 'string') {
115
142
  throw new Error('Return directly requires the delegated tool handler to return a string output.');
116
143
  }
117
144
  result.response = directResultMessage.message;
145
+ const materializedDirectResponse = materializeLLMResponse({
146
+ rawText: result.response,
147
+ structuredOutput: undefined,
148
+ responseFormat: pipelineOptions.responseFormat,
149
+ });
150
+ if (materializedDirectResponse.validation === 'invalid') {
151
+ throw new Error('Return directly tool handler response validation failed.\n' +
152
+ 'Response format: JSON schema\n' +
153
+ `Parsed Response type: ${materializedDirectResponse.value.type}\n` +
154
+ 'A direct tool result is terminal and is not retried or sent to another LLM profile.');
155
+ }
118
156
  result.allMessages = [...result.allMessages, directResultMessage];
119
157
  result.functionCalls = [];
120
158
  result.commonOutputs['response'] = {
121
- type: 'string',
122
- value: result.response,
159
+ ...materializedDirectResponse.value,
123
160
  };
124
161
  result.commonOutputs['all-messages'] = {
125
162
  type: 'chat-message[]',
@@ -0,0 +1,23 @@
1
+ export function findAutoDelegateGraphCandidate(candidates, toolName, getGraphName) {
2
+ return (candidates.find((candidate) => getGraphName(candidate) === toolName) ??
3
+ candidates.find((candidate) => getGraphName(candidate)?.includes(toolName)));
4
+ }
5
+ /**
6
+ * Preserves legacy exact-name then first fuzzy auto-delegation matching in a
7
+ * single resolver, making all runtime paths use identical routing.
8
+ */
9
+ export function resolveToolHandler(params) {
10
+ const { project, toolName, config, hasExternalFunction } = params;
11
+ if (!config.autoDelegate) {
12
+ const selected = config.handlers.find((handler) => handler.key === toolName);
13
+ if (selected)
14
+ return { kind: 'graph', graphId: selected.value, graphName: project.graphs[selected.value]?.metadata?.name };
15
+ return config.unknownHandler ? { kind: 'unknown', graphId: config.unknownHandler } : undefined;
16
+ }
17
+ const graph = findAutoDelegateGraphCandidate(Object.values(project.graphs), toolName, (candidate) => candidate.metadata?.name);
18
+ if (graph?.metadata?.id)
19
+ return { kind: 'graph', graphId: graph.metadata.id, graphName: graph.metadata.name };
20
+ if (config.fallBackToExternalCall && hasExternalFunction)
21
+ return { kind: 'external', name: toolName };
22
+ return config.unknownHandler ? { kind: 'unknown', graphId: config.unknownHandler } : undefined;
23
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Adapts the legacy individual/round callbacks without changing their
3
+ * concurrency semantics: a connected host owns a full round; internal
4
+ * delegation starts independent calls in parallel.
5
+ */
6
+ export function createCallbackToolRoundExecutor(params) {
7
+ return {
8
+ executeRound: ({ calls, assistantMessage }) => params.delegateRound
9
+ ? params.delegateRound([...calls], assistantMessage)
10
+ : Promise.all(calls.map((call) => params.delegateOne(call))),
11
+ };
12
+ }
@@ -27,6 +27,12 @@ export class ChatNodeImpl extends NodeImpl {
27
27
  getOutputDefinitions() {
28
28
  return ChatNodeBase.getOutputDefinitions(this.data);
29
29
  }
30
+ getRunActivityDescriptor() {
31
+ return {
32
+ category: 'model',
33
+ primaryOutputPortId: 'response',
34
+ };
35
+ }
30
36
  static getUIData() {
31
37
  return {
32
38
  infoBoxBody: dedent `
@@ -820,6 +820,7 @@ export const ChatNodeBase = {
820
820
  if (data.cache) {
821
821
  const cached = cache.get(cacheKey);
822
822
  if (cached) {
823
+ context.markResultAsEditorCacheHit?.();
823
824
  return cached;
824
825
  }
825
826
  }
@@ -6,6 +6,8 @@ import { NodeImpl } from '../NodeImpl.js';
6
6
  import {} from '../NodeBodySpec.js';
7
7
  import { appendCodeNodeSourceUrl, buildCodeNodeSourceUrl, enrichCodeNodeErrorWithLocation, } from './codeNodeErrorDiagnostics.js';
8
8
  import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
9
+ import { ALL_CODE_RUNNER_OPTIONS } from '../../integrations/CodeRunnerOptions.js';
10
+ const CODE_RUNTIME_HELPER_MESSAGE = 'Node execution also provides "require" and "process". Browser execution provides "fetch", "console", and "Rivet".';
9
11
  const DEFAULT_CODE_NEW = dedent `
10
12
  // This is a Code node. Write JavaScript here and return one value.
11
13
  // Interpolation tokens create input ports and evaluate as connected values.
@@ -90,11 +92,6 @@ export class CodeNewNodeImpl extends NodeImpl {
90
92
  },
91
93
  data: {
92
94
  code: DEFAULT_CODE_NEW,
93
- allowFetch: false,
94
- allowRequire: false,
95
- allowRivet: false,
96
- allowProcess: false,
97
- allowConsole: false,
98
95
  },
99
96
  };
100
97
  }
@@ -115,46 +112,13 @@ export class CodeNewNodeImpl extends NodeImpl {
115
112
  {
116
113
  type: 'code',
117
114
  label: 'Code',
118
- helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values.',
115
+ helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values. ' +
116
+ CODE_RUNTIME_HELPER_MESSAGE,
119
117
  dataKey: 'code',
120
118
  language: 'javascript',
121
119
  interpolationSyntax: 'js-value',
122
120
  enableFolding: true,
123
121
  },
124
- {
125
- type: 'group',
126
- label: 'Runtime permissions',
127
- defaultOpen: true,
128
- editors: [
129
- {
130
- type: 'toggle',
131
- label: 'Allow "fetch"',
132
- dataKey: 'allowFetch',
133
- },
134
- {
135
- type: 'toggle',
136
- label: 'Allow "Rivet"',
137
- dataKey: 'allowRivet',
138
- },
139
- {
140
- type: 'toggle',
141
- label: 'Allow "console"',
142
- dataKey: 'allowConsole',
143
- },
144
- {
145
- type: 'toggle',
146
- label: 'Allow "require"',
147
- dataKey: 'allowRequire',
148
- helperMessage: 'Only available with the Node executor',
149
- },
150
- {
151
- type: 'toggle',
152
- label: 'Allow "process"',
153
- dataKey: 'allowProcess',
154
- helperMessage: 'Only available with the Node executor',
155
- },
156
- ],
157
- },
158
122
  ];
159
123
  }
160
124
  getBody() {
@@ -182,13 +146,7 @@ export class CodeNewNodeImpl extends NodeImpl {
182
146
  const { inputNames, inputsIdentifier } = interpolationContext;
183
147
  const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext);
184
148
  try {
185
- const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, {
186
- includeFetch: this.data.allowFetch ?? false,
187
- includeRequire: this.data.allowRequire ?? false,
188
- includeRivet: this.data.allowRivet ?? false,
189
- includeProcess: this.data.allowProcess ?? false,
190
- includeConsole: this.data.allowConsole ?? false,
191
- }, context.graphInputNodeValues, context.contextValues);
149
+ const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, ALL_CODE_RUNNER_OPTIONS, context.graphInputNodeValues, context.contextValues);
192
150
  return validateCodeNewRunnerOutputs(outputs);
193
151
  }
194
152
  catch (error) {