@valerypopoff/rivet2-core 2.1.4 → 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.
- package/dist/cjs/bundle.cjs +3733 -969
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +605 -16
- package/dist/cjs/webAppRuntime.cjs.map +3 -3
- package/dist/esm/api/createProcessor.js +5 -1
- package/dist/esm/exports.js +3 -0
- package/dist/esm/model/GraphBoundaryEffects.js +13 -0
- package/dist/esm/model/GraphProcessor.js +1127 -82
- package/dist/esm/model/ManagedAsyncBranches.js +28 -0
- package/dist/esm/model/Nodes.js +9 -0
- package/dist/esm/model/ProcessContextBuilder.js +2 -1
- package/dist/esm/model/RecordingPlayer.js +9 -0
- package/dist/esm/model/StoredValueStore.js +226 -0
- package/dist/esm/model/SubprocessorBridge.js +50 -19
- package/dist/esm/model/ToolCallContinuation.js +1 -0
- package/dist/esm/model/UiGraph.js +50 -0
- package/dist/esm/model/UiGraphActionProtocol.js +10 -1
- package/dist/esm/model/UiGraphBrowserRuntime.js +333 -0
- package/dist/esm/model/UiGraphNormalization.js +35 -185
- package/dist/esm/model/UiGraphRendererStyles.js +772 -74
- package/dist/esm/model/UiGraphRuntimeModel.js +230 -14
- package/dist/esm/model/UiGraphSchema.js +91 -0
- package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
- package/dist/esm/model/chat/chatMessages.js +5 -9
- package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
- package/dist/esm/model/chat-v2/index.js +1 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
- package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
- package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
- package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
- package/dist/esm/model/nodes/MatchNode.js +7 -7
- package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
- package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
- package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
- package/dist/esm/recording/ExecutionRecorder.js +1 -0
- package/dist/esm/utils/coerceType.js +3 -0
- package/dist/esm/webAppRuntime.js +3 -3
- package/dist/types/api/createProcessor.d.ts +4 -0
- package/dist/types/exports.d.ts +3 -0
- package/dist/types/model/EditorDefinition.d.ts +2 -1
- package/dist/types/model/ExecutorProtocol.d.ts +12 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
- package/dist/types/model/GraphProcessor.d.ts +19 -2
- package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
- package/dist/types/model/Nodes.d.ts +5 -2
- package/dist/types/model/ProcessContext.d.ts +15 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
- package/dist/types/model/StoredValueStore.d.ts +55 -0
- package/dist/types/model/SubprocessorBridge.d.ts +4 -2
- package/dist/types/model/ToolCallContinuation.d.ts +13 -0
- package/dist/types/model/UiGraph.d.ts +21 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +51 -0
- package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
- package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
- package/dist/types/model/UiGraphSchema.d.ts +113 -0
- package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
- package/dist/types/model/chat-v2/index.d.ts +1 -0
- package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
- package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
- package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
- package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
- package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
- package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
- package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
- package/dist/types/recording/RecordedEvents.d.ts +5 -0
- package/dist/types/webAppRuntime.d.ts +4 -4
- package/package.json +1 -1
|
@@ -1,9 +1,48 @@
|
|
|
1
|
-
import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphComponentActionOutputStateKeys, getUiGraphComponentActionState, getUiGraphInitialState, } from './UiGraph.js';
|
|
1
|
+
import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, 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
|
|
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,13 +179,26 @@ 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
|
};
|
|
124
204
|
updateSnapshot();
|
|
@@ -133,6 +213,9 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
133
213
|
}
|
|
134
214
|
},
|
|
135
215
|
detachActions() {
|
|
216
|
+
for (const executionId of activeActions.keys()) {
|
|
217
|
+
clearActionLoadingPresentation(executionId);
|
|
218
|
+
}
|
|
136
219
|
activeActions.clear();
|
|
137
220
|
actionController.reset();
|
|
138
221
|
actionProgress = {};
|
|
@@ -141,6 +224,14 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
141
224
|
getSnapshot() {
|
|
142
225
|
return snapshot;
|
|
143
226
|
},
|
|
227
|
+
reset() {
|
|
228
|
+
abortAllActions(false);
|
|
229
|
+
state = { ...initialState };
|
|
230
|
+
actionErrors = {};
|
|
231
|
+
actionProgress = {};
|
|
232
|
+
collapsedOutputComponentIds.clear();
|
|
233
|
+
publish('state');
|
|
234
|
+
},
|
|
144
235
|
async runAction(component, runner) {
|
|
145
236
|
const execution = actionController.begin(component);
|
|
146
237
|
if (!execution) {
|
|
@@ -148,6 +239,7 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
148
239
|
}
|
|
149
240
|
const abortController = new AbortController();
|
|
150
241
|
activeActions.set(execution.id, { abortController, execution });
|
|
242
|
+
delayActionLoadingPresentation(execution);
|
|
151
243
|
removeActionPresentation(component.id);
|
|
152
244
|
publish('action');
|
|
153
245
|
try {
|
|
@@ -171,7 +263,9 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
171
263
|
}
|
|
172
264
|
const statePatch = actionController.resolveStatePatch(execution, result.statePatch);
|
|
173
265
|
if (statePatch) {
|
|
174
|
-
|
|
266
|
+
const nextState = applyUiGraphStatePatch(state, statePatch);
|
|
267
|
+
expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
|
|
268
|
+
state = nextState;
|
|
175
269
|
}
|
|
176
270
|
}
|
|
177
271
|
catch (error) {
|
|
@@ -184,6 +278,7 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
184
278
|
}
|
|
185
279
|
finally {
|
|
186
280
|
if (activeActions.delete(execution.id)) {
|
|
281
|
+
clearActionLoadingPresentation(execution.id);
|
|
187
282
|
actionController.finish(execution);
|
|
188
283
|
if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {
|
|
189
284
|
actionProgress = { ...actionProgress };
|
|
@@ -197,16 +292,48 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
197
292
|
if (nextUiGraph.id !== uiGraphId) {
|
|
198
293
|
abortAllActions(false);
|
|
199
294
|
uiGraphId = nextUiGraph.id;
|
|
200
|
-
|
|
295
|
+
initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);
|
|
296
|
+
state = { ...initialState };
|
|
201
297
|
actionErrors = {};
|
|
202
298
|
actionProgress = {};
|
|
299
|
+
outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);
|
|
300
|
+
outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);
|
|
301
|
+
actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);
|
|
302
|
+
collapsedOutputComponentIds.clear();
|
|
203
303
|
publish('graph');
|
|
204
304
|
return;
|
|
205
305
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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;
|
|
210
337
|
const remainingErrors = Object.fromEntries(Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId)));
|
|
211
338
|
const remainingProgress = Object.fromEntries(Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId)));
|
|
212
339
|
if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {
|
|
@@ -225,20 +352,65 @@ export function createUiGraphInteractionController(initialUiGraph, options = {})
|
|
|
225
352
|
listeners.add(listener);
|
|
226
353
|
return () => listeners.delete(listener);
|
|
227
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
|
+
},
|
|
228
367
|
updateState(stateKey, value) {
|
|
229
368
|
actionController.noteStateWrite(stateKey);
|
|
230
|
-
|
|
369
|
+
const nextState = { ...state, [stateKey]: value };
|
|
370
|
+
expandOutputsForUpdatedState([stateKey], nextState);
|
|
371
|
+
state = nextState;
|
|
231
372
|
publish('state');
|
|
232
373
|
},
|
|
233
374
|
updateStatePatch(statePatch) {
|
|
234
375
|
for (const stateKey of Object.keys(statePatch)) {
|
|
235
376
|
actionController.noteStateWrite(stateKey);
|
|
236
377
|
}
|
|
237
|
-
|
|
378
|
+
const nextState = applyUiGraphStatePatch(state, statePatch);
|
|
379
|
+
expandOutputsForUpdatedState(Object.keys(statePatch), nextState);
|
|
380
|
+
state = nextState;
|
|
238
381
|
publish('state');
|
|
239
382
|
},
|
|
240
383
|
};
|
|
241
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
|
+
}
|
|
242
414
|
export function getUiGraphComponentRenderModel(component, state) {
|
|
243
415
|
switch (component.type) {
|
|
244
416
|
case 'text':
|
|
@@ -255,6 +427,16 @@ export function getUiGraphComponentRenderModel(component, state) {
|
|
|
255
427
|
type: component.type,
|
|
256
428
|
value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,
|
|
257
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
|
+
}
|
|
258
440
|
case 'button':
|
|
259
441
|
return { component, label: component.label, type: 'button' };
|
|
260
442
|
case 'chat':
|
|
@@ -262,6 +444,7 @@ export function getUiGraphComponentRenderModel(component, state) {
|
|
|
262
444
|
component,
|
|
263
445
|
draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,
|
|
264
446
|
messages: getUiGraphChatMessages(component.id, state),
|
|
447
|
+
pins: getUiGraphChatPins(component.id, state),
|
|
265
448
|
type: 'chat',
|
|
266
449
|
};
|
|
267
450
|
case 'output':
|
|
@@ -278,15 +461,17 @@ export function getUiGraphComponentLabel(component) {
|
|
|
278
461
|
}
|
|
279
462
|
export function getUiGraphOutputRenderModel(state, stateKey, renderAs) {
|
|
280
463
|
const value = state[stateKey];
|
|
281
|
-
const hasValue = hasUiGraphStateValue(state, stateKey);
|
|
282
464
|
const renderedValue = renderUiGraphOutputValue(value, renderAs);
|
|
283
|
-
const
|
|
284
|
-
const
|
|
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;
|
|
285
470
|
return {
|
|
286
471
|
hasValue,
|
|
287
472
|
...(imageErrorMessage ? { imageErrorMessage } : {}),
|
|
288
473
|
...(imageSource ? { imageSource } : {}),
|
|
289
|
-
...(hasValue && renderAs === 'json' ? { jsonDownloadValue:
|
|
474
|
+
...(hasValue && renderAs === 'json' ? { jsonDownloadValue: renderedValue } : {}),
|
|
290
475
|
renderedValue,
|
|
291
476
|
renderAs,
|
|
292
477
|
};
|
|
@@ -300,6 +485,37 @@ export function renderUiGraphOutputValue(value, renderAs) {
|
|
|
300
485
|
}
|
|
301
486
|
return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';
|
|
302
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
|
+
}
|
|
303
519
|
export function getUiGraphImageSource(value) {
|
|
304
520
|
if (typeof value !== 'string') {
|
|
305
521
|
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:
|
|
35
|
+
return coercedString != null ? [{ type: 'user', message: coercedString }] : [];
|
|
36
36
|
}
|
|
37
37
|
export function prependSystemPrompt(messages, systemPrompt) {
|
|
38
|
-
|
|
38
|
+
const systemMessage = coerceTypeOptional(systemPrompt, 'string');
|
|
39
|
+
if (!systemMessage) {
|
|
39
40
|
return messages;
|
|
40
41
|
}
|
|
41
|
-
|
|
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
|
}
|
|
@@ -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 =
|
|
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
|
-
|
|
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) {
|
|
@@ -18,9 +18,7 @@ function addUsage(accumulated, usage) {
|
|
|
18
18
|
totalTokens: accumulated.totalTokens + usage.totalTokens,
|
|
19
19
|
cachedTokens: accumulated.cachedTokens + usage.cachedTokens,
|
|
20
20
|
reasoningTokens: accumulated.reasoningTokens + usage.reasoningTokens,
|
|
21
|
-
totalCost: accumulated.totalCost == null || usage.totalCost == null
|
|
22
|
-
? undefined
|
|
23
|
-
: accumulated.totalCost + usage.totalCost,
|
|
21
|
+
totalCost: accumulated.totalCost == null || usage.totalCost == null ? undefined : accumulated.totalCost + usage.totalCost,
|
|
24
22
|
};
|
|
25
23
|
}
|
|
26
24
|
function applyAccumulatedUsage(result, usage, outputUsage) {
|
|
@@ -64,7 +62,7 @@ function applyAccumulatedReasoning(result, reasoningRounds, outputReasoning) {
|
|
|
64
62
|
}
|
|
65
63
|
}
|
|
66
64
|
export async function runChatV2PipelineWithToolContinuation(options) {
|
|
67
|
-
const { autoContinue, maxToolRounds, functions, delegateToolCall, runPipeline = runChatV2Pipeline, ...pipelineOptions } = options;
|
|
65
|
+
const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline = runChatV2Pipeline, ...pipelineOptions } = options;
|
|
68
66
|
const toolNames = getToolNames(functions);
|
|
69
67
|
const maxRounds = Math.max(1, Math.floor(Number.isFinite(maxToolRounds) ? maxToolRounds : 1));
|
|
70
68
|
let currentPrompt = pipelineOptions.prompt;
|
|
@@ -83,9 +81,7 @@ export async function runChatV2PipelineWithToolContinuation(options) {
|
|
|
83
81
|
if (autoContinue) {
|
|
84
82
|
appendReasoningRound(reasoningRounds, result.reasoning);
|
|
85
83
|
}
|
|
86
|
-
if (!autoContinue ||
|
|
87
|
-
completedRounds >= maxRounds ||
|
|
88
|
-
!canAutoContinue(result.functionCalls, toolNames)) {
|
|
84
|
+
if (!autoContinue || completedRounds >= maxRounds || !canAutoContinue(result.functionCalls, toolNames)) {
|
|
89
85
|
if (result.functionCalls.length === 0 && delegatedToolCalls.length > 0 && pipelineOptions.includeFunctionCalls) {
|
|
90
86
|
result.commonOutputs['function-calls'] = {
|
|
91
87
|
type: 'object[]',
|
|
@@ -98,7 +94,9 @@ export async function runChatV2PipelineWithToolContinuation(options) {
|
|
|
98
94
|
}
|
|
99
95
|
return result;
|
|
100
96
|
}
|
|
101
|
-
const toolResultMessages =
|
|
97
|
+
const toolResultMessages = delegateToolCallRound
|
|
98
|
+
? await delegateToolCallRound(result.functionCalls, result.response)
|
|
99
|
+
: await Promise.all(result.functionCalls.map(delegateToolCall));
|
|
102
100
|
delegatedToolCalls.push(...toolResultMessages
|
|
103
101
|
.map((message) => message.delegatedToolCall)
|
|
104
102
|
.filter((record) => record != null));
|