@valerypopoff/rivet2-core 2.1.4 → 2.1.6

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 (107) hide show
  1. package/dist/cjs/bundle.cjs +6651 -1022
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +733 -19
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +6 -1
  6. package/dist/esm/exports.js +7 -0
  7. package/dist/esm/integrations/KnowledgeStore.js +1 -0
  8. package/dist/esm/integrations/KnowledgeStoreProvider.js +292 -0
  9. package/dist/esm/integrations/KnowledgeStoreValidation.js +428 -0
  10. package/dist/esm/integrations/ManagedKnowledgeStore.js +539 -0
  11. package/dist/esm/model/DataValue.js +22 -2
  12. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  13. package/dist/esm/model/GraphProcessor.js +1141 -82
  14. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  15. package/dist/esm/model/Nodes.js +27 -0
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  17. package/dist/esm/model/RecordingPlayer.js +9 -0
  18. package/dist/esm/model/StoredValueStore.js +226 -0
  19. package/dist/esm/model/SubprocessorBridge.js +50 -19
  20. package/dist/esm/model/ToolCallContinuation.js +1 -0
  21. package/dist/esm/model/UiGraph.js +52 -2
  22. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  23. package/dist/esm/model/UiGraphBrowserRuntime.js +444 -0
  24. package/dist/esm/model/UiGraphNormalization.js +35 -185
  25. package/dist/esm/model/UiGraphRendererStyles.js +878 -78
  26. package/dist/esm/model/UiGraphRuntimeModel.js +255 -15
  27. package/dist/esm/model/UiGraphSchema.js +91 -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/openAIChatRequest.js +8 -2
  31. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
  33. package/dist/esm/model/chat-v2/index.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
  35. package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
  36. package/dist/esm/model/chat-v2/toolContinuation.js +45 -8
  37. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  38. package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
  43. package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  45. package/dist/esm/model/nodes/MatchNode.js +7 -7
  46. package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
  47. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  48. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  49. package/dist/esm/model/nodes/StoredValueNodeUtils.js +57 -0
  50. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
  51. package/dist/esm/model/nodes/ToolNode.js +14 -0
  52. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  53. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
  54. package/dist/esm/plugins/pinecone/plugin.js +32 -0
  55. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  56. package/dist/esm/utils/coerceType.js +27 -2
  57. package/dist/esm/utils/getPluginConfig.js +12 -6
  58. package/dist/esm/utils/serialization/serialization.js +4 -1
  59. package/dist/esm/utils/serialization/serializationUtils.js +59 -1
  60. package/dist/esm/webAppRuntime.js +3 -3
  61. package/dist/types/api/createProcessor.d.ts +6 -0
  62. package/dist/types/exports.d.ts +7 -0
  63. package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
  64. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
  65. package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
  66. package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
  67. package/dist/types/model/DataValue.d.ts +10 -3
  68. package/dist/types/model/EditorDefinition.d.ts +9 -2
  69. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  70. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  71. package/dist/types/model/GraphProcessor.d.ts +21 -2
  72. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  73. package/dist/types/model/Nodes.d.ts +11 -2
  74. package/dist/types/model/ProcessContext.d.ts +18 -0
  75. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  76. package/dist/types/model/Project.d.ts +11 -0
  77. package/dist/types/model/StoredValueStore.d.ts +55 -0
  78. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  79. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  80. package/dist/types/model/UiGraph.d.ts +24 -1
  81. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +75 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  84. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  85. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  86. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  87. package/dist/types/model/chat-v2/index.d.ts +1 -0
  88. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
  89. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  90. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  91. package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
  92. package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
  93. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  94. package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
  95. package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
  96. package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
  97. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  98. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  99. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  100. package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
  101. package/dist/types/model/nodes/ToolNode.d.ts +2 -0
  102. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  103. package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
  104. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  105. package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
  106. package/dist/types/webAppRuntime.d.ts +5 -4
  107. package/package.json +1 -1
@@ -1,9 +1,48 @@
1
- import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphComponentActionOutputStateKeys, getUiGraphComponentActionState, getUiGraphInitialState, } from './UiGraph.js';
1
+ import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphChatMessagesStateKey, getUiGraphChatPins, getUiGraphComponentActionOutputStateKeys, getUiGraphComponentActionState, getUiGraphInitialState, } from './UiGraph.js';
2
2
  import { normalizeGraphProgress } from './GraphProgress.js';
3
3
  const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\s\S]+)$/i;
4
4
  const IMAGE_URL_PATTERN = /^(?:https?:\/\/|blob:|\/\/|\/|\.\.?\/)/i;
5
5
  const RELATIVE_IMAGE_PATH_PATTERN = /\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;
6
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
+ }
7
46
  /**
8
47
  * Coordinates independent web-app actions without allowing older completions to
9
48
  * clear newer loading states or overwrite newer writes to the same UI state key.
@@ -63,17 +102,27 @@ export function createUiGraphActionExecutionController() {
63
102
  */
64
103
  export function createUiGraphInteractionController(initialUiGraph, options = {}) {
65
104
  let uiGraphId = initialUiGraph.id;
66
- let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);
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 };
67
111
  let actionErrors = {};
68
112
  let actionProgress = {};
113
+ const collapsedOutputComponentIds = new Set();
69
114
  let snapshot;
70
115
  const actionController = createUiGraphActionExecutionController();
71
116
  const activeActions = new Map();
117
+ const loadingActionIds = new Set();
118
+ const loadingDelayTimers = new Map();
72
119
  const listeners = new Set();
73
120
  const updateSnapshot = () => {
74
121
  snapshot = {
75
122
  actionErrors,
76
123
  actionProgress,
124
+ collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),
125
+ loadingComponentIds: new Set([...activeActions].flatMap(([executionId, { execution }]) => loadingActionIds.has(executionId) ? [execution.componentId] : [])),
77
126
  runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),
78
127
  state,
79
128
  };
@@ -84,6 +133,23 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
84
133
  listener(change);
85
134
  }
86
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
+ };
87
153
  const abortMatchingActions = (predicate, notify) => {
88
154
  let changed = false;
89
155
  for (const [executionId, activeAction] of activeActions) {
@@ -92,6 +158,7 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
92
158
  }
93
159
  activeAction.abortController.abort();
94
160
  activeActions.delete(executionId);
161
+ clearActionLoadingPresentation(executionId);
95
162
  actionController.finish(activeAction.execution);
96
163
  changed = true;
97
164
  }
@@ -112,15 +179,52 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
112
179
  }
113
180
  };
114
181
  const removeActionPresentation = (componentId) => {
182
+ let changed = false;
115
183
  if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {
116
184
  actionErrors = { ...actionErrors };
117
185
  delete actionErrors[componentId];
186
+ changed = true;
118
187
  }
119
188
  if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {
120
189
  actionProgress = { ...actionProgress };
121
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
+ }
122
202
  }
123
203
  };
204
+ const stampChatResponseAtBrowserReceipt = (component, statePatch) => {
205
+ if (component.type !== 'chat' || !statePatch) {
206
+ return statePatch;
207
+ }
208
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
209
+ const messages = statePatch[messagesStateKey];
210
+ if (!Array.isArray(messages) || messages.length === 0) {
211
+ return statePatch;
212
+ }
213
+ const lastMessage = messages[messages.length - 1];
214
+ if (!lastMessage ||
215
+ typeof lastMessage !== 'object' ||
216
+ lastMessage.role !== 'assistant' ||
217
+ typeof lastMessage.content !== 'string') {
218
+ return statePatch;
219
+ }
220
+ return {
221
+ ...statePatch,
222
+ [messagesStateKey]: [
223
+ ...messages.slice(0, -1),
224
+ { ...lastMessage, timestamp: new Date().toISOString() },
225
+ ],
226
+ };
227
+ };
124
228
  updateSnapshot();
125
229
  return {
126
230
  abortActions() {
@@ -133,6 +237,9 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
133
237
  }
134
238
  },
135
239
  detachActions() {
240
+ for (const executionId of activeActions.keys()) {
241
+ clearActionLoadingPresentation(executionId);
242
+ }
136
243
  activeActions.clear();
137
244
  actionController.reset();
138
245
  actionProgress = {};
@@ -141,6 +248,14 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
141
248
  getSnapshot() {
142
249
  return snapshot;
143
250
  },
251
+ reset() {
252
+ abortAllActions(false);
253
+ state = { ...initialState };
254
+ actionErrors = {};
255
+ actionProgress = {};
256
+ collapsedOutputComponentIds.clear();
257
+ publish('state');
258
+ },
144
259
  async runAction(component, runner) {
145
260
  const execution = actionController.begin(component);
146
261
  if (!execution) {
@@ -148,6 +263,7 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
148
263
  }
149
264
  const abortController = new AbortController();
150
265
  activeActions.set(execution.id, { abortController, execution });
266
+ delayActionLoadingPresentation(execution);
151
267
  removeActionPresentation(component.id);
152
268
  publish('action');
153
269
  try {
@@ -169,9 +285,11 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
169
285
  if (!actionController.isCurrent(execution)) {
170
286
  return;
171
287
  }
172
- const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
288
+ const statePatch = actionController.resolveStatePatch(execution, stampChatResponseAtBrowserReceipt(component, result.statePatch));
173
289
  if (statePatch) {
174
- state = applyUiGraphStatePatch(state, statePatch);
290
+ const nextState = applyUiGraphStatePatch(state, statePatch);
291
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
292
+ state = nextState;
175
293
  }
176
294
  }
177
295
  catch (error) {
@@ -184,6 +302,7 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
184
302
  }
185
303
  finally {
186
304
  if (activeActions.delete(execution.id)) {
305
+ clearActionLoadingPresentation(execution.id);
187
306
  actionController.finish(execution);
188
307
  if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
189
308
  actionProgress = { ...actionProgress };
@@ -197,16 +316,48 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
197
316
  if (nextUiGraph.id !== uiGraphId) {
198
317
  abortAllActions(false);
199
318
  uiGraphId = nextUiGraph.id;
200
- state = getUiGraphInitialState(nextUiGraph);
319
+ initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
320
+ state = { ...initialState };
201
321
  actionErrors = {};
202
322
  actionProgress = {};
323
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
324
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
325
+ actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
326
+ collapsedOutputComponentIds.clear();
203
327
  publish('graph');
204
328
  return;
205
329
  }
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);
330
+ if (!initialStateOverride) {
331
+ initialState = getUiGraphInitialState(nextUiGraph);
332
+ }
333
+ const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);
334
+ const stateChanged = normalizedState !== state;
335
+ if (stateChanged) {
336
+ state = normalizedState;
337
+ }
338
+ outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
339
+ outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
340
+ const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;
341
+ for (const componentId of collapsedOutputComponentIds) {
342
+ if (!outputComponentIds.has(componentId)) {
343
+ collapsedOutputComponentIds.delete(componentId);
344
+ }
345
+ }
346
+ const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
347
+ const actionComponentIds = new Set(nextActionComponentsById.keys());
348
+ const changedActionComponentIds = new Set([...nextActionComponentsById].flatMap(([componentId, component]) => {
349
+ const previousComponent = actionComponentsById.get(componentId);
350
+ return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component)
351
+ ? [componentId]
352
+ : [];
353
+ }));
354
+ let changed = collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup ||
355
+ stateChanged ||
356
+ abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId), false);
357
+ for (const componentId of changedActionComponentIds) {
358
+ changed = removeActionPresentation(componentId) || changed;
359
+ }
360
+ actionComponentsById = nextActionComponentsById;
210
361
  const remainingErrors = Object.fromEntries(Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId)));
211
362
  const remainingProgress = Object.fromEntries(Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId)));
212
363
  if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
@@ -225,20 +376,65 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
225
376
  listeners.add(listener);
226
377
  return () => listeners.delete(listener);
227
378
  },
379
+ toggleOutputCollapsed(componentId) {
380
+ if (!outputComponentIds.has(componentId)) {
381
+ return;
382
+ }
383
+ if (collapsedOutputComponentIds.has(componentId)) {
384
+ collapsedOutputComponentIds.delete(componentId);
385
+ }
386
+ else {
387
+ collapsedOutputComponentIds.add(componentId);
388
+ }
389
+ publish('presentation');
390
+ },
228
391
  updateState(stateKey, value) {
229
392
  actionController.noteStateWrite(stateKey);
230
- state = { ...state, [stateKey]: value };
393
+ const nextState = { ...state, [stateKey]: value };
394
+ expandOutputsForUpdatedState([stateKey], nextState);
395
+ state = nextState;
231
396
  publish('state');
232
397
  },
233
398
  updateStatePatch(statePatch) {
234
399
  for (const stateKey of Object.keys(statePatch)) {
235
400
  actionController.noteStateWrite(stateKey);
236
401
  }
237
- state = applyUiGraphStatePatch(state, statePatch);
402
+ const nextState = applyUiGraphStatePatch(state, statePatch);
403
+ expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
404
+ state = nextState;
238
405
  publish('state');
239
406
  },
240
407
  };
241
408
  }
409
+ function getUiGraphOutputComponentIds(uiGraph) {
410
+ return new Set(uiGraph.components.filter((component) => component.type === 'output').map((component) => component.id));
411
+ }
412
+ function getUiGraphOutputComponentsByStateKey(uiGraph) {
413
+ const componentsByStateKey = new Map();
414
+ for (const component of uiGraph.components) {
415
+ if (component.type !== 'output')
416
+ continue;
417
+ const components = componentsByStateKey.get(component.stateKey) ?? [];
418
+ components.push(component);
419
+ componentsByStateKey.set(component.stateKey, components);
420
+ }
421
+ return componentsByStateKey;
422
+ }
423
+ function normalizeUiGraphDropdownState(uiGraph, state) {
424
+ let normalizedState;
425
+ for (const component of uiGraph.components) {
426
+ if (component.type !== 'dropdown') {
427
+ continue;
428
+ }
429
+ const selectedValue = `${state[component.stateKey] ?? ''}`;
430
+ if (selectedValue === '' || component.items.some((item) => item.value === selectedValue)) {
431
+ continue;
432
+ }
433
+ normalizedState ??= { ...state };
434
+ normalizedState[component.stateKey] = '';
435
+ }
436
+ return normalizedState ?? state;
437
+ }
242
438
  export function getUiGraphComponentRenderModel(component, state) {
243
439
  switch (component.type) {
244
440
  case 'text':
@@ -255,6 +451,16 @@ export function getUiGraphComponentRenderModel(component, state) {
255
451
  type: component.type,
256
452
  value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,
257
453
  };
454
+ case 'dropdown': {
455
+ const selectedValue = `${state[component.stateKey] ?? ''}`;
456
+ return {
457
+ component,
458
+ items: component.items,
459
+ label: getUiGraphComponentLabel(component),
460
+ type: 'dropdown',
461
+ value: component.items.some((item) => item.value === selectedValue) ? selectedValue : '',
462
+ };
463
+ }
258
464
  case 'button':
259
465
  return { component, label: component.label, type: 'button' };
260
466
  case 'chat':
@@ -262,6 +468,7 @@ export function getUiGraphComponentRenderModel(component, state) {
262
468
  component,
263
469
  draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,
264
470
  messages: getUiGraphChatMessages(component.id, state),
471
+ pins: getUiGraphChatPins(component.id, state),
265
472
  type: 'chat',
266
473
  };
267
474
  case 'output':
@@ -278,15 +485,17 @@ export function getUiGraphComponentLabel(component) {
278
485
  }
279
486
  export function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
280
487
  const value = state[stateKey];
281
- const hasValue = hasUiGraphStateValue(state, stateKey);
282
488
  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;
489
+ const hasStateValue = hasUiGraphStateValue(state, stateKey);
490
+ const hasImageValue = hasStateValue && value != null && value !== '';
491
+ const imageSource = hasImageValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;
492
+ const imageErrorMessage = hasImageValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;
493
+ const hasValue = renderAs === 'image' ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;
285
494
  return {
286
495
  hasValue,
287
496
  ...(imageErrorMessage ? { imageErrorMessage } : {}),
288
497
  ...(imageSource ? { imageSource } : {}),
289
- ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),
498
+ ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: renderedValue } : {}),
290
499
  renderedValue,
291
500
  renderAs,
292
501
  };
@@ -300,6 +509,37 @@ export function renderUiGraphOutputValue(value, renderAs) {
300
509
  }
301
510
  return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';
302
511
  }
512
+ /**
513
+ * Splits very large JSON output into append-only DOM text chunks. Appending the
514
+ * chunks lets browser renderers show the first screenful without blocking on
515
+ * layout for every visual line in one huge escaped JSON string.
516
+ */
517
+ export function getUiGraphProgressiveJsonOutputChunks(value) {
518
+ if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {
519
+ return undefined;
520
+ }
521
+ const chunks = [];
522
+ let offset = 0;
523
+ let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;
524
+ while (offset < value.length) {
525
+ let nextOffset = Math.min(value.length, offset + chunkLength);
526
+ if (nextOffset < value.length &&
527
+ isHighSurrogate(value.charCodeAt(nextOffset - 1)) &&
528
+ isLowSurrogate(value.charCodeAt(nextOffset))) {
529
+ nextOffset += 1;
530
+ }
531
+ chunks.push(value.slice(offset, nextOffset));
532
+ offset = nextOffset;
533
+ chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;
534
+ }
535
+ return chunks;
536
+ }
537
+ function isHighSurrogate(value) {
538
+ return value >= 0xd800 && value <= 0xdbff;
539
+ }
540
+ function isLowSurrogate(value) {
541
+ return value >= 0xdc00 && value <= 0xdfff;
542
+ }
303
543
  export function getUiGraphImageSource(value) {
304
544
  if (typeof value !== 'string') {
305
545
  return undefined;
@@ -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 @@
1
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';
2
- import { getScalarTypeOf, isArrayDataValue } from '../DataValue.js';
2
+ import { getScalarTypeOf, isArrayDataValue, } from '../DataValue.js';
3
3
  export function coercePromptToChatMessages(prompt, options = {}) {
4
4
  if (!prompt) {
5
5
  if (options.requirePrompt) {
@@ -32,16 +32,12 @@ export function coercePromptToChatMessages(prompt, options = {}) {
32
32
  return [coercedMessage];
33
33
  }
34
34
  const coercedString = coerceTypeOptional(value, 'string');
35
- return coercedString != null ? [{ type: 'user', message: coerceType(value, 'string') }] : [];
35
+ return coercedString != null ? [{ type: 'user', message: coercedString }] : [];
36
36
  }
37
37
  export function prependSystemPrompt(messages, systemPrompt) {
38
- if (!systemPrompt) {
38
+ const systemMessage = coerceTypeOptional(systemPrompt, 'string');
39
+ if (!systemMessage) {
39
40
  return messages;
40
41
  }
41
- const systemMessage = coerceType(systemPrompt, 'string');
42
- const nextMessages = [...messages];
43
- if (nextMessages.length > 0 && nextMessages[0].type === 'system') {
44
- nextMessages.splice(0, 1);
45
- }
46
- return [{ type: 'system', message: systemMessage }, ...nextMessages];
42
+ return [{ type: 'system', message: systemMessage }, ...messages];
47
43
  }
@@ -53,7 +53,8 @@ export function resolveAdditionalHeaders(data, inputs) {
53
53
  return acc;
54
54
  }, {});
55
55
  return data.useHeadersInput
56
- ? coerceTypeOptional(inputs['headers'], 'object') ?? headersFromData
56
+ ? coerceTypeOptional(inputs['headers'], 'object') ??
57
+ headersFromData
57
58
  : headersFromData;
58
59
  }
59
60
  export function resolveAdditionalParameters(data, inputs) {
@@ -69,7 +70,12 @@ export function resolveAdditionalParameters(data, inputs) {
69
70
  export function resolveChatTools(inputs) {
70
71
  const functions = coerceTypeOptional(inputs['functions'], 'gpt-function[]');
71
72
  return (functions ?? []).map((fn) => ({
72
- function: fn,
73
+ function: {
74
+ name: fn.name,
75
+ description: fn.description,
76
+ parameters: fn.parameters,
77
+ strict: fn.strict,
78
+ },
73
79
  type: 'function',
74
80
  }));
75
81
  }
@@ -58,6 +58,39 @@ function parseResponseBodyMessage(responseBody) {
58
58
  return compact(responseBody);
59
59
  }
60
60
  }
61
+ function getProviderMessage(error, seen = new Set()) {
62
+ if (!isRecord(error) || seen.has(error)) {
63
+ return undefined;
64
+ }
65
+ seen.add(error);
66
+ const responseBodyMessage = typeof error.responseBody === 'string' ? parseResponseBodyMessage(error.responseBody) : undefined;
67
+ if (responseBodyMessage) {
68
+ return responseBodyMessage;
69
+ }
70
+ const response = error.response;
71
+ if (isRecord(response)) {
72
+ const nestedResponseBody = typeof response.responseBody === 'string'
73
+ ? response.responseBody
74
+ : typeof response.body === 'string'
75
+ ? response.body
76
+ : undefined;
77
+ const nestedResponseMessage = parseResponseBodyMessage(nestedResponseBody) ??
78
+ findProviderMessage(response.data) ??
79
+ findProviderMessage(response);
80
+ if (nestedResponseMessage) {
81
+ return nestedResponseMessage;
82
+ }
83
+ }
84
+ const dataMessage = findProviderMessage(error.data);
85
+ if (dataMessage) {
86
+ return dataMessage;
87
+ }
88
+ const causeMessage = getProviderMessage(error.cause, seen);
89
+ if (causeMessage) {
90
+ return causeMessage;
91
+ }
92
+ return findProviderMessage(error);
93
+ }
61
94
  function formatEndpoint(url) {
62
95
  try {
63
96
  const parsed = new URL(url);
@@ -180,7 +213,7 @@ function formatProviderFetchError(error, context) {
180
213
  function formatApiCallError(error, context) {
181
214
  const statusCode = getChatV2ProviderErrorStatusCode(error);
182
215
  const statusLabel = statusCode == null ? 'request failed' : `${statusCode} ${STATUS_TEXT[statusCode] ?? 'HTTP error'}`;
183
- const providerMessage = findProviderMessage(error.data) ?? parseResponseBodyMessage(error.responseBody);
216
+ const providerMessage = getProviderMessage(error);
184
217
  const lines = [
185
218
  `LLM provider request failed (${statusLabel}).`,
186
219
  `Provider: ${getChatV2ProviderLabel(context.provider)}`,
@@ -189,10 +222,10 @@ function formatApiCallError(error, context) {
189
222
  if (error.url) {
190
223
  lines.push(`Endpoint: ${formatEndpoint(error.url)}`);
191
224
  }
192
- lines.push(getApiCallRecommendation(statusCode, context));
193
- if (providerMessage && providerMessage !== compact(error.message)) {
225
+ if (providerMessage) {
194
226
  lines.push(`Provider message: ${providerMessage}`);
195
227
  }
228
+ lines.push(getApiCallRecommendation(statusCode, context));
196
229
  return lines.join('\n');
197
230
  }
198
231
  function formatKnownSdkError(error, context) {
@@ -3,6 +3,7 @@ import { createOpenAI } from '@ai-sdk/openai';
3
3
  import { coerceTypeOptional } from '../../utils/coerceType.js';
4
4
  import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
5
5
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
6
+ import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
6
7
  export function resolveLLMChatV2Headers(data, inputs) {
7
8
  const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
8
9
  ? coerceTypeOptional(inputs['headers'], 'object')
@@ -123,14 +124,13 @@ function resolveProviderOptions(data, inputs) {
123
124
  return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
124
125
  }
125
126
  export function resolveLLMChatV2RuntimeProviderOptions(data, inputs) {
126
- const providerOptions = resolveProviderOptions(data, inputs) ?? {};
127
- if (data.provider === 'openai' && data.useToolCalling) {
128
- providerOptions.openai = {
129
- ...(providerOptions.openai ?? {}),
130
- parallelToolCalls: !!data.parallelToolCalls,
131
- };
132
- }
133
- return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
127
+ const providerOptions = applyLLMChatV2ParallelToolCallProviderOptions({
128
+ provider: data.provider,
129
+ useToolCalling: data.useToolCalling,
130
+ parallelToolCalls: data.parallelToolCalls,
131
+ providerOptions: resolveProviderOptions(data, inputs),
132
+ });
133
+ return providerOptions != null && Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
134
134
  }
135
135
  export function resolveLLMChatV2ToolChoice(data) {
136
136
  if (!data.useToolCalling || !data.toolChoice) {
@@ -10,3 +10,4 @@ export * from './messageConverter.js';
10
10
  export * from './modelRegistry.js';
11
11
  export * from './providerOptions.js';
12
12
  export * from './toolConverter.js';
13
+ export * from './toolContinuationConnection.js';