@valerypopoff/rivet2-core 2.1.9 → 2.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/cjs/bundle.cjs +3596 -1745
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +298 -21
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/AgentResponseTrace.js +448 -0
  7. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  8. package/dist/esm/model/GraphProcessor.js +151 -74
  9. package/dist/esm/model/NodeImpl.js +6 -0
  10. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  11. package/dist/esm/model/RecordingPlayer.js +164 -22
  12. package/dist/esm/model/SplitRunProcessor.js +49 -8
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  15. package/dist/esm/model/UiGraph.js +21 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +2 -0
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  18. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  19. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  20. package/dist/esm/model/UiGraphSchema.js +7 -1
  21. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  22. package/dist/esm/model/chat-v2/chatV2CallObserver.js +9 -5
  23. package/dist/esm/model/chat-v2/chatV2EditorCache.js +42 -16
  24. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  25. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  26. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  27. package/dist/esm/model/chat-v2/chatV2Pipeline.js +61 -146
  28. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +8 -2
  29. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  30. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  31. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  32. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  33. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  34. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  35. package/dist/esm/model/chat-v2/chatV2Types.js +5 -9
  36. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  37. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  38. package/dist/esm/model/chat-v2/index.js +12 -0
  39. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  40. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  41. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  42. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +6 -50
  43. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -13
  44. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +121 -193
  46. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  47. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  48. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  49. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  50. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  51. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  52. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  53. package/dist/esm/model/chat-v2/llmProfile.js +10 -65
  54. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  55. package/dist/esm/model/chat-v2/llmProfileFallback.js +55 -99
  56. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  57. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  58. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  59. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  60. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  61. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  62. package/dist/esm/model/chat-v2/providerOptions.js +86 -20
  63. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  64. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  65. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  66. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  67. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  68. package/dist/esm/model/nodes/ChatNode.js +6 -0
  69. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  70. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  71. package/dist/esm/model/nodes/LLMChatV2Node.js +112 -229
  72. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  73. package/dist/esm/model/nodes/PromptNode.js +7 -0
  74. package/dist/esm/model/nodes/ToolNode.js +7 -0
  75. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  76. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  77. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  78. package/dist/esm/plugins/google/google.js +5 -9
  79. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  80. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  81. package/dist/esm/utils/emitDetached.js +6 -3
  82. package/dist/esm/utils/openai.js +60 -16
  83. package/dist/esm/utils/serialization/serialization.js +2 -19
  84. package/dist/esm/webAppRuntime.js +3 -2
  85. package/dist/types/exports.d.ts +1 -0
  86. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  87. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  88. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  89. package/dist/types/model/GraphProcessor.d.ts +27 -5
  90. package/dist/types/model/NodeImpl.d.ts +18 -1
  91. package/dist/types/model/Nodes.d.ts +2 -2
  92. package/dist/types/model/ProcessContext.d.ts +47 -0
  93. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  94. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  95. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  96. package/dist/types/model/UiGraph.d.ts +8 -0
  97. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  98. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  99. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  100. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  101. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  102. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  103. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -3
  104. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  105. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  106. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +4 -0
  107. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  108. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  109. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  110. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  111. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  112. package/dist/types/model/chat-v2/chatV2Types.d.ts +20 -10
  113. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  114. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  115. package/dist/types/model/chat-v2/index.d.ts +12 -0
  116. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  117. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  118. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  119. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -3
  120. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  121. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  122. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  123. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  124. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  125. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  126. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  127. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  128. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  129. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  130. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +17 -49
  131. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  132. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  133. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  134. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  135. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  136. package/dist/types/model/chat-v2/providerOptions.d.ts +10 -0
  137. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  138. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  139. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  140. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  141. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  142. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  143. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  144. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  145. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  146. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  147. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  148. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  149. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  150. package/dist/types/plugins/google/google.d.ts +2 -8
  151. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  152. package/dist/types/utils/emitDetached.d.ts +3 -2
  153. package/dist/types/utils/openai.d.ts +49 -0
  154. package/dist/types/webAppRuntime.d.ts +4 -2
  155. package/package.json +2 -2
@@ -1,5 +1,12 @@
1
- import { materializeChatV2PipelineFailure, runChatV2PipelineExecution, } from './chatV2Pipeline.js';
2
- import { shouldOutputChatV2RequestError, } from './chatV2Types.js';
1
+ import { isChatV2ResponseValidationError, runChatV2PipelineExecution } from './chatV2Pipeline.js';
2
+ import {} from './chatV2Types.js';
3
+ import { getCustomProviderApiContract } from './customProviderApi.js';
4
+ function formatCandidateIdentity(candidate) {
5
+ const providerLabel = candidate.provider === 'custom'
6
+ ? getCustomProviderApiContract(candidate.customProviderApi).label
7
+ : candidate.provider;
8
+ return `${providerLabel}/${candidate.model}`;
9
+ }
3
10
  export class LLMProfileFallbackExhaustedError extends Error {
4
11
  attempts;
5
12
  constructor(attempts) {
@@ -8,32 +15,25 @@ export class LLMProfileFallbackExhaustedError extends Error {
8
15
  this.name = 'LLMProfileFallbackExhaustedError';
9
16
  }
10
17
  }
11
- function getSafeErrorMessage(error, candidate) {
12
- let message;
18
+ export function getLLMAttemptErrorMessage(error) {
13
19
  try {
14
- message = error instanceof Error ? error.message : String(error);
20
+ return error instanceof Error ? error.message : String(error);
15
21
  }
16
22
  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]');
23
+ return 'Provider request failed with unreadable error metadata.';
27
24
  }
28
- return message.length > 1_000 ? `${message.slice(0, 997)}...` : message;
29
25
  }
30
26
  function buildExhaustedMessage(attempts) {
31
27
  const details = attempts
32
28
  .map((attempt) => {
33
- const request = attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`;
29
+ const stage = attempt.stage === 'request'
30
+ ? `request${attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`}`
31
+ : attempt.stage === 'response-validation'
32
+ ? 'response validation'
33
+ : 'configuration';
34
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}`;
35
+ const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
36
+ return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
37
37
  })
38
38
  .join('\n');
39
39
  return details
@@ -52,17 +52,21 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
52
52
  return candidates
53
53
  .map((candidate, profileIndex) => {
54
54
  const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
55
- const identity = `Profile ${profileIndex} (${candidate.provider}/${candidate.model})`;
55
+ const identity = `Profile ${profileIndex} (${formatCandidateIdentity(candidate)})`;
56
56
  if (profileAttempts.length === 0) {
57
57
  return `${identity}: not attempted.`;
58
58
  }
59
59
  const successfulRounds = [
60
60
  ...new Set(profileAttempts
61
- .filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'success')
61
+ .filter((attempt) => attempt.stage === 'request' &&
62
+ attempt.outcome === 'success' &&
63
+ !profileAttempts.some((candidate) => candidate.stage === 'response-validation' && candidate.roundIndex === attempt.roundIndex))
62
64
  .map((attempt) => attempt.roundIndex)),
63
65
  ];
64
66
  const failedConfiguration = profileAttempts.some((attempt) => attempt.stage === 'configuration' && attempt.outcome === 'failure');
65
67
  const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
68
+ const hasSuccessfulRequest = profileAttempts.some((attempt) => attempt.stage === 'request' && attempt.outcome === 'success');
69
+ const failedResponseValidations = profileAttempts.filter((attempt) => attempt.stage === 'response-validation' && attempt.outcome === 'failure');
66
70
  const clauses = [];
67
71
  if (successfulRounds.length > 0) {
68
72
  clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
@@ -73,50 +77,17 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
73
77
  if (failedRequestAttempts.length > 0) {
74
78
  const lastFailedRequest = failedRequestAttempts.at(-1);
75
79
  const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.status}`;
76
- clauses.push(`failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
80
+ clauses.push(hasSuccessfulRequest
81
+ ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}`
82
+ : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
83
+ }
84
+ if (failedResponseValidations.length > 0) {
85
+ clauses.push(`failed response validation in ${pluralize(failedResponseValidations.length, 'model round')}`);
77
86
  }
78
87
  return `${identity}: ${clauses.join('; ')}.`;
79
88
  })
80
89
  .join('\n');
81
90
  }
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
91
  function clearPartialResponse(options) {
121
92
  if (!options.emitPartialOutputs) {
122
93
  return;
@@ -149,6 +120,15 @@ function throwIfAborted(signal) {
149
120
  */
150
121
  export function createLLMProfileFallbackRunner(params) {
151
122
  const attempts = [];
123
+ const recordAttempt = (attempt) => {
124
+ attempts.push(attempt);
125
+ try {
126
+ params.onAttempt?.(attempt);
127
+ }
128
+ catch {
129
+ // Diagnostics must not alter profile recovery.
130
+ }
131
+ };
152
132
  let activeProfileIndex = 0;
153
133
  let nextRoundIndex = 0;
154
134
  let exhausted = false;
@@ -158,11 +138,6 @@ export function createLLMProfileFallbackRunner(params) {
158
138
  wasExhausted: () => exhausted,
159
139
  run: async (roundOptions) => {
160
140
  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
141
  let lastError;
167
142
  for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
168
143
  throwIfAborted(roundOptions.context.signal);
@@ -176,15 +151,15 @@ export function createLLMProfileFallbackRunner(params) {
176
151
  throw error;
177
152
  }
178
153
  lastError = error;
179
- terminalProviderFailure = undefined;
180
- attempts.push({
154
+ recordAttempt({
181
155
  roundIndex,
182
156
  profileIndex,
183
157
  provider: candidate.provider,
184
158
  model: candidate.model,
159
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
185
160
  stage: 'configuration',
186
161
  outcome: 'failure',
187
- error: getSafeErrorMessage(error, candidate),
162
+ error: getLLMAttemptErrorMessage(error),
188
163
  });
189
164
  clearPartialResponse(roundOptions);
190
165
  continue;
@@ -206,16 +181,17 @@ export function createLLMProfileFallbackRunner(params) {
206
181
  // A caller-owned observer must not prevent this runner from
207
182
  // retaining the profile-chain diagnostics it owns.
208
183
  }
209
- attempts.push({
184
+ recordAttempt({
210
185
  roundIndex,
211
186
  profileIndex,
212
187
  provider: candidate.provider,
213
188
  model: candidate.model,
189
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
214
190
  stage: 'request',
215
- outcome: attempt.outcome === 'success' ? 'success' : 'failure',
191
+ outcome: attempt.outcome === 'success' ? 'success' : attempt.outcome === 'aborted' ? 'aborted' : 'failure',
216
192
  attemptIndex: attempt.attemptIndex,
217
193
  ...(attempt.status == null ? {} : { status: attempt.status }),
218
- ...(attempt.error == null ? {} : { error: getSafeErrorMessage(attempt.error, candidate) }),
194
+ ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
219
195
  });
220
196
  },
221
197
  };
@@ -232,18 +208,19 @@ export function createLLMProfileFallbackRunner(params) {
232
208
  // exactly what a fallback chain is intended to recover from. This
233
209
  // also lets a later profile whose provider supports the same shared
234
210
  // 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.
211
+ // configuration problem, the aggregate error retains every failed
212
+ // candidate diagnostic.
237
213
  lastError = error;
238
- terminalProviderFailure = undefined;
239
- attempts.push({
214
+ const responseValidationFailure = isChatV2ResponseValidationError(error);
215
+ recordAttempt({
240
216
  roundIndex,
241
217
  profileIndex,
242
218
  provider: candidate.provider,
243
219
  model: candidate.model,
244
- stage: 'configuration',
220
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
221
+ stage: responseValidationFailure ? 'response-validation' : 'configuration',
245
222
  outcome: 'failure',
246
- error: getSafeErrorMessage(error, candidate),
223
+ error: getLLMAttemptErrorMessage(error),
247
224
  });
248
225
  clearPartialResponse(roundOptions);
249
226
  continue;
@@ -253,35 +230,14 @@ export function createLLMProfileFallbackRunner(params) {
253
230
  nextRoundIndex += 1;
254
231
  return execution.result;
255
232
  }
256
- terminalProviderFailure = execution.failure;
257
233
  lastError = execution.failure.normalizedError;
258
234
  clearPartialResponse(roundOptions);
259
235
  }
260
236
  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.
237
+ // A scalar profile keeps its underlying provider/configuration error.
267
238
  if (params.candidates.length === 1 && lastError !== undefined) {
268
239
  throw lastError;
269
240
  }
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
241
  throw new LLMProfileFallbackExhaustedError(attempts);
286
242
  },
287
243
  };
@@ -0,0 +1,67 @@
1
+ export const llmProfileFieldSpecs = [
2
+ { key: 'model', inputId: 'model', valueKind: 'string' },
3
+ { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
4
+ { key: 'temperature', inputId: 'temperature', valueKind: 'required-number' },
5
+ { key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },
6
+ { key: 'topP', inputId: 'topP', valueKind: 'optional-number' },
7
+ { key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },
8
+ { key: 'topK', inputId: 'topK', valueKind: 'optional-number' },
9
+ { key: 'useTopKInput', valueKind: 'boolean', resolvedInputToggle: true },
10
+ { key: 'presencePenalty', inputId: 'presencePenalty', valueKind: 'optional-number' },
11
+ { key: 'usePresencePenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },
12
+ { key: 'frequencyPenalty', inputId: 'frequencyPenalty', valueKind: 'optional-number' },
13
+ { key: 'useFrequencyPenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },
14
+ { key: 'stopSequences', inputId: 'stopSequences' },
15
+ { key: 'useStopSequencesInput', valueKind: 'boolean', resolvedInputToggle: true },
16
+ { key: 'seed', inputId: 'seed', valueKind: 'optional-number' },
17
+ { key: 'useSeedInput', valueKind: 'boolean', resolvedInputToggle: true },
18
+ { key: 'maxTokens', inputId: 'maxTokens', valueKind: 'required-number' },
19
+ { key: 'useMaxTokensInput', valueKind: 'boolean', resolvedInputToggle: true },
20
+ { key: 'provider' },
21
+ { key: 'apiKeySource', inputId: 'apiKey' },
22
+ { key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },
23
+ { key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },
24
+ { key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },
25
+ { key: 'useCustomProviderBaseURLInput', valueKind: 'boolean', resolvedInputToggle: true },
26
+ { key: 'customProviderApi' },
27
+ { key: 'headers', inputId: 'headers' },
28
+ { key: 'useHeadersInput', valueKind: 'boolean', resolvedInputToggle: true },
29
+ { key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },
30
+ { key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },
31
+ { key: 'openAIReasoningEffort', valueKind: 'string' },
32
+ { key: 'openAIReasoningSummary', valueKind: 'string' },
33
+ { key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },
34
+ { key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },
35
+ { key: 'enableOpenAIWebSearch', valueKind: 'boolean' },
36
+ { key: 'openAIWebSearchContextSize' },
37
+ { key: 'enableOpenAICodeInterpreter', valueKind: 'boolean' },
38
+ { key: 'anthropicThinkingMode' },
39
+ { key: 'anthropicThinkingBudget', inputId: 'anthropicThinkingBudget', valueKind: 'optional-number' },
40
+ { key: 'useAnthropicThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
41
+ { key: 'anthropicEffort' },
42
+ { key: 'anthropicCacheControlTtl' },
43
+ { key: 'googleThinkingBudget', inputId: 'googleThinkingBudget', valueKind: 'optional-number' },
44
+ { key: 'useGoogleThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
45
+ { key: 'googleThinkingLevel' },
46
+ { key: 'googleIncludeThoughts', valueKind: 'boolean' },
47
+ { key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },
48
+ { key: 'enableGoogleUrlContext', valueKind: 'boolean' },
49
+ ];
50
+ export const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);
51
+ export const llmProfileInputIds = llmProfileFieldSpecs
52
+ .flatMap((field) => ('inputId' in field ? [field.inputId] : []))
53
+ .filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);
54
+ function keysForValueKind(valueKind) {
55
+ return llmProfileFieldSpecs
56
+ .filter((field) => 'valueKind' in field && field.valueKind === valueKind)
57
+ .map((field) => field.key);
58
+ }
59
+ /** Runtime validation categories for resolved LLM Profile values. */
60
+ export const llmProfileStringDataKeys = keysForValueKind('string');
61
+ export const llmProfileBooleanDataKeys = keysForValueKind('boolean');
62
+ export const llmProfileRequiredNumberDataKeys = keysForValueKind('required-number');
63
+ export const llmProfileOptionalNumberDataKeys = keysForValueKind('optional-number');
64
+ /** A serialized profile must be self-contained, not driven by hidden ports. */
65
+ export const llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs
66
+ .filter((field) => 'resolvedInputToggle' in field && field.resolvedInputToggle)
67
+ .map((field) => field.key);
@@ -3,6 +3,7 @@ import { getInputOrData } from '../../utils/inputs.js';
3
3
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
4
4
  import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
5
5
  import { LLM_PROFILE_VALUE_VERSION } from './llmProfileTypes.js';
6
+ import { parseCustomProviderApi } from './customProviderApi.js';
6
7
  export function resolveLLMProfileNodeValue(params) {
7
8
  const { data, inputs, context } = params;
8
9
  const runtimeData = data;
@@ -25,6 +26,7 @@ export function resolveLLMProfileNodeValue(params) {
25
26
  const googleThinkingBudget = data.provider === 'google' && data.useGoogleThinkingBudgetInput
26
27
  ? coerceTypeOptional(inputs['googleThinkingBudget'], 'number') ?? data.googleThinkingBudget
27
28
  : data.googleThinkingBudget;
29
+ const customProviderApi = parseCustomProviderApi(data.customProviderApi);
28
30
  const credential = resolveChatV2Credential({
29
31
  provider: data.provider,
30
32
  context,
@@ -58,6 +60,7 @@ export function resolveLLMProfileNodeValue(params) {
58
60
  useSeedInput: false,
59
61
  customProviderBaseURL,
60
62
  useCustomProviderBaseURLInput: false,
63
+ customProviderApi,
61
64
  openAIPreviousResponseId,
62
65
  useOpenAIPreviousResponseIdInput: false,
63
66
  headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
@@ -5,24 +5,7 @@ export const LLM_PROFILE_VALUE_VERSION = 1;
5
5
  * until their matching provider or input toggle is enabled. This lets editor
6
6
  * operations preserve recoverable connections across configuration changes.
7
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
- ];
8
+ export { llmProfileInputIds } from './llmProfileFieldRegistry.js';
26
9
  export function createLLMProfileNodeData() {
27
10
  return pickLLMChatV2ProfileData(createLLMChatV2NodeData());
28
11
  }
@@ -0,0 +1,42 @@
1
+ import { inferType } from '../../utils/coerceType.js';
2
+ import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
3
+ function tryParseJson(value) {
4
+ try {
5
+ return JSON.parse(value);
6
+ }
7
+ catch {
8
+ return undefined;
9
+ }
10
+ }
11
+ export function materializeLLMResponse(params) {
12
+ const { rawText, structuredOutput, responseFormat } = params;
13
+ let value;
14
+ let source;
15
+ if (!isChatV2StructuredResponseFormat(responseFormat)) {
16
+ value = { type: 'string', value: rawText };
17
+ source = 'plain-text';
18
+ }
19
+ else if (structuredOutput !== undefined) {
20
+ value = inferType(structuredOutput);
21
+ source = 'sdk-structured';
22
+ }
23
+ else {
24
+ const parsed = tryParseJson(rawText);
25
+ if (parsed === undefined) {
26
+ value = { type: 'string', value: rawText };
27
+ source = 'plain-text';
28
+ }
29
+ else {
30
+ value = inferType(parsed);
31
+ source = 'text-json';
32
+ }
33
+ }
34
+ const validationRequested = responseFormat === 'json_schema';
35
+ const valid = !validationRequested || value.type === 'object';
36
+ return {
37
+ rawText,
38
+ value,
39
+ source,
40
+ validation: !validationRequested ? 'not-requested' : valid ? 'valid' : 'invalid',
41
+ };
42
+ }
@@ -1,10 +1,48 @@
1
1
  import { anthropicModels } from '../../plugins/anthropic/anthropic.js';
2
2
  import { generativeAiGoogleModels } from '../../plugins/google/google.js';
3
3
  import { openaiModels } from '../../utils/openai.js';
4
+ const TOKENS_PER_THOUSAND = 1_000;
5
+ function isFiniteNonNegative(value) {
6
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
7
+ }
8
+ function normalizePerThousandTokenModelRegistry(provider, models) {
9
+ return Object.fromEntries(Object.entries(models).map(([modelId, model]) => {
10
+ if (model.pricing === 'unpriced') {
11
+ if (model.cost != null) {
12
+ throw new Error(`Unpriced ${provider} LLM Chat model ${modelId} must not define a rate.`);
13
+ }
14
+ return [
15
+ modelId,
16
+ {
17
+ maxTokens: model.maxTokens,
18
+ displayName: model.displayName,
19
+ },
20
+ ];
21
+ }
22
+ if (model.cost == null ||
23
+ !isFiniteNonNegative(model.cost.prompt) ||
24
+ !isFiniteNonNegative(model.cost.completion)) {
25
+ throw new Error(`Invalid ${provider} LLM Chat pricing for model ${modelId}.`);
26
+ }
27
+ return [
28
+ modelId,
29
+ {
30
+ maxTokens: model.maxTokens,
31
+ displayName: model.displayName,
32
+ cost: {
33
+ prompt: model.cost.prompt / TOKENS_PER_THOUSAND,
34
+ completion: model.cost.completion / TOKENS_PER_THOUSAND,
35
+ },
36
+ },
37
+ ];
38
+ }));
39
+ }
4
40
  const chatV2ModelRegistry = {
5
- openai: openaiModels,
41
+ // OpenAI and Google catalogs predate LLM Chat V2 and store USD per 1,000
42
+ // tokens for their legacy nodes. Normalize them once at this boundary.
43
+ openai: normalizePerThousandTokenModelRegistry('OpenAI', openaiModels),
6
44
  anthropic: anthropicModels,
7
- google: generativeAiGoogleModels,
45
+ google: normalizePerThousandTokenModelRegistry('Google', generativeAiGoogleModels),
8
46
  custom: {},
9
47
  };
10
48
  export function getChatV2ModelRegistry() {
@@ -16,8 +54,20 @@ export function getChatV2ModelInfo(provider, modelId) {
16
54
  }
17
55
  export function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
18
56
  const model = getChatV2ModelInfo(provider, modelId);
19
- if (model == null) {
57
+ if (model?.cost == null || !isFiniteNonNegative(promptTokens) || !isFiniteNonNegative(completionTokens)) {
58
+ return undefined;
59
+ }
60
+ const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
61
+ return isFiniteNonNegative(cost) ? cost : undefined;
62
+ }
63
+ /**
64
+ * Estimates a call only when the provider reported both billable text-token
65
+ * counts. Cache discounts, long-context premiums, and provider tool fees stay
66
+ * outside this baseline estimate until their billing inputs are modeled.
67
+ */
68
+ export function calculateChatV2UsageCost(provider, modelId, usage) {
69
+ if (!isFiniteNonNegative(usage?.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
20
70
  return undefined;
21
71
  }
22
- return model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
72
+ return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
23
73
  }
@@ -1,6 +1,8 @@
1
- export const LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE = 'Supported by OpenAI, Anthropic, and compatible Custom providers. Custom providers receive parallel_tool_calls only when enabled; otherwise their default applies unless Extra provider options supplies the field.';
1
+ import { getCustomProviderApiContract } from './customProviderApi.js';
2
+ import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
3
+ export const LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE = 'Allows the model to request multiple tool calls in one round.';
2
4
  export function supportsLLMChatV2ParallelToolCalls(provider) {
3
- return provider === 'openai' || provider === 'anthropic' || provider === 'custom';
5
+ return getChatV2ProviderCapabilities(provider).parallelToolCalls;
4
6
  }
5
7
  function mergeProviderOptions(providerOptions, provider, options) {
6
8
  return {
@@ -26,6 +28,11 @@ export function applyLLMChatV2ParallelToolCallProviderOptions(params) {
26
28
  disableParallelToolUse: !parallelToolCalls,
27
29
  });
28
30
  case 'custom':
31
+ if (getCustomProviderApiContract(params.customProviderApi).parallelToolCalls === 'openai-option') {
32
+ return mergeProviderOptions(providerOptions, 'openai', {
33
+ parallelToolCalls: !!parallelToolCalls,
34
+ });
35
+ }
29
36
  // OpenAI-compatible endpoints vary widely. Do not send an unsupported
30
37
  // field to existing/default Custom-provider graphs unless the user
31
38
  // explicitly opts in to requesting parallel calls.