@valerypopoff/rivet2-core 2.1.8 → 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 (168) hide show
  1. package/dist/cjs/bundle.cjs +4457 -1809
  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 +152 -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 +68 -18
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +13 -4
  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/aiSdkMessages.js +8 -0
  22. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  24. package/dist/esm/model/chat-v2/chatV2EditorCache.js +58 -10
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  26. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2Outputs.js +56 -106
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +142 -149
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +9 -2
  30. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  31. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +5 -5
  32. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  33. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  34. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  35. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  36. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  37. package/dist/esm/model/chat-v2/chatV2Types.js +7 -1
  38. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  39. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  40. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  41. package/dist/esm/model/chat-v2/index.js +12 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  44. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +8 -54
  46. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +41 -20
  47. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  48. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +178 -94
  49. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  50. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  51. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  52. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  53. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  54. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  55. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  56. package/dist/esm/model/chat-v2/llmProfile.js +31 -65
  57. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  58. package/dist/esm/model/chat-v2/llmProfileFallback.js +244 -0
  59. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  60. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  61. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  62. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  63. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  64. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  65. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  66. package/dist/esm/model/chat-v2/providerOptions.js +120 -21
  67. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  68. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  69. package/dist/esm/model/chat-v2/toolContinuation.js +72 -39
  70. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  71. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  72. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  73. package/dist/esm/model/nodes/ChatNode.js +6 -0
  74. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  75. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +26 -1
  76. package/dist/esm/model/nodes/LLMChatV2Node.js +131 -144
  77. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  78. package/dist/esm/model/nodes/PromptNode.js +16 -2
  79. package/dist/esm/model/nodes/ToolNode.js +7 -0
  80. package/dist/esm/model/nodes/toolCallDelegation.js +193 -110
  81. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  82. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +29 -28
  83. package/dist/esm/plugins/google/google.js +25 -18
  84. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +21 -7
  85. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  86. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  87. package/dist/esm/utils/emitDetached.js +6 -3
  88. package/dist/esm/utils/openai.js +60 -16
  89. package/dist/esm/utils/serialization/serialization.js +2 -0
  90. package/dist/esm/webAppRuntime.js +3 -2
  91. package/dist/types/exports.d.ts +1 -0
  92. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  93. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  94. package/dist/types/model/DataValue.d.ts +7 -1
  95. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  96. package/dist/types/model/GraphProcessor.d.ts +27 -5
  97. package/dist/types/model/NodeBase.d.ts +6 -0
  98. package/dist/types/model/NodeImpl.d.ts +18 -1
  99. package/dist/types/model/Nodes.d.ts +2 -2
  100. package/dist/types/model/ProcessContext.d.ts +51 -0
  101. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  102. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  103. package/dist/types/model/SplitRunProcessor.d.ts +11 -3
  104. package/dist/types/model/UiGraph.d.ts +8 -0
  105. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  106. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  107. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  108. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  109. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  110. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  111. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +3 -1
  112. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +7 -17
  113. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +29 -0
  114. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +5 -0
  115. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  116. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  117. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  118. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  119. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  120. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  121. package/dist/types/model/chat-v2/chatV2Types.d.ts +35 -1
  122. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  123. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  124. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  125. package/dist/types/model/chat-v2/index.d.ts +12 -0
  126. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  127. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  128. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  129. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +13 -3
  130. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  131. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -4
  132. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  133. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  134. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  135. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  136. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  137. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  138. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  139. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  140. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  141. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +47 -0
  142. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  143. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  144. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  145. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  146. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  147. package/dist/types/model/chat-v2/providerOptions.d.ts +11 -0
  148. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  149. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  150. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  151. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  152. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  153. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  154. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  155. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  156. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  157. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  158. package/dist/types/model/nodes/PromptNode.d.ts +6 -3
  159. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  160. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  161. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  162. package/dist/types/plugins/google/google.d.ts +14 -9
  163. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  164. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  165. package/dist/types/utils/emitDetached.d.ts +3 -2
  166. package/dist/types/utils/openai.d.ts +49 -0
  167. package/dist/types/webAppRuntime.d.ts +4 -2
  168. package/package.json +2 -2
@@ -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 {
@@ -141,18 +153,87 @@ function cloneCapturedRequestBody(body) {
141
153
  return body;
142
154
  }
143
155
  }
144
- function createRequestBodyCapturingFetch(onRequestBody) {
156
+ function serializeTransformedFetchBody(originalBody, transformedBody) {
157
+ const serialized = JSON.stringify(transformedBody);
158
+ if (serialized === undefined) {
159
+ throw new Error('Provider request-body transformation returned a non-serializable value.');
160
+ }
161
+ if (originalBody instanceof ArrayBuffer) {
162
+ return new TextEncoder().encode(serialized);
163
+ }
164
+ if (ArrayBuffer.isView(originalBody)) {
165
+ return new TextEncoder().encode(serialized);
166
+ }
167
+ return serialized;
168
+ }
169
+ function removeStaleContentLength(headers) {
170
+ if (headers == null) {
171
+ return undefined;
172
+ }
173
+ const nextHeaders = new Headers(headers);
174
+ nextHeaders.delete('content-length');
175
+ return nextHeaders;
176
+ }
177
+ function applyEndpointQuery(input, endpointQuery) {
178
+ if (endpointQuery.length === 0) {
179
+ return input;
180
+ }
181
+ const originalURL = input instanceof Request ? input.url : input instanceof URL ? input.toString() : input;
182
+ const url = new URL(originalURL);
183
+ const configuredKeys = new Set(endpointQuery.map(([key]) => key));
184
+ for (const key of configuredKeys) {
185
+ url.searchParams.delete(key);
186
+ }
187
+ for (const [key, value] of endpointQuery) {
188
+ url.searchParams.append(key, value);
189
+ }
190
+ return input instanceof Request ? new Request(url, input) : input instanceof URL ? url : url.toString();
191
+ }
192
+ function createProviderProcessingFetch(options, processing) {
145
193
  return async (input, init) => {
146
- const body = parseFetchBody(init?.body);
147
- if (body !== undefined) {
148
- onRequestBody(cloneCapturedRequestBody(body));
194
+ const parsedBody = parseFetchBody(init?.body);
195
+ const processedBody = parsedBody !== undefined && options.transformRequestBody != null
196
+ ? options.transformRequestBody(parsedBody)
197
+ : parsedBody;
198
+ if (processedBody !== undefined) {
199
+ options.onRequestBody?.(cloneCapturedRequestBody(processedBody));
149
200
  }
150
201
  const nativeFetch = globalThis.fetch;
151
- return nativeFetch(input, init);
202
+ let processedInit = processedBody !== parsedBody
203
+ ? {
204
+ ...init,
205
+ body: serializeTransformedFetchBody(init?.body, processedBody),
206
+ headers: removeStaleContentLength(init?.headers),
207
+ }
208
+ : init;
209
+ if (processing.omitGeneratedEmptyBearer && processedInit?.headers != null) {
210
+ const headers = new Headers(processedInit.headers);
211
+ if (headers.get('authorization')?.trim().toLowerCase() === 'bearer') {
212
+ headers.delete('authorization');
213
+ processedInit = { ...processedInit, headers };
214
+ }
215
+ }
216
+ const processedInput = applyEndpointQuery(input, processing.endpointQuery);
217
+ const response = await nativeFetch(processedInput, processedInit);
218
+ try {
219
+ options.onResponseBody?.(response);
220
+ }
221
+ catch {
222
+ // Diagnostic capture is observational and must never change a provider call.
223
+ }
224
+ return response;
152
225
  };
153
226
  }
154
- function maybeCreateRequestBodyCapturingFetch(options) {
155
- return options.onRequestBody == null ? undefined : createRequestBodyCapturingFetch(options.onRequestBody);
227
+ function maybeCreateProviderProcessingFetch(options, processing = {}) {
228
+ const omitGeneratedEmptyBearer = processing.omitGeneratedEmptyBearer === true;
229
+ const endpointQuery = options.endpointQuery ?? [];
230
+ return options.onRequestBody == null &&
231
+ options.onResponseBody == null &&
232
+ options.transformRequestBody == null &&
233
+ !omitGeneratedEmptyBearer &&
234
+ endpointQuery.length === 0
235
+ ? undefined
236
+ : createProviderProcessingFetch(options, { omitGeneratedEmptyBearer, endpointQuery });
156
237
  }
157
238
  export async function resolveChatV2ProviderConfig(provider, _modelId, context, options = {}) {
158
239
  const headers = cleanHeaders({
@@ -180,8 +261,9 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
180
261
  if (!configuredBaseURL) {
181
262
  throw new Error('Provider base URL is required when provider is Custom provider.');
182
263
  }
264
+ const endpoint = normalizeOpenAICompatibleEndpoint(configuredBaseURL);
183
265
  return {
184
- baseURL: openAICompatibleEndpointToBaseURL(configuredBaseURL),
266
+ ...endpoint,
185
267
  headers: Object.keys(headers).length > 0 ? headers : undefined,
186
268
  };
187
269
  }
@@ -195,7 +277,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
195
277
  organization: context.settings.openAiOrganization || undefined,
196
278
  baseURL: undefined,
197
279
  headers: options.headers,
198
- fetch: maybeCreateRequestBodyCapturingFetch(options),
280
+ fetch: maybeCreateProviderProcessingFetch(options),
199
281
  });
200
282
  return providerInstance.responses(modelId);
201
283
  }
@@ -204,7 +286,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
204
286
  apiKey: options.apiKey || context.settings.anthropicApiKey || context.getPluginConfig('anthropicApiKey') || undefined,
205
287
  baseURL: undefined,
206
288
  headers: options.headers,
207
- fetch: maybeCreateRequestBodyCapturingFetch(options),
289
+ fetch: maybeCreateProviderProcessingFetch(options),
208
290
  });
209
291
  return providerInstance.messages(modelId);
210
292
  }
@@ -213,7 +295,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
213
295
  apiKey: options.apiKey || context.settings.googleApiKey || context.getPluginConfig('googleApiKey') || undefined,
214
296
  baseURL: undefined,
215
297
  headers: options.headers,
216
- fetch: maybeCreateRequestBodyCapturingFetch(options),
298
+ fetch: maybeCreateProviderProcessingFetch(options),
217
299
  });
218
300
  return providerInstance.chat(modelId);
219
301
  }
@@ -221,13 +303,30 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
221
303
  if (!options.baseURL) {
222
304
  throw new Error('Provider base URL is required when provider is Custom provider.');
223
305
  }
306
+ const apiContract = getCustomProviderApiContract(options.customProviderApi);
307
+ if (apiContract.adapter === 'openai-responses') {
308
+ const hasExplicitAuthorizationHeader = Object.keys(options.headers ?? {}).some((header) => header.toLowerCase() === 'authorization');
309
+ const providerInstance = createOpenAI({
310
+ name: 'custom',
311
+ // Prevent the OpenAI adapter from falling back to OPENAI_API_KEY for
312
+ // a Custom provider. A configured Authorization header can still
313
+ // override this placeholder for non-Bearer authentication schemes.
314
+ apiKey: options.apiKey ?? '',
315
+ baseURL: options.baseURL,
316
+ headers: options.headers,
317
+ fetch: maybeCreateProviderProcessingFetch(options, {
318
+ omitGeneratedEmptyBearer: !options.apiKey && !hasExplicitAuthorizationHeader,
319
+ }),
320
+ });
321
+ return providerInstance.responses(modelId);
322
+ }
224
323
  const providerInstance = createOpenAICompatible({
225
324
  name: 'custom',
226
325
  apiKey: options.apiKey,
227
326
  baseURL: options.baseURL,
228
327
  headers: options.headers,
229
328
  includeUsage: false,
230
- fetch: maybeCreateRequestBodyCapturingFetch(options),
329
+ fetch: maybeCreateProviderProcessingFetch(options),
231
330
  });
232
331
  const model = providerInstance.chatModel(modelId);
233
332
  // 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) {
@@ -39,10 +30,6 @@ function applyAccumulatedUsage(result, usage, outputUsage) {
39
30
  return;
40
31
  }
41
32
  result.usage = usage;
42
- result.commonOutputs['responseTokens'] = {
43
- type: 'number',
44
- value: usage.completionTokens,
45
- };
46
33
  if (outputUsage) {
47
34
  result.commonOutputs['usage'] = {
48
35
  type: 'object',
@@ -74,9 +61,25 @@ function applyAccumulatedReasoning(result, reasoningRounds, outputReasoning) {
74
61
  };
75
62
  }
76
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
+ }
77
76
  export async function runChatV2PipelineWithToolContinuation(options) {
78
- const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline = runChatV2Pipeline, ...pipelineOptions } = options;
79
- 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
+ });
80
83
  const maxRounds = Math.max(1, Math.floor(Number.isFinite(maxToolRounds) ? maxToolRounds : 1));
81
84
  let currentPrompt = pipelineOptions.prompt;
82
85
  let currentSystemPrompt = pipelineOptions.systemPrompt;
@@ -88,42 +91,72 @@ export async function runChatV2PipelineWithToolContinuation(options) {
88
91
  ...pipelineOptions,
89
92
  functions,
90
93
  prompt: currentPrompt,
94
+ roundIndex: completedRounds,
91
95
  systemPrompt: currentSystemPrompt,
92
96
  });
93
97
  accumulatedUsage = autoContinue ? addUsage(accumulatedUsage, result.usage) : undefined;
94
98
  if (autoContinue) {
95
99
  appendReasoningRound(reasoningRounds, result.reasoning);
96
100
  }
97
- if (!autoContinue || completedRounds >= maxRounds || !canAutoContinue(result.functionCalls, toolNames)) {
98
- if (result.functionCalls.length === 0 && delegatedToolCalls.length > 0 && pipelineOptions.includeFunctionCalls) {
99
- result.commonOutputs['function-calls'] = {
100
- type: 'object[]',
101
- value: delegatedToolCalls,
102
- };
103
- }
104
- if (autoContinue) {
105
- applyAccumulatedUsage(result, accumulatedUsage, pipelineOptions.outputUsage);
106
- applyAccumulatedReasoning(result, reasoningRounds, pipelineOptions.outputReasoning);
107
- }
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
+ });
108
111
  return result;
109
112
  }
110
- const toolResultMessages = delegateToolCallRound
111
- ? await delegateToolCallRound(result.functionCalls, result.response)
112
- : 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
+ });
113
136
  delegatedToolCalls.push(...toolResultMessages
114
137
  .map((message) => message.delegatedToolCall)
115
138
  .filter((record) => record != null));
116
- if (shouldReturnToolResultDirectly(result.functionCalls, functions)) {
139
+ if (decision.kind === 'direct-tool-response') {
117
140
  const directResultMessage = toolResultMessages[0]?.value;
118
141
  if (directResultMessage?.type !== 'function' || typeof directResultMessage.message !== 'string') {
119
142
  throw new Error('Return directly requires the delegated tool handler to return a string output.');
120
143
  }
121
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
+ }
122
156
  result.allMessages = [...result.allMessages, directResultMessage];
123
157
  result.functionCalls = [];
124
158
  result.commonOutputs['response'] = {
125
- type: 'string',
126
- value: result.response,
159
+ ...materializedDirectResponse.value,
127
160
  };
128
161
  result.commonOutputs['all-messages'] = {
129
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
+ }
@@ -10,6 +10,7 @@ import { match } from 'ts-pattern';
10
10
  import { getNextVariadicPortIndex } from './variadicPortIndex.js';
11
11
  const messageTypeToTitle = {
12
12
  assistant: 'Assistant',
13
+ developer: 'Developer',
13
14
  function: 'Function Tool Call',
14
15
  system: 'System',
15
16
  user: 'User',
@@ -81,6 +82,7 @@ export class AssembleMessageNodeImpl extends NodeImpl {
81
82
  dataKey: 'type',
82
83
  options: [
83
84
  { value: 'system', label: 'System' },
85
+ { value: 'developer', label: 'Developer' },
84
86
  { value: 'user', label: 'User' },
85
87
  { value: 'assistant', label: 'Assistant' },
86
88
  { value: 'function', label: 'Function' },
@@ -123,6 +125,10 @@ export class AssembleMessageNodeImpl extends NodeImpl {
123
125
  .with('system', (type) => ({
124
126
  type,
125
127
  message: [],
128
+ }))
129
+ .with('developer', (type) => ({
130
+ type,
131
+ message: [],
126
132
  }))
127
133
  .with('user', (type) => ({
128
134
  type,
@@ -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
  }
@@ -39,10 +39,22 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
39
39
  }
40
40
  getOutputDefinitions() {
41
41
  const outputs = [];
42
+ outputs.push({
43
+ id: 'tool-name',
44
+ dataType: ['string', 'string[]'],
45
+ title: 'Tool Name',
46
+ description: 'The name of the tool selected by the LLM.',
47
+ });
48
+ outputs.push({
49
+ id: 'tool-arguments',
50
+ dataType: ['object', 'object[]'],
51
+ title: 'Tool Arguments',
52
+ description: 'The resolved arguments passed to the selected tool.',
53
+ });
42
54
  outputs.push({
43
55
  id: 'assistant-message',
44
56
  dataType: 'string',
45
- title: 'Message (fires before tool call invocation)',
57
+ title: 'Message',
46
58
  description: 'Nonblank text the assistant emitted alongside a connected tool-call round. This output fires before the tools are invoked.',
47
59
  });
48
60
  outputs.push({
@@ -51,6 +63,12 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
51
63
  title: 'Output',
52
64
  description: 'The output of the tool call.',
53
65
  });
66
+ outputs.push({
67
+ id: 'execution-time',
68
+ dataType: ['number', 'number[]'],
69
+ title: 'Tool Execution Time (sec)',
70
+ description: 'Seconds spent running the tool handler graph or external function.',
71
+ });
54
72
  outputs.push({
55
73
  id: 'message',
56
74
  dataType: ['chat-message', 'chat-message[]', 'object', 'object[]'],
@@ -59,6 +77,13 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
59
77
  });
60
78
  return outputs;
61
79
  }
80
+ getRunActivityDescriptor() {
81
+ return {
82
+ category: 'tool',
83
+ primaryOutputPortId: 'output',
84
+ fullOutputActionLabel: 'Open tool result',
85
+ };
86
+ }
62
87
  static getUIData() {
63
88
  return {
64
89
  infoBoxBody: dedent `