@valerypopoff/rivet2-core 2.1.8 → 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 (55) hide show
  1. package/dist/cjs/bundle.cjs +1922 -1125
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/model/GraphProcessor.js +1 -0
  4. package/dist/esm/model/SplitRunProcessor.js +19 -10
  5. package/dist/esm/model/ToolCallContinuationCoordinator.js +6 -1
  6. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  7. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  8. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  9. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  10. package/dist/esm/model/chat-v2/chatV2Pipeline.js +122 -44
  11. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  12. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  13. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  14. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  15. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  16. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -5
  17. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +22 -13
  18. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +224 -68
  19. package/dist/esm/model/chat-v2/llmProfile.js +21 -0
  20. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  21. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  22. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  23. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  24. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  25. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  26. package/dist/esm/model/nodes/LLMChatV2Node.js +115 -11
  27. package/dist/esm/model/nodes/PromptNode.js +9 -2
  28. package/dist/esm/model/nodes/toolCallDelegation.js +18 -2
  29. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  30. package/dist/esm/plugins/google/google.js +20 -9
  31. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  32. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  33. package/dist/esm/utils/serialization/serialization.js +19 -0
  34. package/dist/types/model/DataValue.d.ts +7 -1
  35. package/dist/types/model/NodeBase.d.ts +6 -0
  36. package/dist/types/model/ProcessContext.d.ts +4 -0
  37. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  38. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  39. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  40. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  41. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  42. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  43. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  44. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  45. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  46. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  47. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  48. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  49. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  50. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  51. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  52. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  53. package/dist/types/plugins/google/google.d.ts +12 -1
  54. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  55. 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
+ }
@@ -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,
@@ -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[]'],
@@ -6,10 +6,11 @@ import { getCommonChatV2Inputs, getCommonChatV2Outputs } from '../chat-v2/chatV2
6
6
  import { getLLMChatV2Editors } from '../chat-v2/llmChatV2NodeEditors.js';
7
7
  import { createLLMChatV2NodeData, shouldIncludeLLMChatV2ToolCalls, } from '../chat-v2/llmChatV2NodeData.js';
8
8
  import { isLLMChatV2StructuredResponseFormat } from '../chat-v2/chatV2FeatureCompatibility.js';
9
+ import { buildLLMProfileRequestDiagnostics, compactLLMProfileRequestErrors, compactLLMProfileRequestStatuses, } from '../chat-v2/llmProfileFallback.js';
9
10
  import { getChatV2ModelInfo } from '../chat-v2/modelRegistry.js';
11
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError } from '../chat-v2/chatV2Types.js';
10
12
  import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolveLLMChatV2RuntimeConfig, resolveLLMChatV2RuntimeProviderOptions, } from '../chat-v2/llmChatV2NodeRuntime.js';
11
13
  import { anthropicEffortOptions, getChatV2ProviderLabel, googleThinkingLevelOptions, openAIReasoningEffortOptions, } from '../chat-v2/providerOptions.js';
12
- import { runChatV2Pipeline } from '../chat-v2/chatV2Pipeline.js';
13
14
  import { runChatV2PipelineWithToolContinuation } from '../chat-v2/toolContinuation.js';
14
15
  import { delegateToolCall } from './toolCallDelegation.js';
15
16
  export { buildLLMChatV2EditorCacheKey, resolveLLMChatV2RuntimeProviderOptions };
@@ -108,9 +109,12 @@ export class LLMChatV2NodeImpl extends NodeImpl {
108
109
  if (usesProfile) {
109
110
  inputs.unshift({
110
111
  id: 'llmProfile',
111
- title: 'LLM Profile',
112
- dataType: 'llm-config',
112
+ title: 'LLM Profiles',
113
+ dataType: ['llm-config', 'llm-config[]'],
113
114
  required: true,
115
+ coerced: true,
116
+ splitRunBehavior: 'preserve-array',
117
+ description: 'One LLM Profile or an ordered fallback chain. Profiles are tried left to right.',
114
118
  });
115
119
  }
116
120
  if (!usesProfile && this.data.apiKeySource === 'input') {
@@ -221,20 +225,59 @@ export class LLMChatV2NodeImpl extends NodeImpl {
221
225
  ];
222
226
  }
223
227
  if (this.data.outputRequestStatus) {
228
+ const profileArrayRequestDetails = this.data.configurationMode === 'profile'
229
+ ? ['number', 'number[]', 'any']
230
+ : this.data.retryOnNon200
231
+ ? 'number[]'
232
+ : 'number';
224
233
  outputs.push({
225
234
  id: 'requestStatus',
226
235
  title: 'Response Status',
227
- dataType: this.data.retryOnNon200 ? 'number[]' : 'number',
228
- }, {
236
+ dataType: profileArrayRequestDetails,
237
+ ...(this.data.configurationMode === 'profile'
238
+ ? {
239
+ description: 'A scalar profile keeps the normal status shape. An LLM Profile array groups values by profile: one request is a number, retries are a number array.',
240
+ }
241
+ : {}),
242
+ });
243
+ }
244
+ if (shouldOutputChatV2RequestError(this.data)) {
245
+ const profileArrayRequestErrors = this.data.configurationMode === 'profile'
246
+ ? ['string', 'string[]', 'any']
247
+ : this.data.retryOnNon200
248
+ ? 'string[]'
249
+ : 'string';
250
+ outputs.push({
229
251
  id: 'requestError',
230
252
  title: 'Response Error',
231
- dataType: this.data.retryOnNon200 ? 'string[]' : 'string',
232
- }, {
253
+ dataType: profileArrayRequestErrors,
254
+ ...(this.data.configurationMode === 'profile'
255
+ ? {
256
+ description: 'A scalar profile keeps the normal error shape. An LLM Profile array keeps profile positions when errors occur: one error is a string and retries are an array.',
257
+ }
258
+ : {}),
259
+ });
260
+ }
261
+ if (shouldOutputChatV2RequestBody(this.data)) {
262
+ outputs.push({
233
263
  id: 'requestBody',
234
264
  title: 'LLM request body',
235
265
  dataType: ['object', 'object[]', 'string', 'string[]', 'any', 'any[]'],
236
266
  });
237
267
  }
268
+ if (this.data.configurationMode === 'profile') {
269
+ outputs.push({
270
+ id: 'llmProfileSummary',
271
+ title: 'LLM Profile Summary',
272
+ dataType: 'string',
273
+ description: 'Human-readable profile fallback outcome for this LLM Chat run.',
274
+ }, {
275
+ id: 'llmProfileAttempts',
276
+ title: 'LLM Profile Attempts',
277
+ dataType: 'object[]',
278
+ description: 'Chronological provider/profile attempts for this LLM Chat run.',
279
+ });
280
+ }
238
281
  return outputs;
239
282
  }
240
283
  static getUIData() {
@@ -259,7 +302,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
259
302
  type: 'markdown',
260
303
  disableLinks: true,
261
304
  text: [
262
- getBodyLine('Configuration', 'From LLM Profile input'),
305
+ getBodyLine('Configuration', 'From LLM Profiles input'),
263
306
  ...(this.data.useToolCalling ? [getBodyLine('Tools', 'Enabled')] : []),
264
307
  ...(this.data.responseFormat ? [getBodyLine('Response format', this.data.responseFormat)] : []),
265
308
  ].join('\n'),
@@ -303,6 +346,31 @@ export class LLMChatV2NodeImpl extends NodeImpl {
303
346
  });
304
347
  const toolCallContinuation = context.toolCallContinuation;
305
348
  if (runtime.cachedOutputs != null) {
349
+ if (runtime.profileChainUsesArray && this.data.outputRequestStatus) {
350
+ const cachedStatus = runtime.cachedOutputs['requestStatus'];
351
+ if (cachedStatus?.type === 'any' && Array.isArray(cachedStatus.value)) {
352
+ cachedStatus.value = compactLLMProfileRequestStatuses(cachedStatus.value);
353
+ }
354
+ }
355
+ if (runtime.profileChainUsesArray && shouldOutputChatV2RequestError(this.data)) {
356
+ const cachedError = runtime.cachedOutputs['requestError'];
357
+ if (cachedError?.type === 'any' && Array.isArray(cachedError.value)) {
358
+ cachedError.value = compactLLMProfileRequestErrors(cachedError.value);
359
+ }
360
+ }
361
+ // Cached provider output belongs to an earlier invocation, whereas this
362
+ // port is an observability record for physical profile attempts made by
363
+ // the current one. A cache hit made no such attempt.
364
+ if (runtime.profileAttempts != null) {
365
+ runtime.cachedOutputs['llmProfileAttempts'] = {
366
+ type: 'object[]',
367
+ value: [],
368
+ };
369
+ runtime.cachedOutputs['llmProfileSummary'] = {
370
+ type: 'string',
371
+ value: 'Editor cache hit — no LLM Profile calls were made for this run.',
372
+ };
373
+ }
306
374
  return runtime.cachedOutputs;
307
375
  }
308
376
  const result = runtime.shouldAutoContinueToolCalls
@@ -335,13 +403,49 @@ export class LLMChatV2NodeImpl extends NodeImpl {
335
403
  delegatedToolCall: delegated.record,
336
404
  };
337
405
  },
406
+ runPipeline: runtime.runPipeline,
338
407
  })
339
- : await runChatV2Pipeline(runtime.runOptions);
408
+ : await runtime.runPipeline(runtime.runOptions);
409
+ if (runtime.profileAttempts != null) {
410
+ result.commonOutputs['llmProfileAttempts'] = {
411
+ type: 'object[]',
412
+ value: runtime.profileAttempts,
413
+ };
414
+ result.commonOutputs['llmProfileSummary'] = {
415
+ type: 'string',
416
+ value: runtime.getProfileSummary(),
417
+ };
418
+ if (runtime.profileChainUsesArray && runtime.profileChainLength != null) {
419
+ const diagnostics = buildLLMProfileRequestDiagnostics(runtime.profileChainLength, runtime.profileAttempts);
420
+ // Rivet has scalar and one-dimensional array Data Values, but no
421
+ // nested-array Data Type. Keep profile/retry grouping as portable JSON
422
+ // inside Any values. One request or error stays scalar when doing so
423
+ // preserves useful diagnostic information.
424
+ if (this.data.outputRequestStatus) {
425
+ result.commonOutputs['requestStatus'] = {
426
+ type: 'any',
427
+ value: diagnostics.statuses,
428
+ };
429
+ }
430
+ if (shouldOutputChatV2RequestError(this.data)) {
431
+ result.commonOutputs['requestError'] = {
432
+ type: 'any',
433
+ value: diagnostics.errors,
434
+ };
435
+ }
436
+ }
437
+ }
340
438
  if (toolCallContinuation && result.functionCalls.length > 0) {
341
439
  toolCallContinuation.release();
342
440
  }
343
- if (runtime.cacheKey != null && runtime.editorCache != null) {
344
- runtime.editorCache.set(runtime.cacheKey, cloneLLMChatV2EditorCacheOutputs(result.commonOutputs));
441
+ if (runtime.cacheKey != null && runtime.editorCache != null && !runtime.isProfileFallbackExhausted()) {
442
+ const cacheOutputs = cloneLLMChatV2EditorCacheOutputs(result.commonOutputs);
443
+ // Attempt history is specific to this execution. Rebuild it as an empty
444
+ // observability value on a later cache hit instead of presenting stale
445
+ // provider calls as if they happened again.
446
+ delete cacheOutputs['llmProfileAttempts'];
447
+ delete cacheOutputs['llmProfileSummary'];
448
+ runtime.editorCache.set(runtime.cacheKey, cacheOutputs);
345
449
  }
346
450
  return result.commonOutputs;
347
451
  }