@valerypopoff/rivet2-core 2.1.2 → 2.1.4

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 (112) hide show
  1. package/dist/cjs/bundle.cjs +3373 -1208
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +625 -0
  4. package/dist/cjs/webAppRuntime.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +3 -0
  6. package/dist/esm/api/processSettings.js +5 -0
  7. package/dist/esm/api/streaming.js +6 -0
  8. package/dist/esm/exports.js +7 -0
  9. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  10. package/dist/esm/model/GraphProcessor.js +35 -49
  11. package/dist/esm/model/GraphProgress.js +15 -0
  12. package/dist/esm/model/GraphRunLifecycle.js +67 -0
  13. package/dist/esm/model/MarkdownSanitizationPolicy.js +38 -0
  14. package/dist/esm/model/Nodes.js +3 -0
  15. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  16. package/dist/esm/model/RecordingPlayer.js +10 -0
  17. package/dist/esm/model/SubprocessorBridge.js +1 -0
  18. package/dist/esm/model/UiGraph.js +181 -1
  19. package/dist/esm/model/UiGraphActionProtocol.js +122 -0
  20. package/dist/esm/model/UiGraphBindings.js +530 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +40 -0
  22. package/dist/esm/model/UiGraphNormalization.js +298 -0
  23. package/dist/esm/model/UiGraphRendererStyles.js +456 -6
  24. package/dist/esm/model/UiGraphRuntimeModel.js +371 -0
  25. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -2
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +35 -48
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +98 -0
  30. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +64 -0
  31. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +11 -39
  32. package/dist/esm/model/chat-v2/index.js +2 -0
  33. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +31 -11
  35. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +21 -9
  36. package/dist/esm/model/chat-v2/providerOptions.js +9 -35
  37. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  38. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  39. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  40. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  41. package/dist/esm/model/nodes/DelayNode.js +3 -14
  42. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  43. package/dist/esm/model/nodes/JoinNode.js +2 -13
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +3 -3
  45. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  46. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  47. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  48. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  49. package/dist/esm/model/nodes/PassthroughNode.js +3 -14
  50. package/dist/esm/model/nodes/RaceInputsNode.js +2 -13
  51. package/dist/esm/model/nodes/ReportProgressNode.js +57 -0
  52. package/dist/esm/model/nodes/variadicPortIndex.js +32 -0
  53. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  54. package/dist/esm/plugins/autoevals/AutoEvalsNode.js +3 -1
  55. package/dist/esm/plugins/gentrace/gentraceSdk.js +8 -0
  56. package/dist/esm/plugins/gentrace/plugin.js +5 -4
  57. package/dist/esm/plugins/google/google.js +9 -7
  58. package/dist/esm/recording/ExecutionRecorder.js +5 -0
  59. package/dist/esm/utils/fetchEventSource.js +16 -17
  60. package/dist/esm/utils/pQueueCompat.js +1 -1
  61. package/dist/esm/utils/serialization/serialization.js +4 -0
  62. package/dist/esm/utils/serialization/serializationUtils.js +16 -0
  63. package/dist/esm/utils/serialization/serialization_v4.js +5 -4
  64. package/dist/esm/webAppRuntime.js +4 -0
  65. package/dist/types/api/createProcessor.d.ts +1 -1
  66. package/dist/types/api/processSettings.d.ts +3 -4
  67. package/dist/types/api/streaming.d.ts +6 -0
  68. package/dist/types/exports.d.ts +7 -0
  69. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  70. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  71. package/dist/types/model/GraphProcessor.d.ts +7 -0
  72. package/dist/types/model/GraphProgress.d.ts +6 -0
  73. package/dist/types/model/GraphRunLifecycle.d.ts +22 -0
  74. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +9 -0
  75. package/dist/types/model/Nodes.d.ts +3 -2
  76. package/dist/types/model/ProcessContext.d.ts +5 -2
  77. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  78. package/dist/types/model/Settings.d.ts +1 -0
  79. package/dist/types/model/UiGraph.d.ts +50 -5
  80. package/dist/types/model/UiGraphActionProtocol.d.ts +69 -0
  81. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +4 -0
  83. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  84. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  85. package/dist/types/model/UiGraphRuntimeModel.d.ts +124 -0
  86. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  87. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +46 -0
  88. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +42 -0
  89. package/dist/types/model/chat-v2/chatV2Types.d.ts +1 -0
  90. package/dist/types/model/chat-v2/index.d.ts +2 -0
  91. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +1 -0
  92. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +2 -0
  93. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -2
  94. package/dist/types/model/nodes/ArrayNode.d.ts +0 -1
  95. package/dist/types/model/nodes/AssembleMessageNode.d.ts +0 -1
  96. package/dist/types/model/nodes/AssemblePromptNode.d.ts +0 -1
  97. package/dist/types/model/nodes/DelayNode.d.ts +0 -1
  98. package/dist/types/model/nodes/DidRunNode.d.ts +0 -1
  99. package/dist/types/model/nodes/JoinNode.d.ts +0 -1
  100. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  101. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  102. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  103. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  104. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  105. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +5 -0
  106. package/dist/types/plugins/gentrace/plugin.d.ts +1 -1
  107. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  108. package/dist/types/utils/pQueueCompat.d.ts +1 -1
  109. package/dist/types/webAppRuntime.d.ts +9 -0
  110. package/package.json +15 -9
  111. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  112. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -0,0 +1,371 @@
1
+ import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphComponentActionOutputStateKeys, getUiGraphComponentActionState, getUiGraphInitialState, } from './UiGraph.js';
2
+ import { normalizeGraphProgress } from './GraphProgress.js';
3
+ const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\s\S]+)$/i;
4
+ const IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
5
+ const RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
6
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
7
+ /**
8
+ * Coordinates independent web-app actions without allowing older completions to
9
+ * clear newer loading states or overwrite newer writes to the same UI state key.
10
+ */
11
+ export function createUiGraphActionExecutionController() {
12
+ let nextVersion = 0;
13
+ const activeExecutionByComponent = new Map();
14
+ const latestWriterByStateKey = new Map();
15
+ return {
16
+ begin(component) {
17
+ if (activeExecutionByComponent.has(component.id)) {
18
+ return undefined;
19
+ }
20
+ const execution = { componentId: component.id, id: ++nextVersion };
21
+ activeExecutionByComponent.set(component.id, execution.id);
22
+ for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {
23
+ latestWriterByStateKey.set(stateKey, execution.id);
24
+ }
25
+ return execution;
26
+ },
27
+ finish(execution) {
28
+ if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {
29
+ return false;
30
+ }
31
+ activeExecutionByComponent.delete(execution.componentId);
32
+ return true;
33
+ },
34
+ isCurrent(execution) {
35
+ return activeExecutionByComponent.get(execution.componentId) === execution.id;
36
+ },
37
+ isRunning(componentId) {
38
+ return activeExecutionByComponent.has(componentId);
39
+ },
40
+ noteStateWrite(stateKey) {
41
+ const normalizedStateKey = stateKey.trim();
42
+ if (normalizedStateKey) {
43
+ latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);
44
+ }
45
+ },
46
+ resolveStatePatch(execution, statePatch) {
47
+ if (!statePatch) {
48
+ return undefined;
49
+ }
50
+ const applicableEntries = Object.entries(statePatch).filter(([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id);
51
+ return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;
52
+ },
53
+ reset() {
54
+ activeExecutionByComponent.clear();
55
+ latestWriterByStateKey.clear();
56
+ },
57
+ };
58
+ }
59
+ /**
60
+ * Owns mutable web-app interaction state for every renderer. React and direct
61
+ * DOM hosts subscribe to this controller instead of reimplementing action
62
+ * cancellation, loading/error state, and stale state-patch protection.
63
+ */
64
+ export function createUiGraphInteractionController(initialUiGraph, options = {}) {
65
+ let uiGraphId = initialUiGraph.id;
66
+ let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);
67
+ let actionErrors = {};
68
+ let actionProgress = {};
69
+ let snapshot;
70
+ const actionController = createUiGraphActionExecutionController();
71
+ const activeActions = new Map();
72
+ const listeners = new Set();
73
+ const updateSnapshot = () => {
74
+ snapshot = {
75
+ actionErrors,
76
+ actionProgress,
77
+ runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
78
+ state,
79
+ };
80
+ };
81
+ const publish = (change) => {
82
+ updateSnapshot();
83
+ for (const listener of listeners) {
84
+ listener(change);
85
+ }
86
+ };
87
+ const abortMatchingActions = (predicate, notify) => {
88
+ let changed = false;
89
+ for (const [executionId, activeAction] of activeActions) {
90
+ if (!predicate(activeAction, executionId)) {
91
+ continue;
92
+ }
93
+ activeAction.abortController.abort();
94
+ activeActions.delete(executionId);
95
+ actionController.finish(activeAction.execution);
96
+ changed = true;
97
+ }
98
+ if (changed && notify) {
99
+ publish('action');
100
+ }
101
+ return changed;
102
+ };
103
+ const abortAllActions = (notify) => {
104
+ let changed = abortMatchingActions(() => true, false);
105
+ actionController.reset();
106
+ if (Object.keys(actionProgress).length > 0) {
107
+ actionProgress = {};
108
+ changed = true;
109
+ }
110
+ if (changed && notify) {
111
+ publish('action');
112
+ }
113
+ };
114
+ const removeActionPresentation = (componentId) => {
115
+ if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
116
+ actionErrors = { ...actionErrors };
117
+ delete actionErrors[componentId];
118
+ }
119
+ if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
120
+ actionProgress = { ...actionProgress };
121
+ delete actionProgress[componentId];
122
+ }
123
+ };
124
+ updateSnapshot();
125
+ return {
126
+ abortActions() {
127
+ abortAllActions(true);
128
+ },
129
+ cancelAction(componentId) {
130
+ if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {
131
+ removeActionPresentation(componentId);
132
+ publish('action');
133
+ }
134
+ },
135
+ detachActions() {
136
+ activeActions.clear();
137
+ actionController.reset();
138
+ actionProgress = {};
139
+ updateSnapshot();
140
+ },
141
+ getSnapshot() {
142
+ return snapshot;
143
+ },
144
+ async runAction(component, runner) {
145
+ const execution = actionController.begin(component);
146
+ if (!execution) {
147
+ return;
148
+ }
149
+ const abortController = new AbortController();
150
+ activeActions.set(execution.id, { abortController, execution });
151
+ removeActionPresentation(component.id);
152
+ publish('action');
153
+ try {
154
+ const result = await runner({
155
+ abortOtherActions: () => abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),
156
+ componentId: component.id,
157
+ reportProgress: (progress) => {
158
+ if (!actionController.isCurrent(execution))
159
+ return;
160
+ const normalized = normalizeGraphProgress(progress);
161
+ if (!normalized)
162
+ return;
163
+ actionProgress = { ...actionProgress, [component.id]: normalized };
164
+ publish('action');
165
+ },
166
+ signal: abortController.signal,
167
+ state: getUiGraphComponentActionState(component, state),
168
+ });
169
+ if (!actionController.isCurrent(execution)) {
170
+ return;
171
+ }
172
+ const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
173
+ if (statePatch) {
174
+ state = applyUiGraphStatePatch(state, statePatch);
175
+ }
176
+ }
177
+ catch (error) {
178
+ if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
179
+ actionErrors = {
180
+ ...actionErrors,
181
+ [component.id]: error instanceof Error ? error.message : String(error),
182
+ };
183
+ }
184
+ }
185
+ finally {
186
+ if (activeActions.delete(execution.id)) {
187
+ actionController.finish(execution);
188
+ if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
189
+ actionProgress = { ...actionProgress };
190
+ delete actionProgress[component.id];
191
+ }
192
+ publish('action');
193
+ }
194
+ }
195
+ },
196
+ setUiGraph(nextUiGraph) {
197
+ if (nextUiGraph.id !== uiGraphId) {
198
+ abortAllActions(false);
199
+ uiGraphId = nextUiGraph.id;
200
+ state = getUiGraphInitialState(nextUiGraph);
201
+ actionErrors = {};
202
+ actionProgress = {};
203
+ publish('graph');
204
+ return;
205
+ }
206
+ const actionComponentIds = new Set(nextUiGraph.components
207
+ .filter((component) => component.type === 'button' || component.type === 'chat')
208
+ .map((component) => component.id));
209
+ let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);
210
+ const remainingErrors = Object.fromEntries(Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId)));
211
+ const remainingProgress = Object.fromEntries(Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId)));
212
+ if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
213
+ actionErrors = remainingErrors;
214
+ changed = true;
215
+ }
216
+ if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {
217
+ actionProgress = remainingProgress;
218
+ changed = true;
219
+ }
220
+ if (changed) {
221
+ publish('graph');
222
+ }
223
+ },
224
+ subscribe(listener) {
225
+ listeners.add(listener);
226
+ return () => listeners.delete(listener);
227
+ },
228
+ updateState(stateKey, value) {
229
+ actionController.noteStateWrite(stateKey);
230
+ state = { ...state, [stateKey]: value };
231
+ publish('state');
232
+ },
233
+ updateStatePatch(statePatch) {
234
+ for (const stateKey of Object.keys(statePatch)) {
235
+ actionController.noteStateWrite(stateKey);
236
+ }
237
+ state = applyUiGraphStatePatch(state, statePatch);
238
+ publish('state');
239
+ },
240
+ };
241
+ }
242
+ export function getUiGraphComponentRenderModel(component, state) {
243
+ switch (component.type) {
244
+ case 'text':
245
+ return { component, text: component.text, type: 'text' };
246
+ case 'markdown':
247
+ return { component, markdown: component.markdown, type: 'markdown' };
248
+ case 'gap':
249
+ return { component, size: component.size, type: 'gap' };
250
+ case 'input':
251
+ case 'textarea':
252
+ return {
253
+ component,
254
+ label: getUiGraphComponentLabel(component),
255
+ type: component.type,
256
+ value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,
257
+ };
258
+ case 'button':
259
+ return { component, label: component.label, type: 'button' };
260
+ case 'chat':
261
+ return {
262
+ component,
263
+ draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,
264
+ messages: getUiGraphChatMessages(component.id, state),
265
+ type: 'chat',
266
+ };
267
+ case 'output':
268
+ return {
269
+ component,
270
+ label: getUiGraphComponentLabel(component),
271
+ output: getUiGraphOutputRenderModel(state, component.stateKey, component.renderAs ?? 'text'),
272
+ type: 'output',
273
+ };
274
+ }
275
+ }
276
+ export function getUiGraphComponentLabel(component) {
277
+ return component.label || component.stateKey;
278
+ }
279
+ export function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
280
+ const value = state[stateKey];
281
+ const hasValue = hasUiGraphStateValue(state, stateKey);
282
+ const renderedValue = renderUiGraphOutputValue(value, renderAs);
283
+ const imageSource = hasValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;
284
+ const imageErrorMessage = hasValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;
285
+ return {
286
+ hasValue,
287
+ ...(imageErrorMessage ? { imageErrorMessage } : {}),
288
+ ...(imageSource ? { imageSource } : {}),
289
+ ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),
290
+ renderedValue,
291
+ renderAs,
292
+ };
293
+ }
294
+ export function hasUiGraphStateValue(state, key) {
295
+ return Object.prototype.hasOwnProperty.call(state, key) && state[key] !== undefined;
296
+ }
297
+ export function renderUiGraphOutputValue(value, renderAs) {
298
+ if (renderAs === 'json') {
299
+ return stringifyUiGraphValue(value) ?? '';
300
+ }
301
+ return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';
302
+ }
303
+ export function getUiGraphImageSource(value) {
304
+ if (typeof value !== 'string') {
305
+ return undefined;
306
+ }
307
+ const source = value.trim();
308
+ if (!source) {
309
+ return undefined;
310
+ }
311
+ const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);
312
+ if (dataUrl) {
313
+ const base64 = normalizeBase64(dataUrl[2]);
314
+ return base64 ? `data:${normalizeImageMediaType(dataUrl[1])};base64,${base64}` : undefined;
315
+ }
316
+ const base64 = normalizeBase64(source);
317
+ const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;
318
+ if (base64 && inferredMediaType) {
319
+ return `data:${inferredMediaType};base64,${base64}`;
320
+ }
321
+ if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {
322
+ return undefined;
323
+ }
324
+ try {
325
+ const protocol = new URL(source, 'https://rivet.invalid').protocol;
326
+ return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;
327
+ }
328
+ catch {
329
+ return undefined;
330
+ }
331
+ }
332
+ function normalizeBase64(value) {
333
+ const compact = value.replace(/\s/g, '');
334
+ return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;
335
+ }
336
+ function normalizeImageMediaType(mediaType) {
337
+ const normalized = mediaType.toLowerCase();
338
+ return normalized === 'image/jpg' ? 'image/jpeg' : normalized;
339
+ }
340
+ function inferBase64ImageMediaType(value) {
341
+ if (value.startsWith('iVBORw0KGgo'))
342
+ return 'image/png';
343
+ if (value.startsWith('/9j/'))
344
+ return 'image/jpeg';
345
+ if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh'))
346
+ return 'image/gif';
347
+ return undefined;
348
+ }
349
+ export function stringifyUiGraphValue(value) {
350
+ try {
351
+ return JSON.stringify(value, null, 2);
352
+ }
353
+ catch {
354
+ return '[Unserializable value]';
355
+ }
356
+ }
357
+ export function getUiGraphJsonOutputFilename(appName, date = new Date()) {
358
+ const safeName = appName
359
+ .trim()
360
+ .replace(/[<>:"/\\|?*\u0000-\u001F]/g, '-')
361
+ .replace(/\s+/g, ' ')
362
+ .slice(0, 80);
363
+ return `${safeName || 'Rivet web app'} ${formatUiGraphDownloadDateTime(date)}.json`;
364
+ }
365
+ export function formatUiGraphDownloadDateTime(date) {
366
+ const pad = (value) => `${value}`.padStart(2, '0');
367
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}`;
368
+ }
369
+ export function applyUiGraphStatePatch(state, statePatch) {
370
+ return statePatch ? { ...state, ...statePatch } : state;
371
+ }
@@ -0,0 +1,19 @@
1
+ export const RIVET_WEB_APP_STATUS_FUNCTION_NAME = 'setWebAppStatus';
2
+ /** Built-in External Call function used to report web-app status. */
3
+ export const rivetWebAppStatusExternalFunction = async (context, value) => {
4
+ const message = formatRivetWebAppStatusMessage(value);
5
+ context.reportProgress({ message });
6
+ return { type: 'string', value: message };
7
+ };
8
+ export function formatRivetWebAppStatusMessage(value) {
9
+ if (typeof value === 'string')
10
+ return value;
11
+ if (value == null)
12
+ return '';
13
+ try {
14
+ return JSON.stringify(value) ?? String(value);
15
+ }
16
+ catch {
17
+ return '[Unserializable web app status]';
18
+ }
19
+ }
@@ -123,7 +123,7 @@ function buildTextArgs(options) {
123
123
  const args = {
124
124
  model: options.model,
125
125
  messages: options.messages,
126
- maxRetries: 0,
126
+ maxRetries: options.maxRetries ?? 0,
127
127
  };
128
128
  if (options.tools !== undefined)
129
129
  args.tools = options.tools;
@@ -61,8 +61,8 @@ function fingerprintNodeDataForCache(data) {
61
61
  const isCustomProvider = data.provider === 'custom';
62
62
  return {
63
63
  ...data,
64
- baseURL: isCustomProvider ? '' : data.baseURL,
65
- useBaseURLInput: isCustomProvider ? false : data.useBaseURLInput,
64
+ baseURL: '',
65
+ useBaseURLInput: false,
66
66
  customProviderBaseURL: isCustomProvider ? data.customProviderBaseURL : '',
67
67
  useCustomProviderBaseURLInput: isCustomProvider ? data.useCustomProviderBaseURLInput : false,
68
68
  extraProviderOptions: data.useExtraProviderOptionsInput ? '' : fingerprintSecret(data.extraProviderOptions) ?? '',
@@ -2,8 +2,9 @@ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMes
2
2
  import { generateChatV2, streamChatV2 } from './aiSdkBridge.js';
3
3
  import { chatMessagesToModelMessages } from './messageConverter.js';
4
4
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
5
+ import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
5
6
  import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, normalizeChatV2ProviderError, } from './chatV2Errors.js';
6
- import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount, waitForLLMChatV2RetryCooldown, } from './chatV2Retry.js';
7
+ import { waitForLLMChatV2RetryCooldown, } from './chatV2Retry.js';
7
8
  import { createChatV2CommonOutputs, createChatV2ProviderFailureOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
8
9
  class ChatV2RetryFailure extends Error {
9
10
  error;
@@ -41,46 +42,42 @@ function normalizeProviderFailureMessage(error, options) {
41
42
  function normalizeProviderFailureMessages(errors, options) {
42
43
  return errors.map((error) => normalizeProviderFailureMessage(error, options));
43
44
  }
44
- async function runChatV2WithRetry(chatOptions, retryOptions, transportMode) {
45
- const repeatTimes = retryOptions.retryOnNon200
46
- ? normalizeLLMChatV2RetryCount(retryOptions.retryOnNon200RepeatTimes)
47
- : 0;
48
- const cooldownMs = normalizeLLMChatV2RetryCooldownMs(retryOptions.retryOnNon200CooldownMs);
45
+ async function runChatV2WithRetry(chatOptions, retryPlan, signal, transportMode) {
49
46
  const requestStatuses = [];
50
47
  const requestErrors = [];
51
48
  for (let attempt = 0;; attempt++) {
52
49
  try {
53
50
  const result = transportMode === 'generate' ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
54
51
  const statusCode = result.requestStatus ?? 200;
55
- if (retryOptions.retryOnNon200) {
52
+ if (retryPlan.enabled) {
56
53
  requestStatuses.push(statusCode);
57
54
  }
58
- if (!retryOptions.retryOnNon200 || statusCode === 200) {
55
+ if (!retryPlan.enabled || statusCode === 200) {
59
56
  return { result, requestStatuses, requestErrors };
60
57
  }
61
58
  const responseError = buildNon200StatusError(statusCode);
62
59
  requestErrors.push(responseError);
63
- if (attempt >= repeatTimes) {
60
+ if (attempt >= retryPlan.repeatTimes) {
64
61
  return { result, requestStatuses, requestErrors, responseError };
65
62
  }
66
- await waitForLLMChatV2RetryCooldown(cooldownMs, retryOptions.context.signal);
63
+ await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
67
64
  }
68
65
  catch (error) {
69
66
  const statusCode = getChatV2ProviderErrorStatusCode(error);
70
- if (!retryOptions.retryOnNon200 || statusCode == null || statusCode === 200) {
67
+ if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
71
68
  throw error;
72
69
  }
73
70
  requestStatuses.push(statusCode);
74
71
  requestErrors.push(error);
75
- if (attempt >= repeatTimes) {
72
+ if (attempt >= retryPlan.repeatTimes) {
76
73
  throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
77
74
  }
78
- await waitForLLMChatV2RetryCooldown(cooldownMs, retryOptions.context.signal);
75
+ await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
79
76
  }
80
77
  }
81
78
  }
82
- function buildProviderFailureResult(requestMessages, options, normalizedError, rawError, requestStatuses, requestErrors) {
83
- if (!options.outputRequestStatus) {
79
+ function buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors) {
80
+ if (!plan.output.outputRequestStatus) {
84
81
  return undefined;
85
82
  }
86
83
  const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
@@ -88,14 +85,14 @@ function buildProviderFailureResult(requestMessages, options, normalizedError, r
88
85
  return undefined;
89
86
  }
90
87
  const responseError = getProviderFailureMessage(normalizedError);
91
- const retryRequestStatuses = options.retryOnNon200
88
+ const retryRequestStatuses = plan.retry.enabled
92
89
  ? requestStatuses.length > 0
93
90
  ? requestStatuses
94
91
  : statusCode == null
95
92
  ? []
96
93
  : [statusCode]
97
94
  : [];
98
- const retryRequestErrors = options.retryOnNon200 ? (requestErrors.length > 0 ? requestErrors : [responseError]) : [];
95
+ const retryRequestErrors = plan.retry.enabled ? (requestErrors.length > 0 ? requestErrors : [responseError]) : [];
99
96
  const commonOutputs = createChatV2ProviderFailureOutputs({
100
97
  requestMessages,
101
98
  responseStatus: statusCode,
@@ -103,10 +100,10 @@ function buildProviderFailureResult(requestMessages, options, normalizedError, r
103
100
  requestStatuses: retryRequestStatuses,
104
101
  requestErrors: retryRequestErrors,
105
102
  requestBodies: options.requestBodies,
106
- outputUsage: options.outputUsage,
107
- outputReasoning: options.outputReasoning,
108
- includeFunctionCalls: options.includeFunctionCalls,
109
- retryOnNon200: options.retryOnNon200,
103
+ outputUsage: plan.output.outputUsage,
104
+ outputReasoning: plan.output.outputReasoning,
105
+ includeFunctionCalls: plan.output.includeFunctionCalls,
106
+ retryOnNon200: plan.retry.enabled,
110
107
  });
111
108
  const allMessagesOutput = commonOutputs['all-messages'];
112
109
  if (allMessagesOutput?.type !== 'chat-message[]') {
@@ -138,24 +135,14 @@ export async function runChatV2Pipeline(options) {
138
135
  : options.additionalTools == null
139
136
  ? functionTools
140
137
  : { ...functionTools, ...options.additionalTools };
141
- const shouldStreamResponse = options.emitPartialOutputs !== false;
142
- const transportMode = shouldStreamResponse ? 'stream' : 'generate';
143
- const chatResponse = await runChatV2WithRetry({
144
- model: options.model,
138
+ const plan = buildChatV2RequestPlan({
139
+ ...options,
145
140
  messages: modelMessages,
146
141
  tools,
147
- maxTokens: options.maxTokens,
148
- temperature: options.temperature,
149
- topP: options.topP,
150
- topK: options.topK,
151
- presencePenalty: options.presencePenalty,
152
- frequencyPenalty: options.frequencyPenalty,
153
- stopSequences: options.stopSequences,
154
- seed: options.seed,
155
- responseOutput: options.responseOutput,
156
- responseFormat: options.responseFormat,
157
- providerOptions: options.providerOptions,
158
- toolChoice: options.toolChoice,
142
+ });
143
+ const shouldStreamResponse = plan.transportMode === 'stream';
144
+ const chatResponse = await runChatV2WithRetry({
145
+ ...plan.request,
159
146
  abortSignal: options.context.signal,
160
147
  executeStream: options.executeStream,
161
148
  executeGenerate: options.executeGenerate,
@@ -177,13 +164,13 @@ export async function runChatV2Pipeline(options) {
177
164
  outputUsage: false,
178
165
  outputReasoning: false,
179
166
  outputRequestStatus: false,
180
- includeFunctionCalls: options.includeFunctionCalls,
181
- functionCallMode: options.functionCallMode,
167
+ includeFunctionCalls: plan.output.includeFunctionCalls,
168
+ functionCallMode: plan.output.functionCallMode,
182
169
  retryOnNon200: false,
183
170
  responseFormat: undefined,
184
171
  }));
185
172
  },
186
- }, options, transportMode).catch((caughtError) => {
173
+ }, plan.retry, options.context.signal, plan.transportMode).catch((caughtError) => {
187
174
  const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : undefined;
188
175
  const rawError = retryFailure?.error ?? caughtError;
189
176
  const normalizedError = normalizeChatV2ProviderError(rawError, {
@@ -192,7 +179,7 @@ export async function runChatV2Pipeline(options) {
192
179
  });
193
180
  const requestStatuses = retryFailure?.requestStatuses ?? [];
194
181
  const requestErrors = normalizeProviderFailureMessages(retryFailure?.requestErrors ?? [], options);
195
- const failureResult = buildProviderFailureResult(requestMessages, options, normalizedError, rawError, requestStatuses, requestErrors);
182
+ const failureResult = buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors);
196
183
  if (failureResult) {
197
184
  return failureResult;
198
185
  }
@@ -220,13 +207,13 @@ export async function runChatV2Pipeline(options) {
220
207
  requestStatuses,
221
208
  requestErrors,
222
209
  requestBodies: options.requestBodies,
223
- outputUsage: options.outputUsage,
224
- outputReasoning: options.outputReasoning,
225
- outputRequestStatus: options.outputRequestStatus,
226
- includeFunctionCalls: options.includeFunctionCalls,
227
- functionCallMode: options.functionCallMode,
228
- retryOnNon200: options.retryOnNon200,
229
- responseFormat: options.responseFormat,
210
+ outputUsage: plan.output.outputUsage,
211
+ outputReasoning: plan.output.outputReasoning,
212
+ outputRequestStatus: plan.output.outputRequestStatus,
213
+ includeFunctionCalls: plan.output.includeFunctionCalls,
214
+ functionCallMode: plan.output.functionCallMode,
215
+ retryOnNon200: plan.retry.enabled,
216
+ responseFormat: plan.request.responseFormat,
230
217
  });
231
218
  const allMessagesOutput = commonOutputs['all-messages'];
232
219
  if (allMessagesOutput?.type !== 'chat-message[]') {