@valerypopoff/rivet2-core 2.1.7 → 2.1.9

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 (115) hide show
  1. package/dist/cjs/bundle.cjs +4911 -2546
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +45 -4
  4. package/dist/esm/exports.js +2 -0
  5. package/dist/esm/integrations/KnowledgeStoreFieldPolicy.js +216 -0
  6. package/dist/esm/integrations/KnowledgeStoreProvider.js +14 -90
  7. package/dist/esm/integrations/ManagedKnowledgeStore.js +0 -8
  8. package/dist/esm/model/DataBusPorts.js +26 -0
  9. package/dist/esm/model/DataBusTopology.js +207 -0
  10. package/dist/esm/model/DataValue.js +22 -7
  11. package/dist/esm/model/GraphPreprocessor.js +9 -3
  12. package/dist/esm/model/GraphProcessor.js +164 -366
  13. package/dist/esm/model/NodeIO.js +1 -0
  14. package/dist/esm/model/NodePrefabResolver.js +16 -0
  15. package/dist/esm/model/Nodes.js +7 -0
  16. package/dist/esm/model/SplitRunProcessor.js +19 -10
  17. package/dist/esm/model/ToolCallContinuationBranchPlanner.js +165 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +206 -0
  19. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +142 -0
  21. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  22. package/dist/esm/model/chat-v2/chatV2Errors.js +23 -6
  23. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  24. package/dist/esm/model/chat-v2/chatV2Pipeline.js +167 -56
  25. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  26. package/dist/esm/model/chat-v2/chatV2ProviderTypes.js +1 -0
  27. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  28. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  30. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  31. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  32. package/dist/esm/model/chat-v2/index.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +53 -3
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +53 -19
  35. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +232 -68
  36. package/dist/esm/model/chat-v2/llmProfile.js +212 -0
  37. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +73 -0
  39. package/dist/esm/model/chat-v2/llmProfileTypes.js +45 -0
  40. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  41. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  42. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  43. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  44. package/dist/esm/model/nodes/DataBusNode.js +81 -0
  45. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  46. package/dist/esm/model/nodes/GetGlobalNode.js +7 -11
  47. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +1 -1
  48. package/dist/esm/model/nodes/LLMChatV2Node.js +156 -18
  49. package/dist/esm/model/nodes/LLMProfileNode.js +132 -0
  50. package/dist/esm/model/nodes/PassthroughNode.js +1 -11
  51. package/dist/esm/model/nodes/PromptNode.js +9 -2
  52. package/dist/esm/model/nodes/SearchKnowledgeNode.js +1 -1
  53. package/dist/esm/model/nodes/SetGlobalNode.js +6 -6
  54. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +0 -1
  55. package/dist/esm/model/nodes/toolCallDelegation.js +31 -4
  56. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  57. package/dist/esm/plugins/google/google.js +20 -9
  58. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  59. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +0 -4
  60. package/dist/esm/plugins/pinecone/plugin.js +1 -1
  61. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  62. package/dist/esm/utils/coerceType.js +84 -41
  63. package/dist/esm/utils/expectType.js +45 -8
  64. package/dist/esm/utils/fetchEventSource.js +18 -0
  65. package/dist/esm/utils/serialization/serialization.js +37 -7
  66. package/dist/esm/vendor/fnv1a.js +6 -3
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +2 -0
  69. package/dist/types/integrations/KnowledgeStore.d.ts +0 -2
  70. package/dist/types/integrations/KnowledgeStoreFieldPolicy.d.ts +38 -0
  71. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +6 -3
  72. package/dist/types/model/DataBusPorts.d.ts +6 -0
  73. package/dist/types/model/DataBusTopology.d.ts +16 -0
  74. package/dist/types/model/DataValue.d.ts +22 -6
  75. package/dist/types/model/GraphPreprocessor.d.ts +2 -1
  76. package/dist/types/model/GraphProcessor.d.ts +4 -3
  77. package/dist/types/model/NodeBase.d.ts +6 -0
  78. package/dist/types/model/NodeIO.d.ts +5 -0
  79. package/dist/types/model/NodePrefabResolver.d.ts +9 -0
  80. package/dist/types/model/Nodes.d.ts +5 -2
  81. package/dist/types/model/ProcessContext.d.ts +64 -0
  82. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  83. package/dist/types/model/ToolCallContinuationBranchPlanner.d.ts +43 -0
  84. package/dist/types/model/ToolCallContinuationCoordinator.d.ts +70 -0
  85. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +10 -0
  86. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  87. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  88. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  89. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  90. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -0
  91. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  92. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +8 -0
  93. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  94. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -3
  95. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  96. package/dist/types/model/chat-v2/index.d.ts +1 -0
  97. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  98. package/dist/types/model/chat-v2/llmChatV2NodeEditors.d.ts +5 -1
  99. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  100. package/dist/types/model/chat-v2/llmProfile.d.ts +10 -0
  101. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  102. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +9 -0
  103. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +18 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  105. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  106. package/dist/types/model/nodes/DataBusNode.d.ts +19 -0
  107. package/dist/types/model/nodes/LLMProfileNode.d.ts +20 -0
  108. package/dist/types/model/nodes/PassthroughNode.d.ts +2 -15
  109. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  110. package/dist/types/model/nodes/SetGlobalNode.d.ts +2 -2
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +9 -0
  112. package/dist/types/plugins/google/google.d.ts +12 -1
  113. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  114. package/dist/types/vendor/fnv1a.d.ts +5 -5
  115. package/package.json +1 -1
@@ -1,12 +1,18 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
- import { getInputOrData } from '../../utils/inputs.js';
2
+ import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
3
+ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
4
+ import { getInstructionMessageRoles, restoreOpenAICompatibleInstructionRoles } from './developerMessageRoles.js';
3
5
  import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
4
6
  import { hasLLMChatV2ToolResponseFormatConflict, LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY, } from './chatV2FeatureCompatibility.js';
5
- import { parseChatV2Provider } from './providerOptions.js';
7
+ import { createLLMProfileFallbackRunner } from './llmProfileFallback.js';
8
+ import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput } from './llmProfile.js';
9
+ import { parseChatV2Provider, resolveChatV2ProviderConfig } from './providerOptions.js';
6
10
  import { createResolvedChatV2Provider, resolveChatV2Credential } from './chatV2ProviderProfile.js';
11
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError, } from './chatV2Types.js';
7
12
  import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolveLLMChatV2EditorCache, } from './chatV2EditorCache.js';
8
13
  import { resolveLLMChatV2BuiltInTools, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, resolveLLMChatV2RuntimeProviderOptions, resolveLLMChatV2ToolChoice, } from './chatV2RuntimeOptions.js';
9
- import { hasLLMChatV2BuiltInToolsEnabled, } from './llmChatV2NodeData.js';
14
+ import { shouldIncludeLLMChatV2ToolCalls, } from './llmChatV2NodeData.js';
15
+ import { runChatV2Pipeline } from './chatV2Pipeline.js';
10
16
  export { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs };
11
17
  export { resolveLLMChatV2RuntimeProviderOptions } from './chatV2RuntimeOptions.js';
12
18
  function resolveLLMChatV2BaseURL(data, inputs) {
@@ -15,95 +21,253 @@ function resolveLLMChatV2BaseURL(data, inputs) {
15
21
  undefined
16
22
  : undefined;
17
23
  }
18
- export async function resolveLLMChatV2RuntimeConfig(params) {
19
- const { data, nodeId, inputs, context } = params;
20
- if (hasLLMChatV2ToolResponseFormatConflict(data)) {
24
+ function createSharedRunOptions(params) {
25
+ const { shared, provider, modelId } = params;
26
+ return {
27
+ provider,
28
+ // From profile mode replaces this before a provider request. Keeping the
29
+ // field populated preserves the established Tool Continuation contract.
30
+ model: undefined,
31
+ modelId,
32
+ prompt: shared.prompt,
33
+ systemPrompt: shared.systemPrompt,
34
+ functions: shared.functions,
35
+ responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
36
+ responseFormat: shared.responseFormatParameters?.responseFormat,
37
+ outputUsage: shared.data.outputUsage,
38
+ outputReasoning: shared.data.outputReasoning,
39
+ outputRequestStatus: shared.data.outputRequestStatus,
40
+ outputRequestError: shouldOutputChatV2RequestError(shared.data),
41
+ outputRequestBody: shouldOutputChatV2RequestBody(shared.data),
42
+ includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(shared.data),
43
+ emitPartialOutputs: shared.data.useAsGraphPartialOutput,
44
+ toolChoice: shared.toolChoice,
45
+ requestBodies: shared.requestBodies,
46
+ retryOnNon200: shared.data.retryOnNon200,
47
+ retryOnNon200RepeatTimes: shared.data.retryOnNon200RepeatTimes,
48
+ retryOnNon200CooldownMs: shared.data.retryOnNon200CooldownMs,
49
+ context: shared.context,
50
+ };
51
+ }
52
+ function createRuntimeProviderProfile(params) {
53
+ const provider = parseChatV2Provider(params.data.provider);
54
+ return {
55
+ provider,
56
+ modelId: getInputOrData(params.data, params.inputs, 'model', 'string'),
57
+ baseURL: resolveLLMChatV2BaseURL(params.data, params.inputs),
58
+ hasCustomHeaders: Object.keys(resolveLLMChatV2Headers(params.data, params.inputs) ?? {}).length > 0,
59
+ credential: params.credential.reference,
60
+ capabilities: {
61
+ builtInTools: provider === 'openai' || provider === 'google',
62
+ structuredOutput: true,
63
+ },
64
+ };
65
+ }
66
+ async function resolveCandidateRunOptions(params) {
67
+ const { shared, profile, roundOptions } = params;
68
+ const effectiveData = profile ? applyLLMProfileToNodeData(shared.data, profile) : shared.data;
69
+ if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
21
70
  throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
22
71
  }
23
- const provider = parseChatV2Provider(data.provider);
24
- const modelId = getInputOrData(data, inputs, 'model', 'string');
25
- const baseURL = resolveLLMChatV2BaseURL(data, inputs);
26
- const nodeHeaders = resolveLLMChatV2Headers(data, inputs);
27
- const credential = resolveChatV2Credential({
28
- provider,
29
- context,
30
- apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
31
- inputs,
32
- customProgrammaticName: data.customProviderApiKeyProgrammaticName,
33
- customEnvironmentName: data.customProviderApiKeyEnvVarName,
34
- });
35
- const apiKey = credential.value;
36
- const requestBodies = data.outputRequestStatus ? [] : undefined;
72
+ const provider = parseChatV2Provider(effectiveData.provider);
73
+ const modelId = getInputOrData(effectiveData, shared.inputs, 'model', 'string');
74
+ const baseURL = resolveLLMChatV2BaseURL(effectiveData, shared.inputs);
75
+ const headers = resolveLLMChatV2Headers(effectiveData, shared.inputs);
76
+ const credential = profile?.credential ??
77
+ resolveChatV2Credential({
78
+ provider,
79
+ context: shared.context,
80
+ apiKeySource: effectiveData.apiKeySource === 'input' ? 'input' : 'configured',
81
+ inputs: shared.inputs,
82
+ customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
83
+ customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName,
84
+ });
85
+ const transformRequestBody = (provider === 'openai' || provider === 'custom') && shared.instructionRoles.includes('developer')
86
+ ? (body) => restoreOpenAICompatibleInstructionRoles(body, shared.instructionRoles)
87
+ : undefined;
37
88
  const resolvedProvider = await createResolvedChatV2Provider({
38
89
  provider,
39
90
  modelId,
40
- context,
91
+ context: shared.context,
41
92
  baseURL,
42
- headers: nodeHeaders,
93
+ headers,
43
94
  credential,
44
- onRequestBody: requestBodies == null ? undefined : (body) => requestBodies.push(body),
95
+ onRequestBody: shared.requestBodies == null ? undefined : (body) => shared.requestBodies.push(body),
96
+ transformRequestBody,
45
97
  });
46
- const providerConfig = resolvedProvider.config;
47
- const model = resolvedProvider.model;
48
- const prompt = inputs['prompt'];
49
- const systemPrompt = inputs['systemPrompt'];
50
- const functions = data.useToolCalling && inputs['functions'] != null
51
- ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
52
- : undefined;
53
- const toolChoice = resolveLLMChatV2ToolChoice(data);
54
- const responseFormatParameters = resolveChatV2ResponseFormatParameters(data, inputs);
55
- const providerOptions = mergeCustomProviderResponseFormatOptions(provider, resolveLLMChatV2RuntimeProviderOptions(data, inputs), responseFormatParameters);
56
- const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
57
- const runOptions = {
98
+ const generationParameters = resolveLLMChatV2GenerationParameters(effectiveData, shared.inputs);
99
+ const providerOptions = mergeCustomProviderResponseFormatOptions(provider, resolveLLMChatV2RuntimeProviderOptions(effectiveData, shared.inputs), shared.responseFormatParameters);
100
+ return {
101
+ ...roundOptions,
58
102
  provider,
59
- model,
103
+ model: resolvedProvider.model,
60
104
  modelId,
61
- prompt,
62
- systemPrompt,
63
- functions,
64
- additionalTools: resolveLLMChatV2BuiltInTools(data, context, providerConfig, apiKey),
105
+ additionalTools: resolveLLMChatV2BuiltInTools(effectiveData, shared.context, resolvedProvider.config, credential.value),
65
106
  ...generationParameters,
66
- responseOutput: createChatV2ResponseOutput(responseFormatParameters, provider),
67
- responseFormat: responseFormatParameters?.responseFormat,
68
- outputUsage: data.outputUsage,
69
- outputReasoning: data.outputReasoning,
70
- outputRequestStatus: data.outputRequestStatus,
71
- includeFunctionCalls: data.useToolCalling || hasLLMChatV2BuiltInToolsEnabled(data),
72
- emitPartialOutputs: data.useAsGraphPartialOutput,
107
+ responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
108
+ responseFormat: shared.responseFormatParameters?.responseFormat,
73
109
  providerOptions,
74
- toolChoice,
75
- anthropicCacheControlTtl: provider === 'anthropic' ? data.anthropicCacheControlTtl || undefined : undefined,
76
- requestBodies,
77
- retryOnNon200: data.retryOnNon200,
78
- retryOnNon200RepeatTimes: data.retryOnNon200RepeatTimes,
79
- retryOnNon200CooldownMs: data.retryOnNon200CooldownMs,
110
+ anthropicCacheControlTtl: provider === 'anthropic' ? effectiveData.anthropicCacheControlTtl || undefined : undefined,
111
+ requestBodies: shared.requestBodies,
112
+ };
113
+ }
114
+ function createSharedRuntimeValues(params) {
115
+ const { data, inputs, context } = params;
116
+ const prompt = inputs['prompt'];
117
+ const systemPrompt = inputs['systemPrompt'];
118
+ return {
119
+ data,
120
+ inputs,
80
121
  context,
122
+ prompt,
123
+ systemPrompt,
124
+ functions: data.useToolCalling && inputs['functions'] != null
125
+ ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
126
+ : undefined,
127
+ responseFormatParameters: resolveChatV2ResponseFormatParameters(data, inputs),
128
+ toolChoice: resolveLLMChatV2ToolChoice(data),
129
+ requestBodies: shouldOutputChatV2RequestBody(data) ? [] : undefined,
130
+ instructionRoles: getInstructionMessageRoles(prependSystemPrompt(coercePromptToChatMessages(prompt), systemPrompt)),
81
131
  };
132
+ }
133
+ export async function resolveLLMChatV2RuntimeConfig(params) {
134
+ const { data, nodeId, inputs, context } = params;
135
+ const profileInput = inputs['llmProfile'];
136
+ if (data.configurationMode === 'profile' && profileInput == null) {
137
+ throw new Error('LLM Profile input is required when Configuration is From profile.');
138
+ }
139
+ const shared = createSharedRuntimeValues({ data, inputs, context });
82
140
  const editorCache = data.cache ? context.editorExecutionCache : undefined;
141
+ if (data.configurationMode !== 'profile') {
142
+ const inlineRunOptions = await resolveCandidateRunOptions({
143
+ shared,
144
+ profile: undefined,
145
+ roundOptions: createSharedRunOptions({
146
+ shared,
147
+ provider: parseChatV2Provider(data.provider),
148
+ modelId: data.model,
149
+ }),
150
+ });
151
+ const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
152
+ const inlineCredential = resolveChatV2Credential({
153
+ provider: inlineRunOptions.provider,
154
+ context,
155
+ apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
156
+ inputs,
157
+ customProgrammaticName: data.customProviderApiKeyProgrammaticName,
158
+ customEnvironmentName: data.customProviderApiKeyEnvVarName,
159
+ });
160
+ const inlineProviderConfig = await resolveChatV2ProviderConfig(inlineRunOptions.provider, inlineRunOptions.modelId, context, {
161
+ baseURL: resolveLLMChatV2BaseURL(data, inputs),
162
+ headers: resolveLLMChatV2Headers(data, inputs),
163
+ });
164
+ const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
165
+ apiKey: inlineCredential.value,
166
+ data,
167
+ editorCache,
168
+ functions: shared.functions,
169
+ generationParameters,
170
+ modelId: inlineRunOptions.modelId,
171
+ nodeId,
172
+ prompt: shared.prompt,
173
+ provider: inlineRunOptions.provider,
174
+ providerConfig: inlineProviderConfig,
175
+ providerOptions: inlineRunOptions.providerOptions,
176
+ responseFormatParameters: shared.responseFormatParameters,
177
+ systemPrompt: shared.systemPrompt,
178
+ toolChoice: shared.toolChoice,
179
+ });
180
+ return {
181
+ runOptions: inlineRunOptions,
182
+ providerProfile: createRuntimeProviderProfile({
183
+ data,
184
+ inputs,
185
+ credential: inlineCredential,
186
+ }),
187
+ runPipeline: runChatV2Pipeline,
188
+ functions: shared.functions,
189
+ cacheKey,
190
+ cachedOutputs,
191
+ editorCache,
192
+ shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
193
+ maxToolRounds: data.maxToolRounds ?? 3,
194
+ profileAttempts: undefined,
195
+ profileChainUsesArray: false,
196
+ profileChainLength: undefined,
197
+ getProfileSummary: undefined,
198
+ isProfileFallbackExhausted: () => false,
199
+ };
200
+ }
201
+ const profiles = normalizeLLMProfileChainInput(profileInput?.value);
202
+ const firstProfile = profiles[0];
203
+ const firstProvider = parseChatV2Provider(firstProfile.configuration.provider);
204
+ const profileRunOptions = createSharedRunOptions({
205
+ shared,
206
+ provider: firstProvider,
207
+ modelId: firstProfile.configuration.model,
208
+ });
209
+ const firstProfileData = applyLLMProfileToNodeData(data, firstProfile);
210
+ Object.assign(profileRunOptions, {
211
+ ...resolveLLMChatV2GenerationParameters(firstProfileData, inputs),
212
+ providerOptions: mergeCustomProviderResponseFormatOptions(firstProvider, resolveLLMChatV2RuntimeProviderOptions(firstProfileData, inputs), shared.responseFormatParameters),
213
+ anthropicCacheControlTtl: firstProvider === 'anthropic' ? firstProfileData.anthropicCacheControlTtl || undefined : undefined,
214
+ });
215
+ const fallbackRunner = createLLMProfileFallbackRunner({
216
+ candidates: profiles.map((profile) => ({
217
+ provider: parseChatV2Provider(profile.configuration.provider),
218
+ model: profile.configuration.model,
219
+ credential: profile.credential.value,
220
+ redactionValues: [
221
+ ...profile.configuration.headers.map((header) => header.value),
222
+ ...Object.values(cleanHeaders(context.settings?.chatNodeHeaders ?? {})),
223
+ ],
224
+ })),
225
+ resolveCandidate: (profileIndex, roundOptions) => resolveCandidateRunOptions({
226
+ shared,
227
+ profile: profiles[profileIndex],
228
+ roundOptions,
229
+ }),
230
+ });
83
231
  const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
84
- apiKey,
85
- data,
232
+ apiKey: undefined,
233
+ data: firstProfileData,
86
234
  editorCache,
87
- functions,
88
- generationParameters,
89
- modelId,
235
+ functions: shared.functions,
236
+ generationParameters: undefined,
237
+ modelId: firstProfile.configuration.model,
90
238
  nodeId,
91
- prompt,
92
- provider,
93
- providerConfig,
94
- providerOptions,
95
- responseFormatParameters,
96
- systemPrompt,
97
- toolChoice,
239
+ prompt: shared.prompt,
240
+ provider: firstProvider,
241
+ // Profile headers are part of the individual profile fingerprints, but
242
+ // provider resolution also merges project-wide Chat headers. Include those
243
+ // values through the existing redacted provider-config fingerprint so a
244
+ // global-header edit cannot reuse a stale profile-mode editor cache entry.
245
+ providerConfig: { headers: cleanHeaders(context.settings?.chatNodeHeaders ?? {}) },
246
+ providerOptions: undefined,
247
+ responseFormatParameters: shared.responseFormatParameters,
248
+ systemPrompt: shared.systemPrompt,
249
+ toolChoice: shared.toolChoice,
250
+ profileChain: profiles,
251
+ profileChainUsesArray: Array.isArray(profileInput?.value),
98
252
  });
99
253
  return {
100
- providerProfile: resolvedProvider.profile,
101
- runOptions,
102
- functions,
254
+ runOptions: profileRunOptions,
255
+ providerProfile: createRuntimeProviderProfile({
256
+ data: firstProfileData,
257
+ inputs,
258
+ credential: firstProfile.credential,
259
+ }),
260
+ runPipeline: fallbackRunner.run,
261
+ functions: shared.functions,
103
262
  cacheKey,
104
263
  cachedOutputs,
105
264
  editorCache,
106
265
  shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
107
266
  maxToolRounds: data.maxToolRounds ?? 3,
267
+ profileAttempts: fallbackRunner.attempts,
268
+ profileChainUsesArray: Array.isArray(profileInput?.value),
269
+ profileChainLength: profiles.length,
270
+ getProfileSummary: fallbackRunner.summary,
271
+ isProfileFallbackExhausted: fallbackRunner.wasExhausted,
108
272
  };
109
273
  }
@@ -0,0 +1,212 @@
1
+ import { createLLMChatV2NodeData, } from './llmChatV2NodeData.js';
2
+ import { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData } from './llmProfileTypes.js';
3
+ export { applyLLMProfileToNodeData, createDefaultLLMProfileValue, createLLMProfileNodeData, LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, } from './llmProfileTypes.js';
4
+ const credentialSources = new Set([
5
+ 'input',
6
+ 'settings',
7
+ 'plugin',
8
+ 'programmatic',
9
+ 'environment',
10
+ 'none',
11
+ ]);
12
+ const profileProviders = new Set(['openai', 'anthropic', 'google', 'custom']);
13
+ const stringFields = [
14
+ 'model',
15
+ 'customProviderApiKeyProgrammaticName',
16
+ 'customProviderApiKeyEnvVarName',
17
+ 'customProviderBaseURL',
18
+ 'extraProviderOptions',
19
+ 'openAIReasoningEffort',
20
+ 'openAIReasoningSummary',
21
+ 'openAIPreviousResponseId',
22
+ ];
23
+ const booleanFields = [
24
+ 'useModelInput',
25
+ 'useTemperatureInput',
26
+ 'useTopPInput',
27
+ 'useTopKInput',
28
+ 'usePresencePenaltyInput',
29
+ 'useFrequencyPenaltyInput',
30
+ 'useStopSequencesInput',
31
+ 'useSeedInput',
32
+ 'useMaxTokensInput',
33
+ 'useCustomProviderBaseURLInput',
34
+ 'useHeadersInput',
35
+ 'useExtraProviderOptionsInput',
36
+ 'useOpenAIPreviousResponseIdInput',
37
+ 'enableOpenAIWebSearch',
38
+ 'enableOpenAICodeInterpreter',
39
+ 'useAnthropicThinkingBudgetInput',
40
+ 'useGoogleThinkingBudgetInput',
41
+ 'googleIncludeThoughts',
42
+ 'enableGoogleSearchGrounding',
43
+ 'enableGoogleUrlContext',
44
+ ];
45
+ const requiredNumberFields = ['temperature', 'maxTokens'];
46
+ const optionalNumberFields = [
47
+ 'topP',
48
+ 'topK',
49
+ 'presencePenalty',
50
+ 'frequencyPenalty',
51
+ 'seed',
52
+ 'anthropicThinkingBudget',
53
+ 'googleThinkingBudget',
54
+ ];
55
+ const resolvedInputToggleFields = [
56
+ 'useModelInput',
57
+ 'useTemperatureInput',
58
+ 'useTopPInput',
59
+ 'useTopKInput',
60
+ 'usePresencePenaltyInput',
61
+ 'useFrequencyPenaltyInput',
62
+ 'useStopSequencesInput',
63
+ 'useSeedInput',
64
+ 'useMaxTokensInput',
65
+ 'useCustomProviderBaseURLInput',
66
+ 'useHeadersInput',
67
+ 'useExtraProviderOptionsInput',
68
+ 'useOpenAIPreviousResponseIdInput',
69
+ 'useAnthropicThinkingBudgetInput',
70
+ 'useGoogleThinkingBudgetInput',
71
+ ];
72
+ export function normalizeLLMProfileValue(value) {
73
+ if (!isRecord(value)) {
74
+ throw new Error('LLM Profile input must contain an LLM profile value.');
75
+ }
76
+ if (value.version !== LLM_PROFILE_VALUE_VERSION) {
77
+ throw new Error(`Unsupported LLM Profile version: ${String(value.version)}.`);
78
+ }
79
+ if (!isRecord(value.configuration)) {
80
+ throw new Error('LLM Profile configuration is missing.');
81
+ }
82
+ const defaults = createLLMChatV2NodeData();
83
+ const provider = normalizeProvider(value.configuration.provider ?? defaults.provider);
84
+ const model = value.configuration.model;
85
+ if (typeof model !== 'string' || !model.trim()) {
86
+ throw new Error('LLM Profile model must be a non-empty string.');
87
+ }
88
+ const credential = normalizeCredential(value.credential);
89
+ const configuration = normalizeConfiguration({
90
+ ...defaults,
91
+ ...value.configuration,
92
+ provider,
93
+ model: model.trim(),
94
+ });
95
+ return {
96
+ version: LLM_PROFILE_VALUE_VERSION,
97
+ configuration,
98
+ credential,
99
+ };
100
+ }
101
+ /**
102
+ * Normalizes the single LLM Profile or ordered fallback chain accepted by
103
+ * LLM Chat's From profile input. We validate every member here rather than
104
+ * trusting a same-type `llm-config[]` wrapper: arrays can otherwise carry
105
+ * malformed values without re-entering scalar coercion.
106
+ */
107
+ export function normalizeLLMProfileChainInput(value) {
108
+ const rawProfiles = Array.isArray(value) ? value : [value];
109
+ if (rawProfiles.length === 0) {
110
+ throw new Error('LLM Profiles input must contain at least one LLM Profile.');
111
+ }
112
+ return rawProfiles.map((profile, index) => {
113
+ try {
114
+ return normalizeLLMProfileValue(profile);
115
+ }
116
+ catch (error) {
117
+ const message = error instanceof Error ? error.message : String(error);
118
+ throw new Error(`LLM Profiles input item ${index} is invalid: ${message}`);
119
+ }
120
+ });
121
+ }
122
+ function normalizeConfiguration(data) {
123
+ for (const field of stringFields) {
124
+ if (typeof data[field] !== 'string') {
125
+ throw new Error(`LLM Profile ${field} must be a string.`);
126
+ }
127
+ }
128
+ for (const field of booleanFields) {
129
+ if (typeof data[field] !== 'boolean') {
130
+ throw new Error(`LLM Profile ${field} must be a boolean.`);
131
+ }
132
+ }
133
+ for (const field of requiredNumberFields) {
134
+ if (typeof data[field] !== 'number' || !Number.isFinite(data[field])) {
135
+ throw new Error(`LLM Profile ${field} must be a finite number.`);
136
+ }
137
+ }
138
+ for (const field of optionalNumberFields) {
139
+ const fieldValue = data[field];
140
+ if (fieldValue != null && (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue))) {
141
+ throw new Error(`LLM Profile ${field} must be a finite number when provided.`);
142
+ }
143
+ }
144
+ if (!Array.isArray(data.stopSequences) || data.stopSequences.some((sequence) => typeof sequence !== 'string')) {
145
+ throw new Error('LLM Profile stopSequences must be an array of strings.');
146
+ }
147
+ if (!Array.isArray(data.headers) ||
148
+ data.headers.some((header) => !isRecord(header) || typeof header.key !== 'string' || typeof header.value !== 'string')) {
149
+ throw new Error('LLM Profile headers must contain string key/value pairs.');
150
+ }
151
+ if (data.apiKeySource !== 'environment' && data.apiKeySource !== 'input') {
152
+ throw new Error(`Unsupported LLM Profile API key source: ${String(data.apiKeySource)}.`);
153
+ }
154
+ assertEnumValue(data.openAIWebSearchContextSize, ['low', 'medium', 'high'], 'OpenAI web search context');
155
+ assertEnumValue(data.anthropicThinkingMode, ['', 'adaptive', 'enabled', 'disabled'], 'Anthropic thinking mode');
156
+ assertEnumValue(data.anthropicEffort, ['', 'low', 'medium', 'high', 'max'], 'Anthropic effort');
157
+ assertEnumValue(data.anthropicCacheControlTtl, ['', '5m', '1h'], 'Anthropic cache TTL');
158
+ assertEnumValue(data.googleThinkingLevel, ['', 'minimal', 'low', 'medium', 'high'], 'Google thinking level');
159
+ const resolvedData = {
160
+ ...data,
161
+ model: data.model.trim(),
162
+ customProviderBaseURL: data.customProviderBaseURL.trim(),
163
+ customProviderApiKeyProgrammaticName: data.customProviderApiKeyProgrammaticName?.trim(),
164
+ customProviderApiKeyEnvVarName: data.customProviderApiKeyEnvVarName?.trim(),
165
+ stopSequences: [...data.stopSequences],
166
+ headers: data.headers.map(({ key, value }) => ({ key, value })),
167
+ };
168
+ // A profile is a resolved configuration value. LLM Chat intentionally does not
169
+ // expose the profile-owned inputs, so accepting a dynamic flag here would let
170
+ // stale hidden connections influence a supposedly self-contained profile.
171
+ for (const field of resolvedInputToggleFields) {
172
+ resolvedData[field] = false;
173
+ }
174
+ return pickLLMChatV2ProfileData(resolvedData);
175
+ }
176
+ function assertEnumValue(value, allowed, label) {
177
+ if (typeof value !== 'string' || !allowed.includes(value)) {
178
+ throw new Error(`Unsupported LLM Profile ${label}: ${String(value)}.`);
179
+ }
180
+ }
181
+ function normalizeProvider(value) {
182
+ if (typeof value !== 'string' || !profileProviders.has(value)) {
183
+ throw new Error(`Unsupported LLM Profile provider: ${String(value)}.`);
184
+ }
185
+ return value;
186
+ }
187
+ function normalizeCredential(value) {
188
+ if (!isRecord(value) ||
189
+ !isRecord(value.reference) ||
190
+ typeof value.reference.source !== 'string' ||
191
+ !credentialSources.has(value.reference.source)) {
192
+ throw new Error('LLM Profile credential metadata is invalid.');
193
+ }
194
+ const credentialValue = value.value;
195
+ if (credentialValue != null && typeof credentialValue !== 'string') {
196
+ throw new Error('LLM Profile API key must be a string when provided.');
197
+ }
198
+ const name = value.reference.name;
199
+ if (name != null && typeof name !== 'string') {
200
+ throw new Error('LLM Profile credential name must be a string when provided.');
201
+ }
202
+ return {
203
+ ...(credentialValue == null ? {} : { value: credentialValue }),
204
+ reference: {
205
+ source: value.reference.source,
206
+ ...(name == null ? {} : { name }),
207
+ },
208
+ };
209
+ }
210
+ function isRecord(value) {
211
+ return typeof value === 'object' && value != null && !Array.isArray(value);
212
+ }