@valerypopoff/rivet2-core 2.1.3 → 2.1.5

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 (114) hide show
  1. package/dist/cjs/bundle.cjs +10138 -5679
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +1214 -0
  4. package/dist/cjs/webAppRuntime.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +8 -1
  6. package/dist/esm/api/streaming.js +6 -0
  7. package/dist/esm/exports.js +8 -0
  8. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  9. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  10. package/dist/esm/model/GraphProcessor.js +1138 -86
  11. package/dist/esm/model/GraphProgress.js +15 -0
  12. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  13. package/dist/esm/model/Nodes.js +12 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +19 -0
  16. package/dist/esm/model/StoredValueStore.js +226 -0
  17. package/dist/esm/model/SubprocessorBridge.js +50 -18
  18. package/dist/esm/model/ToolCallContinuation.js +1 -0
  19. package/dist/esm/model/UiGraph.js +177 -4
  20. package/dist/esm/model/UiGraphActionProtocol.js +131 -0
  21. package/dist/esm/model/UiGraphBindings.js +530 -0
  22. package/dist/esm/model/UiGraphBrowserRuntime.js +373 -0
  23. package/dist/esm/model/UiGraphNormalization.js +148 -0
  24. package/dist/esm/model/UiGraphRendererStyles.js +1108 -42
  25. package/dist/esm/model/UiGraphRuntimeModel.js +518 -2
  26. package/dist/esm/model/UiGraphSchema.js +91 -0
  27. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  31. package/dist/esm/model/chat-v2/index.js +1 -0
  32. package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
  33. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  34. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  35. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  36. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  37. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  38. package/dist/esm/model/nodes/DelayNode.js +3 -14
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/JoinNode.js +2 -13
  43. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  44. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  45. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  46. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  47. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  48. package/dist/esm/model/nodes/MatchNode.js +7 -7
  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/SetStoredValueNode.js +84 -0
  53. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  54. package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
  55. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  56. package/dist/esm/model/nodes/variadicPortIndex.js +32 -0
  57. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  58. package/dist/esm/recording/ExecutionRecorder.js +6 -0
  59. package/dist/esm/utils/coerceType.js +3 -0
  60. package/dist/esm/utils/fetchEventSource.js +16 -17
  61. package/dist/esm/utils/serialization/serialization.js +4 -0
  62. package/dist/esm/utils/serialization/serializationUtils.js +8 -27
  63. package/dist/esm/utils/serialization/serialization_v4.js +3 -3
  64. package/dist/esm/webAppRuntime.js +4 -2
  65. package/dist/types/api/createProcessor.d.ts +4 -0
  66. package/dist/types/api/streaming.d.ts +6 -0
  67. package/dist/types/exports.d.ts +8 -0
  68. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  69. package/dist/types/model/EditorDefinition.d.ts +2 -1
  70. package/dist/types/model/ExecutorProtocol.d.ts +19 -0
  71. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  72. package/dist/types/model/GraphProcessor.d.ts +26 -2
  73. package/dist/types/model/GraphProgress.d.ts +6 -0
  74. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  75. package/dist/types/model/Nodes.d.ts +6 -2
  76. package/dist/types/model/ProcessContext.d.ts +18 -0
  77. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  78. package/dist/types/model/StoredValueStore.d.ts +55 -0
  79. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  80. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  81. package/dist/types/model/UiGraph.d.ts +63 -9
  82. package/dist/types/model/UiGraphActionProtocol.d.ts +71 -0
  83. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  84. package/dist/types/model/UiGraphBrowserRuntime.d.ts +55 -0
  85. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  86. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  87. package/dist/types/model/UiGraphRuntimeModel.d.ts +97 -6
  88. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  89. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  90. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  91. package/dist/types/model/chat-v2/index.d.ts +1 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  93. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  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/GetStoredValueNode.d.ts +25 -0
  100. package/dist/types/model/nodes/JoinNode.d.ts +0 -1
  101. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  102. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  103. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  104. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  105. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  106. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  107. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  108. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  109. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  110. package/dist/types/recording/RecordedEvents.d.ts +10 -0
  111. package/dist/types/webAppRuntime.d.ts +8 -3
  112. package/package.json +2 -2
  113. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  114. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -1,9 +1,424 @@
1
+ import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphChatPins, 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
+ const UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD = 128 * 1024;
8
+ const UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS = 16 * 1024;
9
+ const UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS = 16 * 1024;
10
+ const ACTION_LOADING_DELAY_MS = 300;
11
+ function getUiGraphActionComponentsById(uiGraph) {
12
+ return new Map(uiGraph.components
13
+ .filter((component) => component.type === 'button' || component.type === 'chat')
14
+ .map((component) => [component.id, component]));
15
+ }
16
+ /**
17
+ * Action data is persisted as JSON, so its execution contract is limited to
18
+ * primitives, arrays, and plain records. Compare the structure rather than
19
+ * serialized property order: a harmless project reserialization must not
20
+ * cancel an active action, but changing its target or bindings must.
21
+ */
22
+ function areUiGraphActionValuesEqual(left, right) {
23
+ if (Object.is(left, right)) {
24
+ return true;
25
+ }
26
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') {
27
+ return false;
28
+ }
29
+ if (Array.isArray(left) || Array.isArray(right)) {
30
+ return (Array.isArray(left) &&
31
+ Array.isArray(right) &&
32
+ left.length === right.length &&
33
+ left.every((value, index) => areUiGraphActionValuesEqual(value, right[index])));
34
+ }
35
+ const leftRecord = left;
36
+ const rightRecord = right;
37
+ const leftKeys = Object.keys(leftRecord);
38
+ const rightKeys = Object.keys(rightRecord);
39
+ return (leftKeys.length === rightKeys.length &&
40
+ leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightRecord, key) &&
41
+ areUiGraphActionValuesEqual(leftRecord[key], rightRecord[key])));
42
+ }
43
+ function areUiGraphActionComponentsExecutionEquivalent(left, right) {
44
+ return left.type === right.type && areUiGraphActionValuesEqual(left.action, right.action);
45
+ }
46
+ /**
47
+ * Coordinates independent web-app actions without allowing older completions to
48
+ * clear newer loading states or overwrite newer writes to the same UI state key.
49
+ */
50
+ export function createUiGraphActionExecutionController() {
51
+ let nextVersion = 0;
52
+ const activeExecutionByComponent = new Map();
53
+ const latestWriterByStateKey = new Map();
54
+ return {
55
+ begin(component) {
56
+ if (activeExecutionByComponent.has(component.id)) {
57
+ return undefined;
58
+ }
59
+ const execution = { componentId: component.id, id: ++nextVersion };
60
+ activeExecutionByComponent.set(component.id, execution.id);
61
+ for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {
62
+ latestWriterByStateKey.set(stateKey, execution.id);
63
+ }
64
+ return execution;
65
+ },
66
+ finish(execution) {
67
+ if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {
68
+ return false;
69
+ }
70
+ activeExecutionByComponent.delete(execution.componentId);
71
+ return true;
72
+ },
73
+ isCurrent(execution) {
74
+ return activeExecutionByComponent.get(execution.componentId) === execution.id;
75
+ },
76
+ isRunning(componentId) {
77
+ return activeExecutionByComponent.has(componentId);
78
+ },
79
+ noteStateWrite(stateKey) {
80
+ const normalizedStateKey = stateKey.trim();
81
+ if (normalizedStateKey) {
82
+ latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);
83
+ }
84
+ },
85
+ resolveStatePatch(execution, statePatch) {
86
+ if (!statePatch) {
87
+ return undefined;
88
+ }
89
+ const applicableEntries = Object.entries(statePatch).filter(([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id);
90
+ return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;
91
+ },
92
+ reset() {
93
+ activeExecutionByComponent.clear();
94
+ latestWriterByStateKey.clear();
95
+ },
96
+ };
97
+ }
98
+ /**
99
+ * Owns mutable web-app interaction state for every renderer. React and direct
100
+ * DOM hosts subscribe to this controller instead of reimplementing action
101
+ * cancellation, loading/error state, and stale state-patch protection.
102
+ */
103
+ export function createUiGraphInteractionController(initialUiGraph, options = {}) {
104
+ let uiGraphId = initialUiGraph.id;
105
+ let actionComponentsById = getUiGraphActionComponentsById(initialUiGraph);
106
+ let outputComponentIds = getUiGraphOutputComponentIds(initialUiGraph);
107
+ let outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(initialUiGraph);
108
+ const initialStateOverride = options.initialState ? { ...options.initialState } : undefined;
109
+ let initialState = normalizeUiGraphDropdownState(initialUiGraph, initialStateOverride ?? getUiGraphInitialState(initialUiGraph));
110
+ let state = { ...initialState };
111
+ let actionErrors = {};
112
+ let actionProgress = {};
113
+ const collapsedOutputComponentIds = new Set();
114
+ let snapshot;
115
+ const actionController = createUiGraphActionExecutionController();
116
+ const activeActions = new Map();
117
+ const loadingActionIds = new Set();
118
+ const loadingDelayTimers = new Map();
119
+ const listeners = new Set();
120
+ const updateSnapshot = () => {
121
+ snapshot = {
122
+ actionErrors,
123
+ actionProgress,
124
+ collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),
125
+ loadingComponentIds: new Set([...activeActions].flatMap(([executionId, { execution }]) => loadingActionIds.has(executionId) ? [execution.componentId] : [])),
126
+ runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
127
+ state,
128
+ };
129
+ };
130
+ const publish = (change) => {
131
+ updateSnapshot();
132
+ for (const listener of listeners) {
133
+ listener(change);
134
+ }
135
+ };
136
+ const clearActionLoadingPresentation = (executionId) => {
137
+ const timer = loadingDelayTimers.get(executionId);
138
+ if (timer != null) {
139
+ clearTimeout(timer);
140
+ loadingDelayTimers.delete(executionId);
141
+ }
142
+ loadingActionIds.delete(executionId);
143
+ };
144
+ const delayActionLoadingPresentation = (execution) => {
145
+ loadingDelayTimers.set(execution.id, setTimeout(() => {
146
+ loadingDelayTimers.delete(execution.id);
147
+ if (!activeActions.has(execution.id) || !actionController.isCurrent(execution))
148
+ return;
149
+ loadingActionIds.add(execution.id);
150
+ publish('action');
151
+ }, ACTION_LOADING_DELAY_MS));
152
+ };
153
+ const abortMatchingActions = (predicate, notify) => {
154
+ let changed = false;
155
+ for (const [executionId, activeAction] of activeActions) {
156
+ if (!predicate(activeAction, executionId)) {
157
+ continue;
158
+ }
159
+ activeAction.abortController.abort();
160
+ activeActions.delete(executionId);
161
+ clearActionLoadingPresentation(executionId);
162
+ actionController.finish(activeAction.execution);
163
+ changed = true;
164
+ }
165
+ if (changed && notify) {
166
+ publish('action');
167
+ }
168
+ return changed;
169
+ };
170
+ const abortAllActions = (notify) => {
171
+ let changed = abortMatchingActions(() => true, false);
172
+ actionController.reset();
173
+ if (Object.keys(actionProgress).length > 0) {
174
+ actionProgress = {};
175
+ changed = true;
176
+ }
177
+ if (changed && notify) {
178
+ publish('action');
179
+ }
180
+ };
181
+ const removeActionPresentation = (componentId) => {
182
+ let changed = false;
183
+ if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
184
+ actionErrors = { ...actionErrors };
185
+ delete actionErrors[componentId];
186
+ changed = true;
187
+ }
188
+ if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
189
+ actionProgress = { ...actionProgress };
190
+ delete actionProgress[componentId];
191
+ changed = true;
192
+ }
193
+ return changed;
194
+ };
195
+ const expandOutputsForUpdatedState = (stateKeys, nextState) => {
196
+ for (const stateKey of stateKeys) {
197
+ for (const component of outputComponentsByStateKey.get(stateKey) ?? []) {
198
+ if (getUiGraphOutputRenderModel(nextState, stateKey, component.renderAs ?? 'text').hasValue) {
199
+ collapsedOutputComponentIds.delete(component.id);
200
+ }
201
+ }
202
+ }
203
+ };
204
+ updateSnapshot();
205
+ return {
206
+ abortActions() {
207
+ abortAllActions(true);
208
+ },
209
+ cancelAction(componentId) {
210
+ if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {
211
+ removeActionPresentation(componentId);
212
+ publish('action');
213
+ }
214
+ },
215
+ detachActions() {
216
+ for (const executionId of activeActions.keys()) {
217
+ clearActionLoadingPresentation(executionId);
218
+ }
219
+ activeActions.clear();
220
+ actionController.reset();
221
+ actionProgress = {};
222
+ updateSnapshot();
223
+ },
224
+ getSnapshot() {
225
+ return snapshot;
226
+ },
227
+ reset() {
228
+ abortAllActions(false);
229
+ state = { ...initialState };
230
+ actionErrors = {};
231
+ actionProgress = {};
232
+ collapsedOutputComponentIds.clear();
233
+ publish('state');
234
+ },
235
+ async runAction(component, runner) {
236
+ const execution = actionController.begin(component);
237
+ if (!execution) {
238
+ return;
239
+ }
240
+ const abortController = new AbortController();
241
+ activeActions.set(execution.id, { abortController, execution });
242
+ delayActionLoadingPresentation(execution);
243
+ removeActionPresentation(component.id);
244
+ publish('action');
245
+ try {
246
+ const result = await runner({
247
+ abortOtherActions: () => abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),
248
+ componentId: component.id,
249
+ reportProgress: (progress) => {
250
+ if (!actionController.isCurrent(execution))
251
+ return;
252
+ const normalized = normalizeGraphProgress(progress);
253
+ if (!normalized)
254
+ return;
255
+ actionProgress = { ...actionProgress, [component.id]: normalized };
256
+ publish('action');
257
+ },
258
+ signal: abortController.signal,
259
+ state: getUiGraphComponentActionState(component, state),
260
+ });
261
+ if (!actionController.isCurrent(execution)) {
262
+ return;
263
+ }
264
+ const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
265
+ if (statePatch) {
266
+ const nextState = applyUiGraphStatePatch(state, statePatch);
267
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
268
+ state = nextState;
269
+ }
270
+ }
271
+ catch (error) {
272
+ if (!abortController.signal.aborted && actionController.isCurrent(execution)) {
273
+ actionErrors = {
274
+ ...actionErrors,
275
+ [component.id]: error instanceof Error ? error.message : String(error),
276
+ };
277
+ }
278
+ }
279
+ finally {
280
+ if (activeActions.delete(execution.id)) {
281
+ clearActionLoadingPresentation(execution.id);
282
+ actionController.finish(execution);
283
+ if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
284
+ actionProgress = { ...actionProgress };
285
+ delete actionProgress[component.id];
286
+ }
287
+ publish('action');
288
+ }
289
+ }
290
+ },
291
+ setUiGraph(nextUiGraph) {
292
+ if (nextUiGraph.id !== uiGraphId) {
293
+ abortAllActions(false);
294
+ uiGraphId = nextUiGraph.id;
295
+ initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
296
+ state = { ...initialState };
297
+ actionErrors = {};
298
+ actionProgress = {};
299
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
300
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
301
+ actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
302
+ collapsedOutputComponentIds.clear();
303
+ publish('graph');
304
+ return;
305
+ }
306
+ if (!initialStateOverride) {
307
+ initialState = getUiGraphInitialState(nextUiGraph);
308
+ }
309
+ const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);
310
+ const stateChanged = normalizedState !== state;
311
+ if (stateChanged) {
312
+ state = normalizedState;
313
+ }
314
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
315
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
316
+ const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;
317
+ for (const componentId of collapsedOutputComponentIds) {
318
+ if (!outputComponentIds.has(componentId)) {
319
+ collapsedOutputComponentIds.delete(componentId);
320
+ }
321
+ }
322
+ const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
323
+ const actionComponentIds = new Set(nextActionComponentsById.keys());
324
+ const changedActionComponentIds = new Set([...nextActionComponentsById].flatMap(([componentId, component]) => {
325
+ const previousComponent = actionComponentsById.get(componentId);
326
+ return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component)
327
+ ? [componentId]
328
+ : [];
329
+ }));
330
+ let changed = collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup ||
331
+ stateChanged ||
332
+ abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId), false);
333
+ for (const componentId of changedActionComponentIds) {
334
+ changed = removeActionPresentation(componentId) || changed;
335
+ }
336
+ actionComponentsById = nextActionComponentsById;
337
+ const remainingErrors = Object.fromEntries(Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId)));
338
+ const remainingProgress = Object.fromEntries(Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId)));
339
+ if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
340
+ actionErrors = remainingErrors;
341
+ changed = true;
342
+ }
343
+ if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {
344
+ actionProgress = remainingProgress;
345
+ changed = true;
346
+ }
347
+ if (changed) {
348
+ publish('graph');
349
+ }
350
+ },
351
+ subscribe(listener) {
352
+ listeners.add(listener);
353
+ return () => listeners.delete(listener);
354
+ },
355
+ toggleOutputCollapsed(componentId) {
356
+ if (!outputComponentIds.has(componentId)) {
357
+ return;
358
+ }
359
+ if (collapsedOutputComponentIds.has(componentId)) {
360
+ collapsedOutputComponentIds.delete(componentId);
361
+ }
362
+ else {
363
+ collapsedOutputComponentIds.add(componentId);
364
+ }
365
+ publish('presentation');
366
+ },
367
+ updateState(stateKey, value) {
368
+ actionController.noteStateWrite(stateKey);
369
+ const nextState = { ...state, [stateKey]: value };
370
+ expandOutputsForUpdatedState([stateKey], nextState);
371
+ state = nextState;
372
+ publish('state');
373
+ },
374
+ updateStatePatch(statePatch) {
375
+ for (const stateKey of Object.keys(statePatch)) {
376
+ actionController.noteStateWrite(stateKey);
377
+ }
378
+ const nextState = applyUiGraphStatePatch(state, statePatch);
379
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
380
+ state = nextState;
381
+ publish('state');
382
+ },
383
+ };
384
+ }
385
+ function getUiGraphOutputComponentIds(uiGraph) {
386
+ return new Set(uiGraph.components.filter((component) => component.type === 'output').map((component) => component.id));
387
+ }
388
+ function getUiGraphOutputComponentsByStateKey(uiGraph) {
389
+ const componentsByStateKey = new Map();
390
+ for (const component of uiGraph.components) {
391
+ if (component.type !== 'output')
392
+ continue;
393
+ const components = componentsByStateKey.get(component.stateKey) ?? [];
394
+ components.push(component);
395
+ componentsByStateKey.set(component.stateKey, components);
396
+ }
397
+ return componentsByStateKey;
398
+ }
399
+ function normalizeUiGraphDropdownState(uiGraph, state) {
400
+ let normalizedState;
401
+ for (const component of uiGraph.components) {
402
+ if (component.type !== 'dropdown') {
403
+ continue;
404
+ }
405
+ const selectedValue = `${state[component.stateKey] ?? ''}`;
406
+ if (selectedValue === '' || component.items.some((item) => item.value === selectedValue)) {
407
+ continue;
408
+ }
409
+ normalizedState ??= { ...state };
410
+ normalizedState[component.stateKey] = '';
411
+ }
412
+ return normalizedState ?? state;
413
+ }
1
414
  export function getUiGraphComponentRenderModel(component, state) {
2
415
  switch (component.type) {
3
416
  case 'text':
4
417
  return { component, text: component.text, type: 'text' };
5
418
  case 'markdown':
6
419
  return { component, markdown: component.markdown, type: 'markdown' };
420
+ case 'gap':
421
+ return { component, size: component.size, type: 'gap' };
7
422
  case 'input':
8
423
  case 'textarea':
9
424
  return {
@@ -12,8 +427,26 @@ export function getUiGraphComponentRenderModel(component, state) {
12
427
  type: component.type,
13
428
  value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,
14
429
  };
430
+ case 'dropdown': {
431
+ const selectedValue = `${state[component.stateKey] ?? ''}`;
432
+ return {
433
+ component,
434
+ items: component.items,
435
+ label: getUiGraphComponentLabel(component),
436
+ type: 'dropdown',
437
+ value: component.items.some((item) => item.value === selectedValue) ? selectedValue : '',
438
+ };
439
+ }
15
440
  case 'button':
16
441
  return { component, label: component.label, type: 'button' };
442
+ case 'chat':
443
+ return {
444
+ component,
445
+ draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,
446
+ messages: getUiGraphChatMessages(component.id, state),
447
+ pins: getUiGraphChatPins(component.id, state),
448
+ type: 'chat',
449
+ };
17
450
  case 'output':
18
451
  return {
19
452
  component,
@@ -28,11 +461,17 @@ export function getUiGraphComponentLabel(component) {
28
461
  }
29
462
  export function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
30
463
  const value = state[stateKey];
31
- const hasValue = hasUiGraphStateValue(state, stateKey);
32
464
  const renderedValue = renderUiGraphOutputValue(value, renderAs);
465
+ const hasStateValue = hasUiGraphStateValue(state, stateKey);
466
+ const hasImageValue = hasStateValue && value != null && value !== '';
467
+ const imageSource = hasImageValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;
468
+ const imageErrorMessage = hasImageValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;
469
+ const hasValue = renderAs === 'image' ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;
33
470
  return {
34
471
  hasValue,
35
- ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),
472
+ ...(imageErrorMessage ? { imageErrorMessage } : {}),
473
+ ...(imageSource ? { imageSource } : {}),
474
+ ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: renderedValue } : {}),
36
475
  renderedValue,
37
476
  renderAs,
38
477
  };
@@ -46,6 +485,83 @@ export function renderUiGraphOutputValue(value, renderAs) {
46
485
  }
47
486
  return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';
48
487
  }
488
+ /**
489
+ * Splits very large JSON output into append-only DOM text chunks. Appending the
490
+ * chunks lets browser renderers show the first screenful without blocking on
491
+ * layout for every visual line in one huge escaped JSON string.
492
+ */
493
+ export function getUiGraphProgressiveJsonOutputChunks(value) {
494
+ if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {
495
+ return undefined;
496
+ }
497
+ const chunks = [];
498
+ let offset = 0;
499
+ let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;
500
+ while (offset < value.length) {
501
+ let nextOffset = Math.min(value.length, offset + chunkLength);
502
+ if (nextOffset < value.length &&
503
+ isHighSurrogate(value.charCodeAt(nextOffset - 1)) &&
504
+ isLowSurrogate(value.charCodeAt(nextOffset))) {
505
+ nextOffset += 1;
506
+ }
507
+ chunks.push(value.slice(offset, nextOffset));
508
+ offset = nextOffset;
509
+ chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;
510
+ }
511
+ return chunks;
512
+ }
513
+ function isHighSurrogate(value) {
514
+ return value >= 0xd800 && value <= 0xdbff;
515
+ }
516
+ function isLowSurrogate(value) {
517
+ return value >= 0xdc00 && value <= 0xdfff;
518
+ }
519
+ export function getUiGraphImageSource(value) {
520
+ if (typeof value !== 'string') {
521
+ return undefined;
522
+ }
523
+ const source = value.trim();
524
+ if (!source) {
525
+ return undefined;
526
+ }
527
+ const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);
528
+ if (dataUrl) {
529
+ const base64 = normalizeBase64(dataUrl[2]);
530
+ return base64 ? `data:${normalizeImageMediaType(dataUrl[1])};base64,${base64}` : undefined;
531
+ }
532
+ const base64 = normalizeBase64(source);
533
+ const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;
534
+ if (base64 && inferredMediaType) {
535
+ return `data:${inferredMediaType};base64,${base64}`;
536
+ }
537
+ if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {
538
+ return undefined;
539
+ }
540
+ try {
541
+ const protocol = new URL(source, 'https://rivet.invalid').protocol;
542
+ return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;
543
+ }
544
+ catch {
545
+ return undefined;
546
+ }
547
+ }
548
+ function normalizeBase64(value) {
549
+ const compact = value.replace(/\s/g, '');
550
+ return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;
551
+ }
552
+ function normalizeImageMediaType(mediaType) {
553
+ const normalized = mediaType.toLowerCase();
554
+ return normalized === 'image/jpg' ? 'image/jpeg' : normalized;
555
+ }
556
+ function inferBase64ImageMediaType(value) {
557
+ if (value.startsWith('iVBORw0KGgo'))
558
+ return 'image/png';
559
+ if (value.startsWith('/9j/'))
560
+ return 'image/jpeg';
561
+ if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh'))
562
+ return 'image/gif';
563
+ return undefined;
564
+ }
49
565
  export function stringifyUiGraphValue(value) {
50
566
  try {
51
567
  return JSON.stringify(value, null, 2);
@@ -0,0 +1,91 @@
1
+ import { z } from 'zod';
2
+ import { UI_GRAPH_GAP_SIZES, UI_GRAPH_OUTPUT_RENDER_MODES, } from './UiGraph.js';
3
+ const requiredString = z.string({ error: 'must be a string' });
4
+ const optionalString = z.string({ error: 'must be a string when provided' }).optional();
5
+ const componentId = z
6
+ .custom((value) => typeof value === 'string', { error: 'must be a string' })
7
+ .optional();
8
+ const uiGraphId = z
9
+ .custom((value) => typeof value === 'string', { error: 'must be a string' })
10
+ .refine((value) => value.trim().length > 0, { error: 'must be a non-empty string' });
11
+ const graphId = z
12
+ .custom((value) => typeof value === 'string', { error: 'must be a string when provided' })
13
+ .optional();
14
+ const objectOptions = { error: 'must be an object' };
15
+ const inputBindingSchema = z.object({ inputKey: requiredString, stateKey: requiredString }, objectOptions);
16
+ const outputBindingSchema = z.object({ outputKey: optionalString, stateKey: requiredString }, objectOptions);
17
+ const stateValueBindingSchema = z.object({ key: requiredString, type: z.literal('state') }, objectOptions);
18
+ const literalValueBindingSchema = z
19
+ .object({ type: z.literal('literal'), value: z.unknown() }, objectOptions)
20
+ .superRefine((binding, context) => {
21
+ if (!Object.hasOwn(binding, 'value')) {
22
+ context.addIssue({ code: 'custom', message: 'is required', path: ['value'] });
23
+ }
24
+ });
25
+ const valueBindingSchema = z.discriminatedUnion('type', [stateValueBindingSchema, literalValueBindingSchema], {
26
+ error: 'must be "state" or "literal"',
27
+ });
28
+ const inputMappingsSchema = z.array(inputBindingSchema, { error: 'must be an array' }).optional();
29
+ const runGraphActionSchema = z.object({
30
+ type: z.literal('runGraph'),
31
+ graphId,
32
+ outputKey: optionalString,
33
+ outputStateKey: optionalString,
34
+ inputMappings: inputMappingsSchema,
35
+ inputs: z.record(z.string(), valueBindingSchema, { error: 'must be an object' }).optional(),
36
+ outputs: z.array(outputBindingSchema, { error: 'must be an array' }).optional(),
37
+ }, objectOptions);
38
+ const chatRunGraphActionSchema = z.object({
39
+ type: z.literal('runGraph'),
40
+ graphId,
41
+ userInputId: optionalString,
42
+ historyInputId: optionalString,
43
+ responseOutputId: optionalString,
44
+ inputMappings: inputMappingsSchema,
45
+ }, objectOptions);
46
+ const inputComponentFields = {
47
+ id: componentId,
48
+ label: requiredString,
49
+ stateKey: requiredString,
50
+ placeholder: optionalString,
51
+ defaultValue: optionalString,
52
+ };
53
+ export const UI_GRAPH_COMPONENT_SCHEMA = z.discriminatedUnion('type', [
54
+ z.object({ id: componentId, type: z.literal('text'), text: requiredString }, objectOptions),
55
+ z.object({ id: componentId, type: z.literal('markdown'), markdown: requiredString }, objectOptions),
56
+ z.object({
57
+ id: componentId,
58
+ type: z.literal('gap'),
59
+ size: z.enum(UI_GRAPH_GAP_SIZES, { error: `must be one of: ${UI_GRAPH_GAP_SIZES.join(', ')}` }),
60
+ }, objectOptions),
61
+ z.object({ type: z.literal('input'), ...inputComponentFields }, objectOptions),
62
+ z.object({ type: z.literal('textarea'), ...inputComponentFields }, objectOptions),
63
+ z.object({
64
+ id: componentId,
65
+ type: z.literal('dropdown'),
66
+ label: requiredString,
67
+ stateKey: requiredString,
68
+ items: z.array(z.object({ label: requiredString, value: requiredString }, objectOptions), {
69
+ error: 'must be an array',
70
+ }),
71
+ }, objectOptions),
72
+ z.object({ id: componentId, type: z.literal('button'), label: requiredString, action: runGraphActionSchema }, objectOptions),
73
+ z.object({ id: componentId, type: z.literal('chat'), placeholder: optionalString, action: chatRunGraphActionSchema }, objectOptions),
74
+ z.object({
75
+ id: componentId,
76
+ type: z.literal('output'),
77
+ label: optionalString,
78
+ stateKey: requiredString,
79
+ renderAs: z
80
+ .enum(UI_GRAPH_OUTPUT_RENDER_MODES, {
81
+ error: `must be one of: ${UI_GRAPH_OUTPUT_RENDER_MODES.join(', ')}`,
82
+ })
83
+ .optional(),
84
+ }, objectOptions),
85
+ ], { error: 'must have a supported string type' });
86
+ export const UI_GRAPH_ENVELOPE_SCHEMA = z.object({
87
+ id: uiGraphId,
88
+ name: requiredString,
89
+ description: optionalString,
90
+ components: z.array(z.unknown(), { error: 'must be an array' }),
91
+ }, objectOptions);
@@ -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
+ }
@@ -0,0 +1 @@
1
+ export {};