@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
@@ -0,0 +1,288 @@
1
+ import { materializeChatV2PipelineFailure, runChatV2PipelineExecution, } from './chatV2Pipeline.js';
2
+ import { shouldOutputChatV2RequestError, } from './chatV2Types.js';
3
+ export class LLMProfileFallbackExhaustedError extends Error {
4
+ attempts;
5
+ constructor(attempts) {
6
+ super(buildExhaustedMessage(attempts));
7
+ this.attempts = attempts;
8
+ this.name = 'LLMProfileFallbackExhaustedError';
9
+ }
10
+ }
11
+ function getSafeErrorMessage(error, candidate) {
12
+ let message;
13
+ try {
14
+ message = error instanceof Error ? error.message : String(error);
15
+ }
16
+ catch {
17
+ message = 'Provider request failed with unreadable error metadata.';
18
+ }
19
+ // Replace longer values first so one secret which contains another cannot
20
+ // leave a meaningful suffix behind. Header values can be credentials too;
21
+ // callers deliberately provide every known sensitive request value here.
22
+ const redactionValues = [candidate.credential, ...(candidate.redactionValues ?? [])]
23
+ .filter((value) => typeof value === 'string' && value.length > 0)
24
+ .sort((left, right) => right.length - left.length);
25
+ for (const value of new Set(redactionValues)) {
26
+ message = message.split(value).join('[redacted]');
27
+ }
28
+ return message.length > 1_000 ? `${message.slice(0, 997)}...` : message;
29
+ }
30
+ function buildExhaustedMessage(attempts) {
31
+ const details = attempts
32
+ .map((attempt) => {
33
+ const request = attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`;
34
+ const status = attempt.status == null ? '' : ` (${attempt.status})`;
35
+ const error = attempt.error ? `: ${attempt.error}` : '';
36
+ return `Profile ${attempt.profileIndex} (${attempt.provider}/${attempt.model}), round ${attempt.roundIndex}${request}${status}${error}`;
37
+ })
38
+ .join('\n');
39
+ return details
40
+ ? `LLM Profile fallback chain exhausted.\n${details}`
41
+ : 'LLM Profile fallback chain exhausted before a provider request could be made.';
42
+ }
43
+ function pluralize(count, singular, plural = `${singular}s`) {
44
+ return `${count} ${count === 1 ? singular : plural}`;
45
+ }
46
+ /**
47
+ * Produces the concise, developer-facing companion to the full attempt trace.
48
+ * It deliberately includes candidates that were never reached, so a successful
49
+ * primary profile does not make the configured fallback order invisible.
50
+ */
51
+ export function buildLLMProfileFallbackSummary(candidates, attempts) {
52
+ return candidates
53
+ .map((candidate, profileIndex) => {
54
+ const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
55
+ const identity = `Profile ${profileIndex} (${candidate.provider}/${candidate.model})`;
56
+ if (profileAttempts.length === 0) {
57
+ return `${identity}: not attempted.`;
58
+ }
59
+ const successfulRounds = [
60
+ ...new Set(profileAttempts
61
+ .filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'success')
62
+ .map((attempt) => attempt.roundIndex)),
63
+ ];
64
+ const failedConfiguration = profileAttempts.some((attempt) => attempt.stage === 'configuration' && attempt.outcome === 'failure');
65
+ const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
66
+ const clauses = [];
67
+ if (successfulRounds.length > 0) {
68
+ clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
69
+ }
70
+ if (failedConfiguration) {
71
+ clauses.push('failed during configuration');
72
+ }
73
+ if (failedRequestAttempts.length > 0) {
74
+ const lastFailedRequest = failedRequestAttempts.at(-1);
75
+ const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.status}`;
76
+ clauses.push(`failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
77
+ }
78
+ return `${identity}: ${clauses.join('; ')}.`;
79
+ })
80
+ .join('\n');
81
+ }
82
+ export function buildLLMProfileRequestDiagnostics(profileCount, attempts) {
83
+ const statuses = Array.from({ length: profileCount }, () => []);
84
+ const errors = Array.from({ length: profileCount }, () => []);
85
+ for (const attempt of attempts) {
86
+ if (attempt.stage !== 'request' || attempt.profileIndex < 0 || attempt.profileIndex >= profileCount) {
87
+ continue;
88
+ }
89
+ if (attempt.status != null) {
90
+ statuses[attempt.profileIndex].push(attempt.status);
91
+ }
92
+ if (attempt.error != null) {
93
+ errors[attempt.profileIndex].push(attempt.error);
94
+ }
95
+ }
96
+ return {
97
+ statuses: compactLLMProfileRequestStatuses(statuses),
98
+ errors: compactLLMProfileRequestErrors(errors),
99
+ };
100
+ }
101
+ /**
102
+ * Preserves one profile slot per input profile while making a single physical
103
+ * request easy to read. This also repairs cache entries made before the
104
+ * scalar-single-status contract was introduced.
105
+ */
106
+ export function compactLLMProfileRequestStatuses(statuses) {
107
+ return statuses.map((profileStatuses) => Array.isArray(profileStatuses) && profileStatuses.length === 1 ? profileStatuses[0] : profileStatuses);
108
+ }
109
+ /**
110
+ * Keeps Response Error readable for profile-array fallback chains and repairs
111
+ * editor-cache entries written before that compact presentation contract.
112
+ */
113
+ export function compactLLMProfileRequestErrors(errors) {
114
+ if (errors.every((profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 0)) {
115
+ return [];
116
+ }
117
+ const compacted = errors.map((profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 1 ? profileErrors[0] : profileErrors);
118
+ return compacted.length === 1 ? compacted[0] ?? [] : compacted;
119
+ }
120
+ function clearPartialResponse(options) {
121
+ if (!options.emitPartialOutputs) {
122
+ return;
123
+ }
124
+ try {
125
+ options.context.onPartialOutputs?.({
126
+ ['response']: {
127
+ type: 'string',
128
+ value: '',
129
+ },
130
+ });
131
+ }
132
+ catch {
133
+ // A presentation callback must not prevent recovery through a fallback profile.
134
+ }
135
+ }
136
+ function throwIfAborted(signal) {
137
+ if (!signal.aborted) {
138
+ return;
139
+ }
140
+ // Do not turn an abort that happens between candidates into a backup-model
141
+ // request. Prefer the host's Error reason when it supplied one, while still
142
+ // giving graph execution a normal Error for the browser's default reason.
143
+ throw signal.reason instanceof Error ? signal.reason : new Error('LLM Chat request was aborted.');
144
+ }
145
+ /**
146
+ * Creates one forward-only fallback chain for a whole LLM Chat invocation.
147
+ * A model which succeeds in an earlier tool round stays active for subsequent
148
+ * rounds; only a later failure advances farther through the configured chain.
149
+ */
150
+ export function createLLMProfileFallbackRunner(params) {
151
+ const attempts = [];
152
+ let activeProfileIndex = 0;
153
+ let nextRoundIndex = 0;
154
+ let exhausted = false;
155
+ return {
156
+ attempts,
157
+ summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
158
+ wasExhausted: () => exhausted,
159
+ run: async (roundOptions) => {
160
+ const roundIndex = nextRoundIndex;
161
+ // Only a provider failure from the terminal candidate may become normal
162
+ // request-detail outputs. If a later candidate instead fails while being
163
+ // configured, returning diagnostics from an earlier provider would lie
164
+ // about which profile terminally failed.
165
+ let terminalProviderFailure;
166
+ let lastError;
167
+ for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
168
+ throwIfAborted(roundOptions.context.signal);
169
+ const candidate = params.candidates[profileIndex];
170
+ let candidateOptions;
171
+ try {
172
+ candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
173
+ }
174
+ catch (error) {
175
+ if (roundOptions.context.signal.aborted) {
176
+ throw error;
177
+ }
178
+ lastError = error;
179
+ terminalProviderFailure = undefined;
180
+ attempts.push({
181
+ roundIndex,
182
+ profileIndex,
183
+ provider: candidate.provider,
184
+ model: candidate.model,
185
+ stage: 'configuration',
186
+ outcome: 'failure',
187
+ error: getSafeErrorMessage(error, candidate),
188
+ });
189
+ clearPartialResponse(roundOptions);
190
+ continue;
191
+ }
192
+ // Candidate resolution can be asynchronous (for example, plugin or
193
+ // provider configuration). Do not start a physical request if the
194
+ // graph was cancelled while that resolution was in flight.
195
+ throwIfAborted(roundOptions.context.signal);
196
+ const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
197
+ candidateOptions = {
198
+ ...candidateOptions,
199
+ profileIndex,
200
+ roundIndex,
201
+ onProviderAttempt: (attempt) => {
202
+ try {
203
+ previousOnProviderAttempt?.(attempt);
204
+ }
205
+ catch {
206
+ // A caller-owned observer must not prevent this runner from
207
+ // retaining the profile-chain diagnostics it owns.
208
+ }
209
+ attempts.push({
210
+ roundIndex,
211
+ profileIndex,
212
+ provider: candidate.provider,
213
+ model: candidate.model,
214
+ stage: 'request',
215
+ outcome: attempt.outcome === 'success' ? 'success' : 'failure',
216
+ attemptIndex: attempt.attemptIndex,
217
+ ...(attempt.status == null ? {} : { status: attempt.status }),
218
+ ...(attempt.error == null ? {} : { error: getSafeErrorMessage(attempt.error, candidate) }),
219
+ });
220
+ },
221
+ };
222
+ let execution;
223
+ try {
224
+ execution = await runChatV2PipelineExecution(candidateOptions);
225
+ }
226
+ catch (error) {
227
+ if (roundOptions.context.signal.aborted) {
228
+ throw error;
229
+ }
230
+ // The candidate's provider/model is part of request construction.
231
+ // Treat a failure there as an unsuccessful candidate too: it is
232
+ // exactly what a fallback chain is intended to recover from. This
233
+ // also lets a later profile whose provider supports the same shared
234
+ // prompt/schema continue. If every candidate has the same graph
235
+ // configuration problem, the aggregate error retains a safe record
236
+ // of every failed candidate.
237
+ lastError = error;
238
+ terminalProviderFailure = undefined;
239
+ attempts.push({
240
+ roundIndex,
241
+ profileIndex,
242
+ provider: candidate.provider,
243
+ model: candidate.model,
244
+ stage: 'configuration',
245
+ outcome: 'failure',
246
+ error: getSafeErrorMessage(error, candidate),
247
+ });
248
+ clearPartialResponse(roundOptions);
249
+ continue;
250
+ }
251
+ if (execution.outcome === 'success') {
252
+ activeProfileIndex = profileIndex;
253
+ nextRoundIndex += 1;
254
+ return execution.result;
255
+ }
256
+ terminalProviderFailure = execution.failure;
257
+ lastError = execution.failure.normalizedError;
258
+ clearPartialResponse(roundOptions);
259
+ }
260
+ exhausted = true;
261
+ if (params.candidates.length === 1 && terminalProviderFailure != null) {
262
+ return materializeChatV2PipelineFailure(terminalProviderFailure);
263
+ }
264
+ // A scalar profile must preserve the legacy error surface for setup or
265
+ // request-planning failures that occurred before the pipeline could
266
+ // produce a provider-failure result.
267
+ if (params.candidates.length === 1 && lastError !== undefined) {
268
+ throw lastError;
269
+ }
270
+ if (terminalProviderFailure != null &&
271
+ (terminalProviderFailure.options.outputRequestStatus ||
272
+ shouldOutputChatV2RequestError(terminalProviderFailure.options))) {
273
+ try {
274
+ return materializeChatV2PipelineFailure(terminalProviderFailure);
275
+ }
276
+ catch {
277
+ // Some response-generation failures intentionally remain node errors
278
+ // even when request details are enabled. The chain error below keeps
279
+ // the complete profile history without hiding that failure.
280
+ }
281
+ }
282
+ // `lastError` can contain raw provider metadata. The attempt records are
283
+ // intentionally redacted, so do not attach the raw error as `cause` and
284
+ // accidentally expose it through node/error serialization.
285
+ throw new LLMProfileFallbackExhaustedError(attempts);
286
+ },
287
+ };
288
+ }
@@ -0,0 +1,73 @@
1
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { getInputOrData } from '../../utils/inputs.js';
3
+ import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
4
+ import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
5
+ import { LLM_PROFILE_VALUE_VERSION } from './llmProfileTypes.js';
6
+ export function resolveLLMProfileNodeValue(params) {
7
+ const { data, inputs, context } = params;
8
+ const runtimeData = data;
9
+ const generation = resolveLLMChatV2GenerationParameters(runtimeData, inputs);
10
+ const headers = resolveLLMChatV2Headers(runtimeData, inputs);
11
+ const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(runtimeData, inputs);
12
+ const model = getInputOrData(runtimeData, inputs, 'model', 'string')?.trim();
13
+ if (!model) {
14
+ throw new Error('LLM Profile model must be a non-empty string.');
15
+ }
16
+ const customProviderBaseURL = data.provider === 'custom'
17
+ ? getInputOrData(runtimeData, inputs, 'customProviderBaseURL', 'string', 'useCustomProviderBaseURLInput')?.trim() ?? ''
18
+ : '';
19
+ const openAIPreviousResponseId = data.provider === 'openai' && data.useOpenAIPreviousResponseIdInput
20
+ ? coerceTypeOptional(inputs['previousResponseId'], 'string') ?? data.openAIPreviousResponseId ?? ''
21
+ : data.openAIPreviousResponseId ?? '';
22
+ const anthropicThinkingBudget = data.provider === 'anthropic' && data.useAnthropicThinkingBudgetInput
23
+ ? coerceTypeOptional(inputs['anthropicThinkingBudget'], 'number') ?? data.anthropicThinkingBudget
24
+ : data.anthropicThinkingBudget;
25
+ const googleThinkingBudget = data.provider === 'google' && data.useGoogleThinkingBudgetInput
26
+ ? coerceTypeOptional(inputs['googleThinkingBudget'], 'number') ?? data.googleThinkingBudget
27
+ : data.googleThinkingBudget;
28
+ const credential = resolveChatV2Credential({
29
+ provider: data.provider,
30
+ context,
31
+ apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
32
+ inputs,
33
+ customProgrammaticName: data.customProviderApiKeyProgrammaticName,
34
+ customEnvironmentName: data.customProviderApiKeyEnvVarName,
35
+ });
36
+ return {
37
+ version: LLM_PROFILE_VALUE_VERSION,
38
+ credential,
39
+ configuration: {
40
+ ...data,
41
+ model,
42
+ useModelInput: false,
43
+ temperature: generation.temperature ?? data.temperature,
44
+ useTemperatureInput: false,
45
+ maxTokens: generation.maxTokens ?? data.maxTokens,
46
+ useMaxTokensInput: false,
47
+ topP: generation.topP,
48
+ useTopPInput: false,
49
+ topK: generation.topK,
50
+ useTopKInput: false,
51
+ presencePenalty: generation.presencePenalty,
52
+ usePresencePenaltyInput: false,
53
+ frequencyPenalty: generation.frequencyPenalty,
54
+ useFrequencyPenaltyInput: false,
55
+ stopSequences: generation.stopSequences ?? [],
56
+ useStopSequencesInput: false,
57
+ seed: generation.seed,
58
+ useSeedInput: false,
59
+ customProviderBaseURL,
60
+ useCustomProviderBaseURLInput: false,
61
+ openAIPreviousResponseId,
62
+ useOpenAIPreviousResponseIdInput: false,
63
+ headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
64
+ useHeadersInput: false,
65
+ extraProviderOptions: extraProviderOptions == null ? '' : JSON.stringify(extraProviderOptions),
66
+ useExtraProviderOptionsInput: false,
67
+ anthropicThinkingBudget,
68
+ useAnthropicThinkingBudgetInput: false,
69
+ googleThinkingBudget,
70
+ useGoogleThinkingBudgetInput: false,
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,45 @@
1
+ import { createLLMChatV2NodeData, llmChatV2ProfileDataKeys, } from './llmChatV2NodeData.js';
2
+ export const LLM_PROFILE_VALUE_VERSION = 1;
3
+ /**
4
+ * Every input port owned by an LLM Profile, including ports that are hidden
5
+ * until their matching provider or input toggle is enabled. This lets editor
6
+ * operations preserve recoverable connections across configuration changes.
7
+ */
8
+ export const llmProfileInputIds = [
9
+ 'model',
10
+ 'apiKey',
11
+ 'customProviderBaseURL',
12
+ 'previousResponseId',
13
+ 'temperature',
14
+ 'maxTokens',
15
+ 'topP',
16
+ 'topK',
17
+ 'presencePenalty',
18
+ 'frequencyPenalty',
19
+ 'stopSequences',
20
+ 'seed',
21
+ 'headers',
22
+ 'extraProviderOptions',
23
+ 'anthropicThinkingBudget',
24
+ 'googleThinkingBudget',
25
+ ];
26
+ export function createLLMProfileNodeData() {
27
+ return pickLLMChatV2ProfileData(createLLMChatV2NodeData());
28
+ }
29
+ export function createDefaultLLMProfileValue() {
30
+ return {
31
+ version: LLM_PROFILE_VALUE_VERSION,
32
+ configuration: createLLMProfileNodeData(),
33
+ credential: { reference: { source: 'none' } },
34
+ };
35
+ }
36
+ export function pickLLMChatV2ProfileData(data) {
37
+ return Object.fromEntries(llmChatV2ProfileDataKeys.map((key) => [key, data[key]]));
38
+ }
39
+ export function applyLLMProfileToNodeData(data, profile) {
40
+ return {
41
+ ...data,
42
+ ...profile.configuration,
43
+ configurationMode: 'profile',
44
+ };
45
+ }
@@ -104,6 +104,20 @@ export async function chatMessagesToModelMessages(messages, options) {
104
104
  });
105
105
  break;
106
106
  }
107
+ case 'developer': {
108
+ // AI SDK ModelMessage is provider-neutral and currently exposes only
109
+ // `system` for instruction messages. OpenAI and OpenAI-compatible
110
+ // transports restore the explicit role at the request-body boundary.
111
+ // Providers without a developer role receive it as a system instruction.
112
+ result.push({
113
+ role: 'system',
114
+ content: stringifyParts(msg.message),
115
+ providerOptions: options.provider === 'anthropic'
116
+ ? getAnthropicCacheMetadata(!!msg.isCacheBreakpoint, options.anthropicCacheControlTtl)
117
+ : undefined,
118
+ });
119
+ break;
120
+ }
107
121
  case 'user': {
108
122
  const parts = Array.isArray(msg.message) ? msg.message : [msg.message];
109
123
  if (parts.length === 1 && typeof parts[0] === 'string' && !msg.isCacheBreakpoint) {
@@ -141,18 +141,51 @@ function cloneCapturedRequestBody(body) {
141
141
  return body;
142
142
  }
143
143
  }
144
- function createRequestBodyCapturingFetch(onRequestBody) {
144
+ function serializeTransformedFetchBody(originalBody, transformedBody) {
145
+ const serialized = JSON.stringify(transformedBody);
146
+ if (serialized === undefined) {
147
+ throw new Error('Provider request-body transformation returned a non-serializable value.');
148
+ }
149
+ if (originalBody instanceof ArrayBuffer) {
150
+ return new TextEncoder().encode(serialized);
151
+ }
152
+ if (ArrayBuffer.isView(originalBody)) {
153
+ return new TextEncoder().encode(serialized);
154
+ }
155
+ return serialized;
156
+ }
157
+ function removeStaleContentLength(headers) {
158
+ if (headers == null) {
159
+ return undefined;
160
+ }
161
+ const nextHeaders = new Headers(headers);
162
+ nextHeaders.delete('content-length');
163
+ return nextHeaders;
164
+ }
165
+ function createRequestBodyProcessingFetch(options) {
145
166
  return async (input, init) => {
146
- const body = parseFetchBody(init?.body);
147
- if (body !== undefined) {
148
- onRequestBody(cloneCapturedRequestBody(body));
167
+ const parsedBody = parseFetchBody(init?.body);
168
+ const processedBody = parsedBody !== undefined && options.transformRequestBody != null
169
+ ? options.transformRequestBody(parsedBody)
170
+ : parsedBody;
171
+ if (processedBody !== undefined) {
172
+ options.onRequestBody?.(cloneCapturedRequestBody(processedBody));
149
173
  }
150
174
  const nativeFetch = globalThis.fetch;
151
- return nativeFetch(input, init);
175
+ const processedInit = processedBody !== parsedBody
176
+ ? {
177
+ ...init,
178
+ body: serializeTransformedFetchBody(init?.body, processedBody),
179
+ headers: removeStaleContentLength(init?.headers),
180
+ }
181
+ : init;
182
+ return nativeFetch(input, processedInit);
152
183
  };
153
184
  }
154
- function maybeCreateRequestBodyCapturingFetch(options) {
155
- return options.onRequestBody == null ? undefined : createRequestBodyCapturingFetch(options.onRequestBody);
185
+ function maybeCreateRequestBodyProcessingFetch(options) {
186
+ return options.onRequestBody == null && options.transformRequestBody == null
187
+ ? undefined
188
+ : createRequestBodyProcessingFetch(options);
156
189
  }
157
190
  export async function resolveChatV2ProviderConfig(provider, _modelId, context, options = {}) {
158
191
  const headers = cleanHeaders({
@@ -195,7 +228,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
195
228
  organization: context.settings.openAiOrganization || undefined,
196
229
  baseURL: undefined,
197
230
  headers: options.headers,
198
- fetch: maybeCreateRequestBodyCapturingFetch(options),
231
+ fetch: maybeCreateRequestBodyProcessingFetch(options),
199
232
  });
200
233
  return providerInstance.responses(modelId);
201
234
  }
@@ -204,7 +237,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
204
237
  apiKey: options.apiKey || context.settings.anthropicApiKey || context.getPluginConfig('anthropicApiKey') || undefined,
205
238
  baseURL: undefined,
206
239
  headers: options.headers,
207
- fetch: maybeCreateRequestBodyCapturingFetch(options),
240
+ fetch: maybeCreateRequestBodyProcessingFetch(options),
208
241
  });
209
242
  return providerInstance.messages(modelId);
210
243
  }
@@ -213,7 +246,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
213
246
  apiKey: options.apiKey || context.settings.googleApiKey || context.getPluginConfig('googleApiKey') || undefined,
214
247
  baseURL: undefined,
215
248
  headers: options.headers,
216
- fetch: maybeCreateRequestBodyCapturingFetch(options),
249
+ fetch: maybeCreateRequestBodyProcessingFetch(options),
217
250
  });
218
251
  return providerInstance.chat(modelId);
219
252
  }
@@ -227,7 +260,7 @@ export function createChatV2Model(provider, modelId, context, options = {}) {
227
260
  baseURL: options.baseURL,
228
261
  headers: options.headers,
229
262
  includeUsage: false,
230
- fetch: maybeCreateRequestBodyCapturingFetch(options),
263
+ fetch: maybeCreateRequestBodyProcessingFetch(options),
231
264
  });
232
265
  const model = providerInstance.chatModel(modelId);
233
266
  // The installed OpenAI-compatible provider reads this from the model instance,
@@ -39,10 +39,6 @@ function applyAccumulatedUsage(result, usage, outputUsage) {
39
39
  return;
40
40
  }
41
41
  result.usage = usage;
42
- result.commonOutputs['responseTokens'] = {
43
- type: 'number',
44
- value: usage.completionTokens,
45
- };
46
42
  if (outputUsage) {
47
43
  result.commonOutputs['usage'] = {
48
44
  type: 'object',
@@ -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,
@@ -0,0 +1,81 @@
1
+ import { NodeImpl } from '../NodeImpl.js';
2
+ import { nodeDefinition } from '../NodeDefinition.js';
3
+ import {} from '../NodeBase.js';
4
+ import { nanoid } from 'nanoid/non-secure';
5
+ import {} from '../GraphProcessor.js';
6
+ import { dedent } from 'ts-dedent';
7
+ import { getDataBusInputPortId, getDataBusOutputPortId, MAX_DATA_BUS_CHANNEL_INDEX, parseDataBusChannelIndex, } from '../DataBusPorts.js';
8
+ export { getDataBusInputPortId, getDataBusOutputPortId, MAX_DATA_BUS_CHANNEL_INDEX, parseDataBusChannelIndex, } from '../DataBusPorts.js';
9
+ function getConnectedChannelIndices(connections, nodeId) {
10
+ const channelIndices = new Set();
11
+ for (const connection of connections) {
12
+ const inputIndex = connection.inputNodeId === nodeId ? parseDataBusChannelIndex(connection.inputId, true) : undefined;
13
+ const outputIndex = connection.outputNodeId === nodeId ? parseDataBusChannelIndex(connection.outputId, false) : undefined;
14
+ if (inputIndex != null) {
15
+ channelIndices.add(inputIndex);
16
+ }
17
+ if (outputIndex != null) {
18
+ channelIndices.add(outputIndex);
19
+ }
20
+ }
21
+ return [...channelIndices].sort((left, right) => left - right);
22
+ }
23
+ function getFirstAvailableChannelIndex(connectedChannelIndices) {
24
+ let availableIndex = 1;
25
+ for (const channelIndex of connectedChannelIndices) {
26
+ if (channelIndex !== availableIndex) {
27
+ break;
28
+ }
29
+ availableIndex += 1;
30
+ }
31
+ return availableIndex <= MAX_DATA_BUS_CHANNEL_INDEX ? availableIndex : undefined;
32
+ }
33
+ export function isDataBusNode(node) {
34
+ return node?.type === 'dataBus';
35
+ }
36
+ export class DataBusNodeImpl extends NodeImpl {
37
+ static create = () => ({
38
+ type: 'dataBus',
39
+ title: 'Data Bus',
40
+ id: nanoid(),
41
+ data: {},
42
+ visualData: {
43
+ x: 0,
44
+ y: 0,
45
+ width: 175,
46
+ },
47
+ });
48
+ getInputDefinitions(connections) {
49
+ const connectedChannelIndices = getConnectedChannelIndices(connections, this.chartNode.id);
50
+ const availableChannelIndex = getFirstAvailableChannelIndex(connectedChannelIndices);
51
+ const channelIndices = availableChannelIndex == null ? connectedChannelIndices : [...connectedChannelIndices, availableChannelIndex];
52
+ return channelIndices.map((channelIndex) => ({
53
+ dataType: 'any',
54
+ id: getDataBusInputPortId(channelIndex),
55
+ title: `Input ${channelIndex}`,
56
+ }));
57
+ }
58
+ getOutputDefinitions(connections) {
59
+ const connectedChannelIndices = getConnectedChannelIndices(connections, this.chartNode.id);
60
+ return connectedChannelIndices.map((channelIndex) => ({
61
+ dataType: 'any',
62
+ id: getDataBusOutputPortId(channelIndex),
63
+ title: `Output ${channelIndex}`,
64
+ }));
65
+ }
66
+ static getUIData() {
67
+ return {
68
+ infoBoxBody: dedent `
69
+ Organizes independent connections in a compact rail at the top of the
70
+ canvas. Data Bus channels are wiring topology, not executable nodes.
71
+ `,
72
+ infoBoxTitle: 'Data Bus',
73
+ contextMenuTitle: 'Data Bus',
74
+ group: ['Logic'],
75
+ };
76
+ }
77
+ async process(_inputData) {
78
+ throw new Error('Data Bus nodes are topology-only and must be compiled out before graph execution.');
79
+ }
80
+ }
81
+ export const dataBusNode = nodeDefinition(DataBusNodeImpl, 'Data Bus');
@@ -45,6 +45,18 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
45
45
  title: 'Message (fires before tool call invocation)',
46
46
  description: 'Nonblank text the assistant emitted alongside a connected tool-call round. This output fires before the tools are invoked.',
47
47
  });
48
+ outputs.push({
49
+ id: 'tool-name',
50
+ dataType: ['string', 'string[]'],
51
+ title: 'Tool Name',
52
+ description: 'The name of the tool selected by the LLM.',
53
+ });
54
+ outputs.push({
55
+ id: 'tool-arguments',
56
+ dataType: ['object', 'object[]'],
57
+ title: 'Tool Arguments',
58
+ description: 'The resolved arguments passed to the selected tool.',
59
+ });
48
60
  outputs.push({
49
61
  id: 'output',
50
62
  dataType: ['string', 'string[]'],