@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.
- package/dist/cjs/bundle.cjs +3596 -1745
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +298 -21
- package/dist/cjs/webAppRuntime.cjs.map +4 -4
- package/dist/esm/exports.js +1 -0
- package/dist/esm/model/AgentResponseTrace.js +448 -0
- package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
- package/dist/esm/model/GraphProcessor.js +151 -74
- package/dist/esm/model/NodeImpl.js +6 -0
- package/dist/esm/model/ProcessContextBuilder.js +3 -1
- package/dist/esm/model/RecordingPlayer.js +164 -22
- package/dist/esm/model/SplitRunProcessor.js +49 -8
- package/dist/esm/model/SubprocessorBridge.js +2 -0
- package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
- package/dist/esm/model/UiGraph.js +21 -0
- package/dist/esm/model/UiGraphActionProtocol.js +2 -0
- package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
- package/dist/esm/model/UiGraphRendererStyles.js +221 -0
- package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
- package/dist/esm/model/UiGraphSchema.js +7 -1
- package/dist/esm/model/chat/aiSdkTools.js +3 -2
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +9 -5
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +42 -16
- package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
- package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +61 -146
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +8 -2
- package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
- package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
- package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
- package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
- package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
- package/dist/esm/model/chat-v2/chatV2Types.js +5 -9
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
- package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
- package/dist/esm/model/chat-v2/index.js +12 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
- package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +6 -50
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -13
- package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +121 -193
- package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
- package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
- package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
- package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
- package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
- package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
- package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
- package/dist/esm/model/chat-v2/llmProfile.js +10 -65
- package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +55 -99
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
- package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
- package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
- package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
- package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
- package/dist/esm/model/chat-v2/providerOptions.js +86 -20
- package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
- package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
- package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
- package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
- package/dist/esm/model/nodes/ChatNode.js +6 -0
- package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
- package/dist/esm/model/nodes/LLMChatV2Node.js +112 -229
- package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
- package/dist/esm/model/nodes/PromptNode.js +7 -0
- package/dist/esm/model/nodes/ToolNode.js +7 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
- package/dist/esm/plugins/anthropic/anthropic.js +4 -4
- package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
- package/dist/esm/plugins/google/google.js +5 -9
- package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
- package/dist/esm/recording/ExecutionRecorder.js +13 -5
- package/dist/esm/utils/emitDetached.js +6 -3
- package/dist/esm/utils/openai.js +60 -16
- package/dist/esm/utils/serialization/serialization.js +2 -19
- package/dist/esm/webAppRuntime.js +3 -2
- package/dist/types/exports.d.ts +1 -0
- package/dist/types/model/AgentResponseTrace.d.ts +110 -0
- package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
- package/dist/types/model/ExecutorProtocol.d.ts +25 -7
- package/dist/types/model/GraphProcessor.d.ts +27 -5
- package/dist/types/model/NodeImpl.d.ts +18 -1
- package/dist/types/model/Nodes.d.ts +2 -2
- package/dist/types/model/ProcessContext.d.ts +47 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
- package/dist/types/model/RecordingPlayer.d.ts +6 -0
- package/dist/types/model/SplitRunProcessor.d.ts +10 -3
- package/dist/types/model/UiGraph.d.ts +8 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
- package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
- package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
- package/dist/types/model/UiGraphSchema.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -3
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
- package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
- package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +4 -0
- package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
- package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
- package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
- package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
- package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2Types.d.ts +20 -10
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
- package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
- package/dist/types/model/chat-v2/index.d.ts +12 -0
- package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
- package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
- package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -3
- package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
- package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
- package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
- package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
- package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
- package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
- package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
- package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
- package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
- package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +17 -49
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
- package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
- package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
- package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
- package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
- package/dist/types/model/chat-v2/providerOptions.d.ts +10 -0
- package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
- package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
- package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
- package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
- package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
- package/dist/types/model/nodes/ChatNode.d.ts +2 -1
- package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
- package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
- package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
- package/dist/types/model/nodes/PromptNode.d.ts +4 -1
- package/dist/types/model/nodes/ToolNode.d.ts +2 -1
- package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
- package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
- package/dist/types/plugins/google/google.d.ts +2 -8
- package/dist/types/recording/RecordedEvents.d.ts +6 -0
- package/dist/types/utils/emitDetached.d.ts +3 -2
- package/dist/types/utils/openai.d.ts +49 -0
- package/dist/types/webAppRuntime.d.ts +4 -2
- 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
|
|
88
|
-
|
|
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
|
-
|
|
92
|
+
url = new URL(endpoint);
|
|
94
93
|
}
|
|
95
|
-
catch {
|
|
96
|
-
|
|
94
|
+
catch (cause) {
|
|
95
|
+
throw new Error('Custom provider base URL must be a valid absolute HTTP or HTTPS URL.', { cause });
|
|
97
96
|
}
|
|
97
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
98
|
+
throw new Error('Custom provider base URL must use HTTP or HTTPS.');
|
|
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
|
|
112
|
+
return normalizeOpenAICompatibleEndpoint(endpoint).baseURL;
|
|
101
113
|
}
|
|
102
114
|
function parseBodyText(text) {
|
|
103
115
|
try {
|
|
@@ -162,7 +174,22 @@ function removeStaleContentLength(headers) {
|
|
|
162
174
|
nextHeaders.delete('content-length');
|
|
163
175
|
return nextHeaders;
|
|
164
176
|
}
|
|
165
|
-
function
|
|
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) {
|
|
166
193
|
return async (input, init) => {
|
|
167
194
|
const parsedBody = parseFetchBody(init?.body);
|
|
168
195
|
const processedBody = parsedBody !== undefined && options.transformRequestBody != null
|
|
@@ -172,20 +199,41 @@ function createRequestBodyProcessingFetch(options) {
|
|
|
172
199
|
options.onRequestBody?.(cloneCapturedRequestBody(processedBody));
|
|
173
200
|
}
|
|
174
201
|
const nativeFetch = globalThis.fetch;
|
|
175
|
-
|
|
202
|
+
let processedInit = processedBody !== parsedBody
|
|
176
203
|
? {
|
|
177
204
|
...init,
|
|
178
205
|
body: serializeTransformedFetchBody(init?.body, processedBody),
|
|
179
206
|
headers: removeStaleContentLength(init?.headers),
|
|
180
207
|
}
|
|
181
208
|
: init;
|
|
182
|
-
|
|
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;
|
|
183
225
|
};
|
|
184
226
|
}
|
|
185
|
-
function
|
|
186
|
-
|
|
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
|
|
187
235
|
? undefined
|
|
188
|
-
:
|
|
236
|
+
: createProviderProcessingFetch(options, { omitGeneratedEmptyBearer, endpointQuery });
|
|
189
237
|
}
|
|
190
238
|
export async function resolveChatV2ProviderConfig(provider, _modelId, context, options = {}) {
|
|
191
239
|
const headers = cleanHeaders({
|
|
@@ -213,8 +261,9 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
|
|
|
213
261
|
if (!configuredBaseURL) {
|
|
214
262
|
throw new Error('Provider base URL is required when provider is Custom provider.');
|
|
215
263
|
}
|
|
264
|
+
const endpoint = normalizeOpenAICompatibleEndpoint(configuredBaseURL);
|
|
216
265
|
return {
|
|
217
|
-
|
|
266
|
+
...endpoint,
|
|
218
267
|
headers: Object.keys(headers).length > 0 ? headers : undefined,
|
|
219
268
|
};
|
|
220
269
|
}
|
|
@@ -228,7 +277,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
|
|
|
228
277
|
organization: context.settings.openAiOrganization || undefined,
|
|
229
278
|
baseURL: undefined,
|
|
230
279
|
headers: options.headers,
|
|
231
|
-
fetch:
|
|
280
|
+
fetch: maybeCreateProviderProcessingFetch(options),
|
|
232
281
|
});
|
|
233
282
|
return providerInstance.responses(modelId);
|
|
234
283
|
}
|
|
@@ -237,7 +286,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
|
|
|
237
286
|
apiKey: options.apiKey || context.settings.anthropicApiKey || context.getPluginConfig('anthropicApiKey') || undefined,
|
|
238
287
|
baseURL: undefined,
|
|
239
288
|
headers: options.headers,
|
|
240
|
-
fetch:
|
|
289
|
+
fetch: maybeCreateProviderProcessingFetch(options),
|
|
241
290
|
});
|
|
242
291
|
return providerInstance.messages(modelId);
|
|
243
292
|
}
|
|
@@ -246,7 +295,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
|
|
|
246
295
|
apiKey: options.apiKey || context.settings.googleApiKey || context.getPluginConfig('googleApiKey') || undefined,
|
|
247
296
|
baseURL: undefined,
|
|
248
297
|
headers: options.headers,
|
|
249
|
-
fetch:
|
|
298
|
+
fetch: maybeCreateProviderProcessingFetch(options),
|
|
250
299
|
});
|
|
251
300
|
return providerInstance.chat(modelId);
|
|
252
301
|
}
|
|
@@ -254,13 +303,30 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
|
|
|
254
303
|
if (!options.baseURL) {
|
|
255
304
|
throw new Error('Provider base URL is required when provider is Custom provider.');
|
|
256
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
|
+
}
|
|
257
323
|
const providerInstance = createOpenAICompatible({
|
|
258
324
|
name: 'custom',
|
|
259
325
|
apiKey: options.apiKey,
|
|
260
326
|
baseURL: options.baseURL,
|
|
261
327
|
headers: options.headers,
|
|
262
328
|
includeUsage: false,
|
|
263
|
-
fetch:
|
|
329
|
+
fetch: maybeCreateProviderProcessingFetch(options),
|
|
264
330
|
});
|
|
265
331
|
const model = providerInstance.chatModel(modelId);
|
|
266
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 {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
|
|
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
|
|
75
|
-
const
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
|
107
|
-
|
|
108
|
-
|
|
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 (
|
|
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
|
-
|
|
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 `
|
|
@@ -39,12 +39,6 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
|
|
|
39
39
|
}
|
|
40
40
|
getOutputDefinitions() {
|
|
41
41
|
const outputs = [];
|
|
42
|
-
outputs.push({
|
|
43
|
-
id: 'assistant-message',
|
|
44
|
-
dataType: 'string',
|
|
45
|
-
title: 'Message (fires before tool call invocation)',
|
|
46
|
-
description: 'Nonblank text the assistant emitted alongside a connected tool-call round. This output fires before the tools are invoked.',
|
|
47
|
-
});
|
|
48
42
|
outputs.push({
|
|
49
43
|
id: 'tool-name',
|
|
50
44
|
dataType: ['string', 'string[]'],
|
|
@@ -57,12 +51,24 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
|
|
|
57
51
|
title: 'Tool Arguments',
|
|
58
52
|
description: 'The resolved arguments passed to the selected tool.',
|
|
59
53
|
});
|
|
54
|
+
outputs.push({
|
|
55
|
+
id: 'assistant-message',
|
|
56
|
+
dataType: 'string',
|
|
57
|
+
title: 'Message',
|
|
58
|
+
description: 'Nonblank text the assistant emitted alongside a connected tool-call round. This output fires before the tools are invoked.',
|
|
59
|
+
});
|
|
60
60
|
outputs.push({
|
|
61
61
|
id: 'output',
|
|
62
62
|
dataType: ['string', 'string[]'],
|
|
63
63
|
title: 'Output',
|
|
64
64
|
description: 'The output of the tool call.',
|
|
65
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
|
+
});
|
|
66
72
|
outputs.push({
|
|
67
73
|
id: 'message',
|
|
68
74
|
dataType: ['chat-message', 'chat-message[]', 'object', 'object[]'],
|
|
@@ -71,6 +77,13 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
|
|
|
71
77
|
});
|
|
72
78
|
return outputs;
|
|
73
79
|
}
|
|
80
|
+
getRunActivityDescriptor() {
|
|
81
|
+
return {
|
|
82
|
+
category: 'tool',
|
|
83
|
+
primaryOutputPortId: 'output',
|
|
84
|
+
fullOutputActionLabel: 'Open tool result',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
74
87
|
static getUIData() {
|
|
75
88
|
return {
|
|
76
89
|
infoBoxBody: dedent `
|